diff --git a/.gitignore b/.gitignore index c15a39c7..49d49a72 100644 --- a/.gitignore +++ b/.gitignore @@ -218,7 +218,6 @@ test-screenshots/ _blender/ # Web files (copied from comfy-3d-viewers and comfy-dynamic-widgets at startup) -web/ # Build system (now in comfy-3d-viewers package) build_vtk_bundle/ diff --git a/__init__.py b/__init__.py index 57109261..b498e1d4 100644 --- a/__init__.py +++ b/__init__.py @@ -62,5 +62,7 @@ except Exception as e: log.warning("[GeomPack] could not register /gpack/getpath: %s", e) -WEB_DIRECTORY = "./web" -__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS', 'WEB_DIRECTORY'] +# Frontend assets are declared in pyproject.toml ([tool.comfy] web = "javascript"), +# served at /extensions/comfyui-geometrypack/. No WEB_DIRECTORY attribute (it would +# double-register the dir under a second mount key). +__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS'] diff --git a/javascript/js/bvh_viewer.js b/javascript/js/bvh_viewer.js new file mode 100644 index 00000000..b7231fa9 --- /dev/null +++ b/javascript/js/bvh_viewer.js @@ -0,0 +1,258 @@ +/** + * BVH Viewer Widget - Interactive BVH skeleton animation viewer + * Displays skeletal animations in BVH format with Three.js + */ + +import { app } from "../../../../scripts/app.js"; + +console.log("[BVHViewer] Loading BVH Viewer extension"); + +// Node types that use this viewer +const BVH_VIEWER_NODES = [ + { + nodeName: "BVHViewer", + extensionName: "comfy3d.bvhviewer", + logPrefix: "[BVHViewer]" + } +]; + +function detectExtensionFolder() { + try { + if (typeof import.meta !== 'undefined' && import.meta.url) { + const match = import.meta.url.match(/\/extensions\/([^\/]+)\//); + if (match) return match[1]; + } + const scripts = document.getElementsByTagName('script'); + for (let i = scripts.length - 1; i >= 0; i--) { + const src = scripts[i].src; + if (src) { + const match = src.match(/\/extensions\/([^\/]+)\//); + if (match) return match[1]; + } + } + } catch (e) { + console.warn('[BVHViewer] Could not detect extension folder:', e); + } + return null; +} + +function getViewerUrl(extensionFolder) { + return `/extensions/${extensionFolder}/viewer_bvh.html?v=` + Date.now(); +} + +function createBVHViewerExtension(config) { + const { extensionName, nodeName, logPrefix } = config; + + console.log(`${logPrefix} Loading BVH viewer extension...`); + + const extensionFolder = detectExtensionFolder(); + if (!extensionFolder) { + console.error(`${logPrefix} Could not detect extension folder`); + return; + } + + app.registerExtension({ + name: extensionName, + + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name !== nodeName) return; + + console.log(`${logPrefix} Registering ${nodeName} node`); + + const onNodeCreated = nodeType.prototype.onNodeCreated; + + nodeType.prototype.onNodeCreated = function() { + const result = onNodeCreated?.apply(this, arguments); + + // Create container + const container = document.createElement("div"); + container.style.cssText = "position: relative; width: 100%; background: #222;"; + + // Create iframe for Three.js viewer + const iframe = document.createElement("iframe"); + iframe.style.cssText = "width: 100%; height: 600px; border: none; display: block; background: #1a1a1a;"; + iframe.src = getViewerUrl(extensionFolder); + container.appendChild(iframe); + + // Controls bar + const controlsBar = document.createElement("div"); + controlsBar.style.cssText = "display: flex; flex-wrap: wrap; gap: 10px; padding: 10px; background: #252525; align-items: center; border-top: 1px solid #333;"; + + // Play/Pause button + const playButton = document.createElement("button"); + playButton.textContent = "\u25B6"; + playButton.style.cssText = "width: 30px; height: 30px; border: none; border-radius: 4px; background: #4a9eff; color: white; font-size: 14px; cursor: pointer; flex-shrink: 0;"; + playButton.disabled = true; + controlsBar.appendChild(playButton); + + // Frame slider + const frameSlider = document.createElement("input"); + frameSlider.type = "range"; + frameSlider.min = 0; + frameSlider.max = 100; + frameSlider.value = 0; + frameSlider.disabled = true; + frameSlider.style.cssText = "flex-grow: 1; height: 6px; min-width: 100px;"; + controlsBar.appendChild(frameSlider); + + // Frame counter + const frameCounter = document.createElement("div"); + frameCounter.style.cssText = "padding: 4px 8px; background: rgba(0,0,0,0.3); color: #aaa; border-radius: 3px; font-size: 11px; font-family: monospace; min-width: 80px; text-align: center;"; + frameCounter.textContent = "0 / 0"; + controlsBar.appendChild(frameCounter); + + // Separator + const sep = document.createElement("div"); + sep.style.cssText = "width: 1px; height: 20px; background: #444; margin: 0 5px;"; + controlsBar.appendChild(sep); + + // Speed control container + const speedContainer = document.createElement("div"); + speedContainer.style.cssText = "display: flex; align-items: center; gap: 5px;"; + + const speedLabel = document.createElement("span"); + speedLabel.textContent = "Spd:"; + speedLabel.style.cssText = "color: #aaa; font-size: 11px;"; + speedContainer.appendChild(speedLabel); + + const speedSlider = document.createElement("input"); + speedSlider.type = "range"; + speedSlider.min = 0.1; + speedSlider.max = 2.0; + speedSlider.step = 0.1; + speedSlider.value = 1.0; + speedSlider.style.cssText = "width: 60px; height: 4px;"; + speedContainer.appendChild(speedSlider); + + const speedValue = document.createElement("span"); + speedValue.textContent = "1.0x"; + speedValue.style.cssText = "color: #fff; font-size: 11px; min-width: 30px;"; + speedContainer.appendChild(speedValue); + + controlsBar.appendChild(speedContainer); + container.appendChild(controlsBar); + + // State + this.bvhViewerState = { + iframe: iframe, + container: container, + playButton: playButton, + frameSlider: frameSlider, + frameCounter: frameCounter, + speedSlider: speedSlider, + speedValue: speedValue, + isPlaying: false, + currentFrame: 0, + totalFrames: 0, + bvhData: null, + viewerReady: false + }; + + // Add DOM widget + this.addDOMWidget("bvh_viewer", "customIframe", container); + + // Play button handler + playButton.onclick = () => { + const state = this.bvhViewerState; + state.isPlaying = !state.isPlaying; + playButton.textContent = state.isPlaying ? "\u23F8" : "\u25B6"; + iframe.contentWindow.postMessage({ + type: state.isPlaying ? 'play' : 'pause' + }, '*'); + }; + + // Frame slider handler + frameSlider.oninput = (e) => { + const frame = parseInt(e.target.value); + this.bvhViewerState.currentFrame = frame; + iframe.contentWindow.postMessage({ type: 'setFrame', frame: frame }, '*'); + }; + + // Speed slider handler + speedSlider.oninput = (e) => { + const speed = parseFloat(e.target.value); + speedValue.textContent = speed.toFixed(1) + 'x'; + iframe.contentWindow.postMessage({ type: 'setSpeed', speed: speed }, '*'); + }; + + // Listen for messages from iframe + const messageHandler = (event) => { + if (event.source !== iframe.contentWindow) return; + + const data = event.data; + const state = this.bvhViewerState; + + if (data.type === 'VIEWER_READY') { + state.viewerReady = true; + if (state.bvhData) { + this.loadBVHData(state.bvhData.bvhContent, state.bvhData.bvhInfo); + } + } else if (data.type === 'playing') { + state.isPlaying = true; + playButton.textContent = "\u23F8"; + } else if (data.type === 'paused') { + state.isPlaying = false; + playButton.textContent = "\u25B6"; + } else if (data.type === 'frameChanged') { + state.currentFrame = data.frame; + state.totalFrames = data.totalFrames; + frameSlider.value = data.frame; + frameCounter.textContent = `${data.frame} / ${data.totalFrames}`; + } else if (data.type === 'looped') { + state.currentFrame = 0; + frameSlider.value = 0; + } + }; + window.addEventListener('message', messageHandler); + + // Cleanup on removal + const originalOnRemoved = this.onRemoved; + this.onRemoved = function() { + window.removeEventListener('message', messageHandler); + if (originalOnRemoved) originalOnRemoved.apply(this, arguments); + }; + + // Handle data from backend + this.onExecuted = (message) => { + if (message?.bvh_content) { + const bvhContent = message.bvh_content[0]; + const bvhInfo = message.bvh_info ? message.bvh_info[0] : {}; + + this.bvhViewerState.bvhData = { bvhContent, bvhInfo }; + this.bvhViewerState.totalFrames = bvhInfo.num_frames || 0; + + playButton.disabled = false; + frameSlider.disabled = false; + frameSlider.max = this.bvhViewerState.totalFrames - 1; + frameCounter.textContent = `0 / ${this.bvhViewerState.totalFrames}`; + + if (this.bvhViewerState.viewerReady) { + this.loadBVHData(bvhContent, bvhInfo); + } + } + }; + + // Method to load BVH data into viewer + this.loadBVHData = function(bvhContent, bvhInfo) { + if (iframe.contentWindow) { + iframe.contentWindow.postMessage({ + type: 'loadBVH', + bvhContent: bvhContent, + bvhInfo: bvhInfo + }, '*'); + } + }; + + this.setSize([Math.max(400, this.size[0] || 400), 720]); + return result; + }; + } + }); + + console.log(`${logPrefix} Extension registered: ${extensionName}`); +} + +// Auto-register all known BVH viewer node types +BVH_VIEWER_NODES.forEach(config => createBVHViewerExtension(config)); + +export { createBVHViewerExtension, detectExtensionFolder }; diff --git a/javascript/js/compare_skeleton_widget.js b/javascript/js/compare_skeleton_widget.js new file mode 100644 index 00000000..0cc1fb21 --- /dev/null +++ b/javascript/js/compare_skeleton_widget.js @@ -0,0 +1,219 @@ +/** + * ComfyUI Compare Skeletons Widget + * + * Widget for UniRigCompareSkeletons node - displays two FBX skeletons side-by-side + * with synced camera rotation and cross-bone highlighting. + */ + +import { app } from "../../../../scripts/app.js"; +import { detectExtensionFolder, getViewerUrl } from "./mesh_preview_fbx.js"; + +console.log("[UniRig Compare] Loading compare skeleton widget..."); + +const extensionFolder = detectExtensionFolder(); +if (!extensionFolder) { + console.error("[UniRig Compare] Could not detect extension folder"); +} + +console.log("[UniRig Compare] Detected extension folder:", extensionFolder); + +app.registerExtension({ + name: "unirig.compareskeletons", + + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name === "CompareSkeletons" || nodeData.name === "UniRigCompareSkeletons") { + console.log("[UniRig Compare] Registering Compare Skeletons node"); + + const onNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function() { + const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined; + + console.log("[UniRig Compare] Node created, adding compare viewer widget"); + + // Create iframe for comparison viewer + const iframe = document.createElement("iframe"); + iframe.style.width = "100%"; + iframe.style.flex = "1 1 0"; + iframe.style.minHeight = "0"; + iframe.style.border = "none"; + iframe.style.backgroundColor = "#2a2a2a"; + + // Load viewer from file URL + const viewerUrl = getViewerUrl(extensionFolder, "viewer_fbx_compare.html"); + iframe.src = viewerUrl; + console.log("[UniRig Compare] Setting iframe src to:", viewerUrl); + + iframe.onload = () => { + console.log("[UniRig Compare] Iframe loaded successfully"); + }; + iframe.onerror = (e) => { + console.error("[UniRig Compare] Iframe failed to load:", e); + }; + + // Add widget + const widget = this.addDOMWidget("preview", "FBX_COMPARE_PREVIEW", iframe, { + getValue() { return ""; }, + setValue(v) { } + }); + + console.log("[UniRig Compare] Widget created:", widget); + + // Set widget size - wider for side-by-side view + widget.computeSize = function(width) { + const w = width || 800; + const h = w * 0.75; // Wider aspect ratio for dual view + return [w, h]; + }; + + widget.element = iframe; + + // Store iframe reference + this.compareViewerIframe = iframe; + this.compareViewerReady = false; + + // Listen for ready message from iframe + const onMessage = (event) => { + if (event.data && event.data.type === 'VIEWER_READY') { + console.log("[UniRig Compare] Viewer iframe is ready!"); + this.compareViewerReady = true; + } + }; + window.addEventListener('message', onMessage.bind(this)); + + const notifyIframeResize = () => { + if (iframe.contentWindow) { + const rect = iframe.getBoundingClientRect(); + iframe.contentWindow.postMessage({ + type: 'RESIZE', + width: rect.width, + height: rect.height + }, '*'); + } + }; + + this.onResize = function(size) { + const isVueNodes = iframe.closest('[data-node-id]') !== null || + document.querySelector('.vue-graph-canvas') !== null; + + if (!isVueNodes && size && size[1]) { + const nodeHeight = size[1]; + const headerHeight = 70; + const availableHeight = Math.max(200, nodeHeight - headerHeight); + iframe.style.height = availableHeight + 'px'; + } + + requestAnimationFrame(() => { + notifyIframeResize(); + }); + }; + + let resizeTimeout = null; + let lastSize = { width: 0, height: 0 }; + const resizeObserver = new ResizeObserver((entries) => { + const entry = entries[0]; + const newWidth = entry.contentRect.width; + const newHeight = entry.contentRect.height; + + if (Math.abs(newWidth - lastSize.width) < 1 && Math.abs(newHeight - lastSize.height) < 1) { + return; + } + lastSize = { width: newWidth, height: newHeight }; + + if (resizeTimeout) { + clearTimeout(resizeTimeout); + } + resizeTimeout = setTimeout(() => { + notifyIframeResize(); + }, 50); + }); + resizeObserver.observe(iframe); + + const originalOnRemoved = this.onRemoved; + this.onRemoved = function() { + resizeObserver.disconnect(); + if (resizeTimeout) { + clearTimeout(resizeTimeout); + } + window.removeEventListener('message', onMessage); + if (originalOnRemoved) { + originalOnRemoved.apply(this, arguments); + } + }; + + // Set initial node size (wider for dual view) + this.setSize([800, 600]); + + // Handle execution + const onExecuted = this.onExecuted; + this.onExecuted = function(message) { + console.log("[UniRig Compare] onExecuted called with message:", message); + onExecuted?.apply(this, arguments); + + // The message contains both FBX file paths + const leftFile = message?.fbx_file_left?.[0]; + const rightFile = message?.fbx_file_right?.[0]; + + if (leftFile || rightFile) { + console.log("[UniRig Compare] Loading FBX files - Left:", leftFile, "Right:", rightFile); + + // Build file paths + const buildFilepath = (filename) => { + if (!filename) return null; + if (!filename.includes('/') && !filename.includes('\\')) { + return `${window.location.origin}/view?filename=${encodeURIComponent(filename)}&type=output&subfolder=`; + } else { + const basename = filename.split(/[/\\]/).pop(); + return `${window.location.origin}/view?filename=${encodeURIComponent(basename)}&type=output&subfolder=`; + } + }; + + const filepathLeft = buildFilepath(leftFile); + const filepathRight = buildFilepath(rightFile); + + // Send message to iframe + const sendMessage = () => { + if (iframe.contentWindow) { + console.log("[UniRig Compare] Sending postMessage to iframe"); + iframe.contentWindow.postMessage({ + type: "LOAD_FBX_COMPARE", + filepathLeft: filepathLeft, + filepathRight: filepathRight, + timestamp: Date.now() + }, "*"); + } else { + console.error("[UniRig Compare] Iframe contentWindow not available"); + } + }; + + // Wait for iframe to be ready, or use timeout as fallback + if (this.compareViewerReady) { + sendMessage(); + } else { + const checkReady = setInterval(() => { + if (this.compareViewerReady) { + clearInterval(checkReady); + sendMessage(); + } + }, 50); + + // Fallback timeout after 2 seconds + setTimeout(() => { + clearInterval(checkReady); + if (!this.compareViewerReady) { + console.warn("[UniRig Compare] Iframe not ready after 2s, sending anyway"); + sendMessage(); + } + }, 2000); + } + } else { + console.log("[UniRig Compare] No FBX files in message data. Keys:", Object.keys(message || {})); + } + }; + + return r; + }; + } + } +}); + +console.log("[UniRig Compare] Compare skeleton widget registered"); diff --git a/javascript/js/compare_smpl_bvh.js b/javascript/js/compare_smpl_bvh.js new file mode 100644 index 00000000..0f821a41 --- /dev/null +++ b/javascript/js/compare_smpl_bvh.js @@ -0,0 +1,161 @@ +/** + * Compare SMPL to BVH Viewer Widget + * Side-by-side comparison of SMPL mesh and BVH skeleton using split view + */ + +import { app } from "../../../../scripts/app.js"; + +console.log("[CompareSMPLBVH] Loading Compare SMPL BVH extension"); + +// Node types that use this viewer +const COMPARE_VIEWER_NODES = [ + { + nodeName: "CompareSMPLtoBVH", + extensionName: "comfy3d.comparesmplbvh", + logPrefix: "[CompareSMPLBVH]", + smplMeshApiPath: "/motioncapture/smpl_mesh" + } +]; + +function detectExtensionFolder() { + try { + if (typeof import.meta !== 'undefined' && import.meta.url) { + const match = import.meta.url.match(/\/extensions\/([^\/]+)\//); + if (match) return match[1]; + } + const scripts = document.getElementsByTagName('script'); + for (let i = scripts.length - 1; i >= 0; i--) { + const src = scripts[i].src; + if (src) { + const match = src.match(/\/extensions\/([^\/]+)\//); + if (match) return match[1]; + } + } + } catch (e) { + console.warn('[CompareSMPLBVH] Could not detect extension folder:', e); + } + return null; +} + +function getViewerUrl(extensionFolder) { + return `/extensions/${extensionFolder}/viewer_compare_smpl_bvh.html?v=` + Date.now(); +} + +function createCompareViewerExtension(config) { + const { extensionName, nodeName, logPrefix, smplMeshApiPath } = config; + + console.log(`${logPrefix} Loading Compare SMPL BVH extension...`); + + const extensionFolder = detectExtensionFolder(); + if (!extensionFolder) { + console.error(`${logPrefix} Could not detect extension folder`); + return; + } + + app.registerExtension({ + name: extensionName, + + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name !== nodeName) return; + + console.log(`${logPrefix} Registering ${nodeName} node`); + + const onNodeCreated = nodeType.prototype.onNodeCreated; + + nodeType.prototype.onNodeCreated = function() { + const result = onNodeCreated?.apply(this, arguments); + + const container = document.createElement("div"); + container.style.width = "100%"; + container.style.height = "100%"; + container.style.background = "#222"; + container.style.display = "flex"; + container.style.flexDirection = "column"; + + const iframe = document.createElement("iframe"); + iframe.style.width = "100%"; + iframe.style.height = "100%"; + iframe.style.border = "none"; + iframe.style.flexGrow = "1"; + iframe.src = getViewerUrl(extensionFolder); + container.appendChild(iframe); + + // Store references + this.compareViewerIframe = iframe; + this.compareViewerReady = false; + this.compareDataToLoad = null; + + // Add widget with computeSize for automatic resizing + const widget = this.addDOMWidget("compare_viewer", "iframe", container); + widget.computeSize = (w) => [w, 500]; + + // Set an initial size for the node + this.setSize([this.size[0], 500 + 30]); + + // Listen for viewer ready message + const messageHandler = (event) => { + if (event.source !== iframe.contentWindow) return; + if (event.data.type === 'VIEWER_READY') { + this.compareViewerReady = true; + if (this.compareDataToLoad) { + this.loadCompareData(this.compareDataToLoad); + } + } + }; + window.addEventListener('message', messageHandler); + + // Cleanup on removal + const originalOnRemoved = this.onRemoved; + this.onRemoved = function() { + window.removeEventListener('message', messageHandler); + if (originalOnRemoved) originalOnRemoved.apply(this, arguments); + }; + + // Method to load compare data + this.loadCompareData = function(data) { + if (!iframe.contentWindow) { + this.compareDataToLoad = data; + return; + } + + if (!this.compareViewerReady) { + this.compareDataToLoad = data; + return; + } + + iframe.contentWindow.postMessage({ + type: 'loadData', + smplFilename: data.smplFilename, + bvhContent: data.bvhContent, + smplMeshApiPath: smplMeshApiPath + }, '*'); + this.compareDataToLoad = null; + }; + + this.onExecuted = (msg) => { + if (msg?.smpl_mesh_filename && msg?.bvh_content) { + const data = { + smplFilename: msg.smpl_mesh_filename[0], + bvhContent: msg.bvh_content[0] + }; + + if (this.compareViewerReady) { + this.loadCompareData(data); + } else { + this.compareDataToLoad = data; + } + } + }; + + return result; + }; + } + }); + + console.log(`${logPrefix} Extension registered: ${extensionName}`); +} + +// Auto-register all known compare viewer node types +COMPARE_VIEWER_NODES.forEach(config => createCompareViewerExtension(config)); + +export { createCompareViewerExtension, detectExtensionFolder }; diff --git a/javascript/js/debug_skeleton_widget.js b/javascript/js/debug_skeleton_widget.js new file mode 100644 index 00000000..d63b2090 --- /dev/null +++ b/javascript/js/debug_skeleton_widget.js @@ -0,0 +1,10 @@ +import { createFBXPreviewExtension } from "./mesh_preview_fbx.js"; + +// Register UniRigDebugSkeleton with the debug viewer +createFBXPreviewExtension({ + nodeName: "UniRigDebugSkeleton", + extensionName: "unirig.debugskeleton", + logPrefix: "[UniRig Debug]", + fbxExportApiPath: "/unirig/export_posed_fbx", + viewerFile: "viewer_fbx_debug.html" +}); diff --git a/javascript/js/fbx_animation_viewer.js b/javascript/js/fbx_animation_viewer.js new file mode 100644 index 00000000..ab2f9cd7 --- /dev/null +++ b/javascript/js/fbx_animation_viewer.js @@ -0,0 +1,315 @@ +/** + * FBX Animation Viewer Widget - Interactive animation playback with Three.js + * Controls animation playback, speed, looping, and skeleton visibility + */ + +import { app } from "../../../../scripts/app.js"; + +console.log("[FBXAnimationViewer] Loading FBX Animation Viewer extension"); + +// Node types that use this viewer +const FBX_ANIMATION_NODES = [ + { + nodeName: "FBXAnimationViewer", + extensionName: "comfy3d.fbxanimationviewer", + logPrefix: "[FBXAnimationViewer]" + } +]; + +function detectExtensionFolder() { + try { + if (typeof import.meta !== 'undefined' && import.meta.url) { + const match = import.meta.url.match(/\/extensions\/([^\/]+)\//); + if (match) return match[1]; + } + const scripts = document.getElementsByTagName('script'); + for (let i = scripts.length - 1; i >= 0; i--) { + const src = scripts[i].src; + if (src) { + const match = src.match(/\/extensions\/([^\/]+)\//); + if (match) return match[1]; + } + } + } catch (e) { + console.warn('[FBXAnimationViewer] Could not detect extension folder:', e); + } + return null; +} + +function getViewerUrl(extensionFolder) { + return `/extensions/${extensionFolder}/viewer_fbx_animation.html?v=` + Date.now(); +} + +function createFBXAnimationViewerExtension(config) { + const { extensionName, nodeName, logPrefix } = config; + + console.log(`${logPrefix} Loading FBX Animation Viewer extension...`); + + const extensionFolder = detectExtensionFolder(); + if (!extensionFolder) { + console.error(`${logPrefix} Could not detect extension folder`); + return; + } + + app.registerExtension({ + name: extensionName, + + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name !== nodeName) return; + + console.log(`${logPrefix} Registering ${nodeName} node`); + + const onNodeCreated = nodeType.prototype.onNodeCreated; + + nodeType.prototype.onNodeCreated = function() { + const result = onNodeCreated?.apply(this, arguments); + + // Main Container + const mainContainer = document.createElement("div"); + mainContainer.style.cssText = "width: 100%; height: 100%; display: flex; flex-direction: column; overflow: hidden; background: #1a1a1a; border: 1px solid #444; box-sizing: border-box;"; + + // Viewer Area (Iframe) + const viewerArea = document.createElement("div"); + viewerArea.style.cssText = "position: relative; flex-grow: 1; min-height: 200px; overflow: hidden;"; + + const iframe = document.createElement("iframe"); + iframe.style.cssText = "display: block; width: 100%; height: 100%; border: none;"; + iframe.src = getViewerUrl(extensionFolder); + + viewerArea.appendChild(iframe); + mainContainer.appendChild(viewerArea); + + // Controls Area + const controlsContainer = document.createElement("div"); + controlsContainer.style.cssText = "flex-shrink: 0; background: #2a2a2a; border-top: 1px solid #444; padding: 10px; box-sizing: border-box; color: white; font-size: 12px; font-family: Arial, sans-serif;"; + + controlsContainer.innerHTML = ` +
+ + +
+ +
+ +
+ 0 / 0 + 0.00s +
+
+ +
+ + +
+ +
+ + + + +
+ + + `; + + mainContainer.appendChild(controlsContainer); + + // Add Single Widget + const widget = this.addDOMWidget("fbx_viewer_unified", "main", mainContainer, { + serialize: false, + hideOnZoom: false + }); + + widget.computeSize = (width) => [width, 500]; + + // Get control elements + const playPauseBtn = controlsContainer.querySelector('#playPauseBtn'); + const resetBtn = controlsContainer.querySelector('#resetBtn'); + const timeline = controlsContainer.querySelector('#timeline'); + const speedControl = controlsContainer.querySelector('#speedControl'); + const loopCheckbox = controlsContainer.querySelector('#loop'); + const animationSelect = controlsContainer.querySelector('#animationSelect'); + const showSkeleton = controlsContainer.querySelector('#showSkeleton'); + const showMesh = controlsContainer.querySelector('#showMesh'); + const xraySkeleton = controlsContainer.querySelector('#xraySkeleton'); + const resetCamera = controlsContainer.querySelector('#resetCamera'); + const currentTimeEl = controlsContainer.querySelector('#currentTime'); + const currentFrameEl = controlsContainer.querySelector('#currentFrame'); + const totalFramesEl = controlsContainer.querySelector('#totalFrames'); + + // Store references + this.animationViewerIframe = iframe; + this.animationViewerReady = false; + this.animationControls = { + playPauseBtn, resetBtn, timeline, speedControl, loopCheckbox, animationSelect, + showSkeleton, showMesh, xraySkeleton, resetCamera, + currentTimeEl, currentFrameEl, totalFramesEl + }; + + // Wire up controls + playPauseBtn.addEventListener('click', () => { + iframe.contentWindow.postMessage({ type: 'PLAY_PAUSE' }, '*'); + }); + + resetBtn.addEventListener('click', () => { + iframe.contentWindow.postMessage({ type: 'RESET' }, '*'); + }); + + timeline.addEventListener('input', (e) => { + const progress = parseFloat(e.target.value) / 100; + iframe.contentWindow.postMessage({ type: 'SET_TIMELINE', progress }, '*'); + }); + + speedControl.addEventListener('change', (e) => { + iframe.contentWindow.postMessage({ type: 'SET_SPEED', speed: parseFloat(e.target.value) }, '*'); + }); + + loopCheckbox.addEventListener('change', (e) => { + iframe.contentWindow.postMessage({ type: 'SET_LOOP', loop: e.target.checked }, '*'); + }); + + animationSelect.addEventListener('change', (e) => { + iframe.contentWindow.postMessage({ type: 'CHANGE_ANIMATION', index: parseInt(e.target.value) }, '*'); + }); + + showSkeleton.addEventListener('change', (e) => { + iframe.contentWindow.postMessage({ type: 'TOGGLE_SKELETON', visible: e.target.checked }, '*'); + }); + + showMesh.addEventListener('change', (e) => { + iframe.contentWindow.postMessage({ type: 'TOGGLE_MESH', visible: e.target.checked }, '*'); + }); + + xraySkeleton.addEventListener('change', (e) => { + iframe.contentWindow.postMessage({ type: 'TOGGLE_XRAY', xray: e.target.checked }, '*'); + }); + + resetCamera.addEventListener('click', () => { + iframe.contentWindow.postMessage({ type: 'RESET_CAMERA' }, '*'); + }); + + // Listen for messages from iframe + const messageHandler = (event) => { + if (event.source !== iframe.contentWindow) return; + + const { type, ...data } = event.data; + + switch(type) { + case 'VIEWER_READY': + this.animationViewerReady = true; + if (this.fbxPathToLoad) { + this.loadAnimationInViewer(this.fbxPathToLoad); + } + break; + + case 'ANIMATIONS_LOADED': + animationSelect.innerHTML = ''; + data.animations.forEach(anim => { + const option = document.createElement('option'); + option.value = anim.index; + option.textContent = anim.name; + animationSelect.appendChild(option); + }); + + playPauseBtn.disabled = false; + resetBtn.disabled = false; + timeline.disabled = false; + speedControl.disabled = false; + loopCheckbox.disabled = false; + animationSelect.disabled = data.animations.length <= 1; + break; + + case 'TIME_UPDATE': + if (currentTimeEl) currentTimeEl.textContent = data.time.toFixed(2) + 's'; + if (currentFrameEl) currentFrameEl.textContent = data.frame; + if (totalFramesEl) totalFramesEl.textContent = data.totalFrames; + timeline.value = data.progress; + break; + + case 'PLAY_STATE_CHANGED': + playPauseBtn.textContent = data.isPlaying ? '\u23F8 Pause' : '\u25B6 Play'; + break; + + case 'ANIMATION_CHANGED': + const fps = 30; + if (totalFramesEl) totalFramesEl.textContent = Math.floor(data.duration * fps); + playPauseBtn.textContent = '\u23F8 Pause'; + break; + + case 'NO_ANIMATIONS': + playPauseBtn.textContent = 'No Animation'; + playPauseBtn.disabled = true; + break; + } + }; + window.addEventListener('message', messageHandler); + + // Cleanup on removal + const originalOnRemoved = this.onRemoved; + this.onRemoved = function() { + window.removeEventListener('message', messageHandler); + if (originalOnRemoved) originalOnRemoved.apply(this, arguments); + }; + + // Set initial node size + const nodeWidth = Math.max(512, this.size[0] || 512); + this.setSize([nodeWidth, 500]); + + return result; + }; + + // Add method to load FBX + nodeType.prototype.loadAnimationInViewer = function(fbxPath) { + if (!this.animationViewerIframe || !this.animationViewerIframe.contentWindow) { + this.fbxPathToLoad = fbxPath; + return; + } + + if (!this.animationViewerReady) { + this.fbxPathToLoad = fbxPath; + return; + } + + let relativePath = fbxPath; + if (fbxPath.includes('/output/')) { + relativePath = fbxPath.split('/output/')[1]; + } else if (fbxPath.includes('/input/')) { + relativePath = fbxPath.split('/input/')[1]; + } else { + relativePath = fbxPath.split('/').pop(); + } + + const viewPath = window.location.origin + "/view?filename=" + encodeURIComponent(relativePath); + + this.animationViewerIframe.contentWindow.postMessage({ + type: 'LOAD_FBX', + path: viewPath + }, '*'); + this.fbxPathToLoad = null; + }; + + // Override onExecuted to load FBX + const onExecuted = nodeType.prototype.onExecuted; + nodeType.prototype.onExecuted = function(message) { + if (onExecuted) onExecuted.apply(this, arguments); + + if (message?.fbx_path?.[0]) { + const fbxPath = message.fbx_path[0]; + this.loadAnimationInViewer(fbxPath); + } + }; + } + }); + + console.log(`${logPrefix} Extension registered: ${extensionName}`); +} + +// Auto-register all known FBX animation viewer node types +FBX_ANIMATION_NODES.forEach(config => createFBXAnimationViewerExtension(config)); + +export { createFBXAnimationViewerExtension, detectExtensionFolder }; diff --git a/javascript/js/gaussian_preview.js b/javascript/js/gaussian_preview.js new file mode 100644 index 00000000..b2e6a12b --- /dev/null +++ b/javascript/js/gaussian_preview.js @@ -0,0 +1,249 @@ +/** + * ComfyUI GeomPack - Gaussian Splat Preview Widget + * Interactive 3D Gaussian Splatting viewer using gsplat.js + */ + +import { app } from "../../../scripts/app.js"; + +// Auto-detect extension folder name (handles ComfyUI-GeometryPack or comfyui-geometrypack) +const EXTENSION_FOLDER = (() => { + const url = import.meta.url; + const match = url.match(/\/extensions\/([^/]+)\//); + return match ? match[1] : "ComfyUI-GeometryPack"; +})(); + +console.log("[GeomPack Gaussian] Loading extension..."); + +app.registerExtension({ + name: "geompack.gaussianpreview", + + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name === "GeomPackPreviewGaussian") { + console.log("[GeomPack Gaussian] Registering Preview Gaussian node"); + + const onNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function() { + const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined; + + // Create container for viewer + info panel + const container = document.createElement("div"); + container.style.width = "100%"; + container.style.height = "100%"; + container.style.display = "flex"; + container.style.flexDirection = "column"; + container.style.backgroundColor = "#1a1a1a"; + container.style.overflow = "hidden"; + + // Create iframe for gsplat.js viewer + const iframe = document.createElement("iframe"); + iframe.style.width = "100%"; + iframe.style.flex = "1 1 0"; + iframe.style.minHeight = "0"; + iframe.style.border = "none"; + iframe.style.backgroundColor = "#1a1a1a"; + + // Point to gsplat.js HTML viewer (with cache buster) + iframe.src = `/extensions/${EXTENSION_FOLDER}/viewer_gaussian.html?v=` + Date.now(); + + // Create info panel + const infoPanel = document.createElement("div"); + infoPanel.style.backgroundColor = "#1a1a1a"; + infoPanel.style.borderTop = "1px solid #444"; + infoPanel.style.padding = "6px 12px"; + infoPanel.style.fontSize = "10px"; + infoPanel.style.fontFamily = "monospace"; + infoPanel.style.color = "#ccc"; + infoPanel.style.lineHeight = "1.3"; + infoPanel.style.flexShrink = "0"; + infoPanel.style.overflow = "hidden"; + infoPanel.innerHTML = 'Gaussian splat info will appear here after execution'; + + // Add iframe and info panel to container + container.appendChild(iframe); + container.appendChild(infoPanel); + + // Add widget with required options + const widget = this.addDOMWidget("preview_gaussian", "GAUSSIAN_PREVIEW", container, { + getValue() { return ""; }, + setValue(v) { } + }); + + // Store reference to node for dynamic resizing + const node = this; + let currentNodeSize = [512, 580]; + + widget.computeSize = () => currentNodeSize; + + // Store references + this.gaussianViewerIframe = iframe; + this.gaussianInfoPanel = infoPanel; + + // Function to resize node dynamically + this.resizeToAspectRatio = function(imageWidth, imageHeight) { + const aspectRatio = imageWidth / imageHeight; + const nodeWidth = 512; + const viewerHeight = Math.round(nodeWidth / aspectRatio); + const nodeHeight = viewerHeight + 60; // Add space for info panel + + currentNodeSize = [nodeWidth, nodeHeight]; + node.setSize(currentNodeSize); + node.setDirtyCanvas(true, true); + app.graph.setDirtyCanvas(true, true); + + console.log("[GeomPack Gaussian] Resized node to:", nodeWidth, "x", nodeHeight, "(aspect ratio:", aspectRatio.toFixed(2), ")"); + }; + + // Track iframe load state + let iframeLoaded = false; + iframe.addEventListener('load', () => { + iframeLoaded = true; + }); + + // Listen for messages from iframe + window.addEventListener('message', async (event) => { + // Handle screenshot messages + if (event.data.type === 'SCREENSHOT' && event.data.image) { + try { + // Convert base64 data URL to blob + const base64Data = event.data.image.split(',')[1]; + const byteString = atob(base64Data); + const arrayBuffer = new ArrayBuffer(byteString.length); + const uint8Array = new Uint8Array(arrayBuffer); + + for (let i = 0; i < byteString.length; i++) { + uint8Array[i] = byteString.charCodeAt(i); + } + + const blob = new Blob([uint8Array], { type: 'image/png' }); + + // Generate filename with timestamp + const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); + const filename = `gaussian-screenshot-${timestamp}.png`; + + // Create FormData for upload + const formData = new FormData(); + formData.append('image', blob, filename); + formData.append('type', 'output'); + formData.append('subfolder', ''); + + // Upload to ComfyUI backend + const response = await fetch('/upload/image', { + method: 'POST', + body: formData + }); + + if (response.ok) { + const result = await response.json(); + console.log('[GeomPack Gaussian] Screenshot saved:', result.name); + } else { + throw new Error(`Upload failed: ${response.status}`); + } + + } catch (error) { + console.error('[GeomPack Gaussian] Error saving screenshot:', error); + } + } + // Handle copy image to clipboard messages + else if (event.data.type === 'COPY_IMAGE' && event.data.success) { + console.log('[GeomPack Gaussian] Image copied to clipboard successfully'); + } + else if (event.data.type === 'COPY_IMAGE' && !event.data.success) { + console.error('[GeomPack Gaussian] Failed to copy image to clipboard:', event.data.error); + } + // Handle error messages from iframe + else if (event.data.type === 'MESH_ERROR' && event.data.error) { + console.error('[GeomPack Gaussian] Error from viewer:', event.data.error); + if (infoPanel) { + infoPanel.innerHTML = `
Error: ${event.data.error}
`; + } + } + }); + + // Set initial node size + this.setSize([512, 580]); + + // Handle execution + const onExecuted = this.onExecuted; + this.onExecuted = function(message) { + console.log("[GeomPack Gaussian] onExecuted called with:", message); + onExecuted?.apply(this, arguments); + + // Check for errors + if (message?.error && message.error[0]) { + infoPanel.innerHTML = `
Error: ${message.error[0]}
`; + return; + } + + // The message IS the UI data (not message.ui) + if (message?.ply_file && message.ply_file[0]) { + const filename = message.ply_file[0]; + const displayName = message.filename?.[0] || filename; + const fileSizeMb = message.file_size_mb?.[0] || 'N/A'; + + // Extract camera parameters if provided + const extrinsics = message.extrinsics?.[0] || null; + const intrinsics = message.intrinsics?.[0] || null; + + // Resize node to match image aspect ratio from intrinsics + if (intrinsics && intrinsics[0] && intrinsics[1]) { + const imageWidth = intrinsics[0][2] * 2; // cx * 2 + const imageHeight = intrinsics[1][2] * 2; // cy * 2 + this.resizeToAspectRatio(imageWidth, imageHeight); + } + + // Update info panel + infoPanel.innerHTML = ` +
+ File: + ${displayName} + Size: + ${fileSizeMb} MB +
+ `; + + // ComfyUI serves files via /view API — parse type/subfolder/filename + // Handles both absolute (/home/.../output/sub/file) and relative (output/sub/file) paths + let filepath; + const normalized = filename.replace(/\\/g, '/'); + const pathMatch = normalized.match(/(?:^|\/)(output|input|temp)\/(.+)$/); + if (pathMatch) { + const [, type, relPath] = pathMatch; + const parts = relPath.split('/'); + const fname = parts.pop(); + const subfolder = parts.join('/'); + filepath = `/view?filename=${encodeURIComponent(fname)}&type=${type}&subfolder=${encodeURIComponent(subfolder)}`; + } else { + // Fallback: use just the basename + const basename = normalized.split('/').pop(); + filepath = `/view?filename=${encodeURIComponent(basename)}&type=output&subfolder=`; + } + + // Send URL to iframe — gsplat.js fetches directly with streaming + const sendUrl = () => { + if (!iframe.contentWindow) { + console.error("[GeomPack Gaussian] Iframe contentWindow not available"); + return; + } + iframe.contentWindow.postMessage({ + type: "LOAD_MESH_URL", + url: filepath, + filename: filename, + extrinsics: extrinsics, + intrinsics: intrinsics, + timestamp: Date.now() + }, "*"); + }; + + if (iframeLoaded) { + sendUrl(); + } else { + setTimeout(sendUrl, 500); + } + } + }; + + return r; + }; + } + } +}); diff --git a/javascript/js/gsplat-bundle.js b/javascript/js/gsplat-bundle.js new file mode 100644 index 00000000..759a2207 --- /dev/null +++ b/javascript/js/gsplat-bundle.js @@ -0,0 +1,2482 @@ +var GSPLAT = (() => { + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + + // gsplat-entry.js + var gsplat_entry_exports = {}; + __export(gsplat_entry_exports, { + Camera: () => wt, + CameraData: () => Rt, + Color32: () => dt, + FPSControls: () => Gt, + FadeInPass: () => Nt, + IntersectionTester: () => Kt, + Loader: () => Tt, + Matrix3: () => _, + Matrix4: () => K, + Object3D: () => st, + OrbitControls: () => Lt, + PLYLoader: () => bt, + Plane: () => vt, + Quaternion: () => y, + RenderData: () => Ut, + RenderProgram: () => Ct, + Scene: () => kt, + ShaderPass: () => _t, + ShaderProgram: () => lt, + Splat: () => X, + SplatData: () => Y, + Splatv: () => tt, + SplatvData: () => ot, + SplatvLoader: () => xt, + Vector3: () => R, + Vector4: () => z, + VideoRenderProgram: () => Yt, + WebGLRenderer: () => Mt + }); + + // node_modules/gsplat/dist/index.es.js + var import_meta = {}; + var R = class _R { + constructor(t = 0, n = 0, i = 0) { + this.x = t, this.y = n, this.z = i; + } + equals(t) { + return !(this.x !== t.x || this.y !== t.y || this.z !== t.z); + } + add(t) { + return typeof t == "number" ? new _R(this.x + t, this.y + t, this.z + t) : new _R(this.x + t.x, this.y + t.y, this.z + t.z); + } + subtract(t) { + return typeof t == "number" ? new _R(this.x - t, this.y - t, this.z - t) : new _R(this.x - t.x, this.y - t.y, this.z - t.z); + } + multiply(t) { + return typeof t == "number" ? new _R(this.x * t, this.y * t, this.z * t) : t instanceof _R ? new _R(this.x * t.x, this.y * t.y, this.z * t.z) : new _R( + this.x * t.buffer[0] + this.y * t.buffer[4] + this.z * t.buffer[8] + t.buffer[12], + this.x * t.buffer[1] + this.y * t.buffer[5] + this.z * t.buffer[9] + t.buffer[13], + this.x * t.buffer[2] + this.y * t.buffer[6] + this.z * t.buffer[10] + t.buffer[14] + ); + } + divide(t) { + return typeof t == "number" ? new _R(this.x / t, this.y / t, this.z / t) : new _R(this.x / t.x, this.y / t.y, this.z / t.z); + } + cross(t) { + const n = this.y * t.z - this.z * t.y, i = this.z * t.x - this.x * t.z, e = this.x * t.y - this.y * t.x; + return new _R(n, i, e); + } + dot(t) { + return this.x * t.x + this.y * t.y + this.z * t.z; + } + lerp(t, n) { + return new _R(this.x + (t.x - this.x) * n, this.y + (t.y - this.y) * n, this.z + (t.z - this.z) * n); + } + min(t) { + return new _R(Math.min(this.x, t.x), Math.min(this.y, t.y), Math.min(this.z, t.z)); + } + max(t) { + return new _R(Math.max(this.x, t.x), Math.max(this.y, t.y), Math.max(this.z, t.z)); + } + getComponent(t) { + switch (t) { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + default: + throw new Error(`Invalid component index: ${t}`); + } + } + minComponent() { + return this.x < this.y && this.x < this.z ? 0 : this.y < this.z ? 1 : 2; + } + maxComponent() { + return this.x > this.y && this.x > this.z ? 0 : this.y > this.z ? 1 : 2; + } + magnitude() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); + } + distanceTo(t) { + return Math.sqrt((this.x - t.x) ** 2 + (this.y - t.y) ** 2 + (this.z - t.z) ** 2); + } + normalize() { + const t = this.magnitude(); + return new _R(this.x / t, this.y / t, this.z / t); + } + flat() { + return [this.x, this.y, this.z]; + } + clone() { + return new _R(this.x, this.y, this.z); + } + toString() { + return `[${this.flat().join(", ")}]`; + } + static One(t = 1) { + return new _R(t, t, t); + } + }; + var y = class _y { + constructor(t = 0, n = 0, i = 0, e = 1) { + this.x = t, this.y = n, this.z = i, this.w = e; + } + equals(t) { + return !(this.x !== t.x || this.y !== t.y || this.z !== t.z || this.w !== t.w); + } + normalize() { + const t = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); + return new _y(this.x / t, this.y / t, this.z / t, this.w / t); + } + multiply(t) { + const n = this.w, i = this.x, e = this.y, A = this.z, o = t.w, s = t.x, r = t.y, Q = t.z; + return new _y( + n * s + i * o + e * Q - A * r, + n * r - i * Q + e * o + A * s, + n * Q + i * r - e * s + A * o, + n * o - i * s - e * r - A * Q + ); + } + inverse() { + const t = this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + return new _y(-this.x / t, -this.y / t, -this.z / t, this.w / t); + } + apply(t) { + const n = new _y(t.x, t.y, t.z, 0), i = new _y(-this.x, -this.y, -this.z, this.w), e = this.multiply(n).multiply(i); + return new R(e.x, e.y, e.z); + } + flat() { + return [this.x, this.y, this.z, this.w]; + } + clone() { + return new _y(this.x, this.y, this.z, this.w); + } + static FromEuler(t) { + const n = t.x / 2, i = t.y / 2, e = t.z / 2, A = Math.cos(i), o = Math.sin(i), s = Math.cos(n), r = Math.sin(n), Q = Math.cos(e), I = Math.sin(e); + return new _y( + A * r * Q + o * s * I, + o * s * Q - A * r * I, + A * s * I - o * r * Q, + A * s * Q + o * r * I + ); + } + toEuler() { + const t = 2 * (this.w * this.x + this.y * this.z), n = 1 - 2 * (this.x * this.x + this.y * this.y), i = Math.atan2(t, n); + let e; + const A = 2 * (this.w * this.y - this.z * this.x); + Math.abs(A) >= 1 ? e = Math.sign(A) * Math.PI / 2 : e = Math.asin(A); + const o = 2 * (this.w * this.z + this.x * this.y), s = 1 - 2 * (this.y * this.y + this.z * this.z), r = Math.atan2(o, s); + return new R(i, e, r); + } + static FromMatrix3(t) { + const n = t.buffer, i = n[0] + n[4] + n[8]; + let e, A, o, s; + if (i > 0) { + const r = 0.5 / Math.sqrt(i + 1); + s = 0.25 / r, e = (n[7] - n[5]) * r, A = (n[2] - n[6]) * r, o = (n[3] - n[1]) * r; + } else if (n[0] > n[4] && n[0] > n[8]) { + const r = 2 * Math.sqrt(1 + n[0] - n[4] - n[8]); + s = (n[7] - n[5]) / r, e = 0.25 * r, A = (n[1] + n[3]) / r, o = (n[2] + n[6]) / r; + } else if (n[4] > n[8]) { + const r = 2 * Math.sqrt(1 + n[4] - n[0] - n[8]); + s = (n[2] - n[6]) / r, e = (n[1] + n[3]) / r, A = 0.25 * r, o = (n[5] + n[7]) / r; + } else { + const r = 2 * Math.sqrt(1 + n[8] - n[0] - n[4]); + s = (n[3] - n[1]) / r, e = (n[2] + n[6]) / r, A = (n[5] + n[7]) / r, o = 0.25 * r; + } + return new _y(e, A, o, s); + } + static FromAxisAngle(t, n) { + const i = n / 2, e = Math.sin(i), A = Math.cos(i); + return new _y(t.x * e, t.y * e, t.z * e, A); + } + static LookRotation(t) { + const n = new R(0, 0, 1), i = n.dot(t); + if (Math.abs(i - -1) < 1e-6) + return new _y(0, 1, 0, Math.PI); + if (Math.abs(i - 1) < 1e-6) + return new _y(); + const e = Math.acos(i), A = n.cross(t).normalize(); + return _y.FromAxisAngle(A, e); + } + toString() { + return `[${this.flat().join(", ")}]`; + } + }; + var Ft = class { + constructor() { + const t = /* @__PURE__ */ new Map(); + this.addEventListener = (n, i) => { + t.has(n) || t.set(n, /* @__PURE__ */ new Set()), t.get(n).add(i); + }, this.removeEventListener = (n, i) => { + t.has(n) && t.get(n).delete(i); + }, this.hasEventListener = (n, i) => t.has(n) ? t.get(n).has(i) : false, this.dispatchEvent = (n) => { + if (t.has(n.type)) + for (const i of t.get(n.type)) + i(n); + }; + } + }; + var K = class _K { + // prettier-ignore + constructor(t = 1, n = 0, i = 0, e = 0, A = 0, o = 1, s = 0, r = 0, Q = 0, I = 0, d = 1, a = 0, U = 0, F = 0, g = 0, B = 1) { + this.buffer = [ + t, + n, + i, + e, + A, + o, + s, + r, + Q, + I, + d, + a, + U, + F, + g, + B + ]; + } + equals(t) { + if (this.buffer.length !== t.buffer.length) + return false; + if (this.buffer === t.buffer) + return true; + for (let n = 0; n < this.buffer.length; n++) + if (this.buffer[n] !== t.buffer[n]) + return false; + return true; + } + multiply(t) { + const n = this.buffer, i = t.buffer; + return new _K( + i[0] * n[0] + i[1] * n[4] + i[2] * n[8] + i[3] * n[12], + i[0] * n[1] + i[1] * n[5] + i[2] * n[9] + i[3] * n[13], + i[0] * n[2] + i[1] * n[6] + i[2] * n[10] + i[3] * n[14], + i[0] * n[3] + i[1] * n[7] + i[2] * n[11] + i[3] * n[15], + i[4] * n[0] + i[5] * n[4] + i[6] * n[8] + i[7] * n[12], + i[4] * n[1] + i[5] * n[5] + i[6] * n[9] + i[7] * n[13], + i[4] * n[2] + i[5] * n[6] + i[6] * n[10] + i[7] * n[14], + i[4] * n[3] + i[5] * n[7] + i[6] * n[11] + i[7] * n[15], + i[8] * n[0] + i[9] * n[4] + i[10] * n[8] + i[11] * n[12], + i[8] * n[1] + i[9] * n[5] + i[10] * n[9] + i[11] * n[13], + i[8] * n[2] + i[9] * n[6] + i[10] * n[10] + i[11] * n[14], + i[8] * n[3] + i[9] * n[7] + i[10] * n[11] + i[11] * n[15], + i[12] * n[0] + i[13] * n[4] + i[14] * n[8] + i[15] * n[12], + i[12] * n[1] + i[13] * n[5] + i[14] * n[9] + i[15] * n[13], + i[12] * n[2] + i[13] * n[6] + i[14] * n[10] + i[15] * n[14], + i[12] * n[3] + i[13] * n[7] + i[14] * n[11] + i[15] * n[15] + ); + } + clone() { + const t = this.buffer; + return new _K( + t[0], + t[1], + t[2], + t[3], + t[4], + t[5], + t[6], + t[7], + t[8], + t[9], + t[10], + t[11], + t[12], + t[13], + t[14], + t[15] + ); + } + determinant() { + const t = this.buffer; + return t[12] * t[9] * t[6] * t[3] - t[8] * t[13] * t[6] * t[3] - t[12] * t[5] * t[10] * t[3] + t[4] * t[13] * t[10] * t[3] + t[8] * t[5] * t[14] * t[3] - t[4] * t[9] * t[14] * t[3] - t[12] * t[9] * t[2] * t[7] + t[8] * t[13] * t[2] * t[7] + t[12] * t[1] * t[10] * t[7] - t[0] * t[13] * t[10] * t[7] - t[8] * t[1] * t[14] * t[7] + t[0] * t[9] * t[14] * t[7] + t[12] * t[5] * t[2] * t[11] - t[4] * t[13] * t[2] * t[11] - t[12] * t[1] * t[6] * t[11] + t[0] * t[13] * t[6] * t[11] + t[4] * t[1] * t[14] * t[11] - t[0] * t[5] * t[14] * t[11] - t[8] * t[5] * t[2] * t[15] + t[4] * t[9] * t[2] * t[15] + t[8] * t[1] * t[6] * t[15] - t[0] * t[9] * t[6] * t[15] - t[4] * t[1] * t[10] * t[15] + t[0] * t[5] * t[10] * t[15]; + } + invert() { + const t = this.buffer, n = this.determinant(); + if (n === 0) + throw new Error("Matrix is not invertible."); + const i = 1 / n; + return new _K( + i * (t[5] * t[10] * t[15] - t[5] * t[11] * t[14] - t[9] * t[6] * t[15] + t[9] * t[7] * t[14] + t[13] * t[6] * t[11] - t[13] * t[7] * t[10]), + i * (-t[1] * t[10] * t[15] + t[1] * t[11] * t[14] + t[9] * t[2] * t[15] - t[9] * t[3] * t[14] - t[13] * t[2] * t[11] + t[13] * t[3] * t[10]), + i * (t[1] * t[6] * t[15] - t[1] * t[7] * t[14] - t[5] * t[2] * t[15] + t[5] * t[3] * t[14] + t[13] * t[2] * t[7] - t[13] * t[3] * t[6]), + i * (-t[1] * t[6] * t[11] + t[1] * t[7] * t[10] + t[5] * t[2] * t[11] - t[5] * t[3] * t[10] - t[9] * t[2] * t[7] + t[9] * t[3] * t[6]), + i * (-t[4] * t[10] * t[15] + t[4] * t[11] * t[14] + t[8] * t[6] * t[15] - t[8] * t[7] * t[14] - t[12] * t[6] * t[11] + t[12] * t[7] * t[10]), + i * (t[0] * t[10] * t[15] - t[0] * t[11] * t[14] - t[8] * t[2] * t[15] + t[8] * t[3] * t[14] + t[12] * t[2] * t[11] - t[12] * t[3] * t[10]), + i * (-t[0] * t[6] * t[15] + t[0] * t[7] * t[14] + t[4] * t[2] * t[15] - t[4] * t[3] * t[14] - t[12] * t[2] * t[7] + t[12] * t[3] * t[6]), + i * (t[0] * t[6] * t[11] - t[0] * t[7] * t[10] - t[4] * t[2] * t[11] + t[4] * t[3] * t[10] + t[8] * t[2] * t[7] - t[8] * t[3] * t[6]), + i * (t[4] * t[9] * t[15] - t[4] * t[11] * t[13] - t[8] * t[5] * t[15] + t[8] * t[7] * t[13] + t[12] * t[5] * t[11] - t[12] * t[7] * t[9]), + i * (-t[0] * t[9] * t[15] + t[0] * t[11] * t[13] + t[8] * t[1] * t[15] - t[8] * t[3] * t[13] - t[12] * t[1] * t[11] + t[12] * t[3] * t[9]), + i * (t[0] * t[5] * t[15] - t[0] * t[7] * t[13] - t[4] * t[1] * t[15] + t[4] * t[3] * t[13] + t[12] * t[1] * t[7] - t[12] * t[3] * t[5]), + i * (-t[0] * t[5] * t[11] + t[0] * t[7] * t[9] + t[4] * t[1] * t[11] - t[4] * t[3] * t[9] - t[8] * t[1] * t[7] + t[8] * t[3] * t[5]), + i * (-t[4] * t[9] * t[14] + t[4] * t[10] * t[13] + t[8] * t[5] * t[14] - t[8] * t[6] * t[13] - t[12] * t[5] * t[10] + t[12] * t[6] * t[9]), + i * (t[0] * t[9] * t[14] - t[0] * t[10] * t[13] - t[8] * t[1] * t[14] + t[8] * t[2] * t[13] + t[12] * t[1] * t[10] - t[12] * t[2] * t[9]), + i * (-t[0] * t[5] * t[14] + t[0] * t[6] * t[13] + t[4] * t[1] * t[14] - t[4] * t[2] * t[13] - t[12] * t[1] * t[6] + t[12] * t[2] * t[5]), + i * (t[0] * t[5] * t[10] - t[0] * t[6] * t[9] - t[4] * t[1] * t[10] + t[4] * t[2] * t[9] + t[8] * t[1] * t[6] - t[8] * t[2] * t[5]) + ); + } + static Compose(t, n, i) { + const e = n.x, A = n.y, o = n.z, s = n.w, r = e + e, Q = A + A, I = o + o, d = e * r, a = e * Q, U = e * I, F = A * Q, g = A * I, B = o * I, C = s * r, c = s * Q, p = s * I, u = i.x, S = i.y, W = i.z; + return new _K( + (1 - (F + B)) * u, + (a + p) * u, + (U - c) * u, + 0, + (a - p) * S, + (1 - (d + B)) * S, + (g + C) * S, + 0, + (U + c) * W, + (g - C) * W, + (1 - (d + F)) * W, + 0, + t.x, + t.y, + t.z, + 1 + ); + } + toString() { + return `[${this.buffer.join(", ")}]`; + } + }; + var It = class extends Event { + constructor(t) { + super("objectAdded"), this.object = t; + } + }; + var ht = class extends Event { + constructor(t) { + super("objectRemoved"), this.object = t; + } + }; + var ct = class extends Event { + constructor(t) { + super("objectChanged"), this.object = t; + } + }; + var st = class extends Ft { + constructor() { + super(), this.positionChanged = false, this.rotationChanged = false, this.scaleChanged = false, this._position = new R(), this._rotation = new y(), this._scale = new R(1, 1, 1), this._transform = new K(), this._changeEvent = new ct(this), this.update = () => { + }, this.applyPosition = () => { + this.position = new R(); + }, this.applyRotation = () => { + this.rotation = new y(); + }, this.applyScale = () => { + this.scale = new R(1, 1, 1); + }, this.raiseChangeEvent = () => { + this.dispatchEvent(this._changeEvent); + }; + } + _updateMatrix() { + this._transform = K.Compose(this._position, this._rotation, this._scale); + } + get position() { + return this._position; + } + set position(t) { + this._position.equals(t) || (this._position = t, this.positionChanged = true, this._updateMatrix(), this.dispatchEvent(this._changeEvent)); + } + get rotation() { + return this._rotation; + } + set rotation(t) { + this._rotation.equals(t) || (this._rotation = t, this.rotationChanged = true, this._updateMatrix(), this.dispatchEvent(this._changeEvent)); + } + get scale() { + return this._scale; + } + set scale(t) { + this._scale.equals(t) || (this._scale = t, this.scaleChanged = true, this._updateMatrix(), this.dispatchEvent(this._changeEvent)); + } + get forward() { + let t = new R(0, 0, 1); + return t = this.rotation.apply(t), t; + } + get transform() { + return this._transform; + } + }; + var _ = class __ { + // prettier-ignore + constructor(t = 1, n = 0, i = 0, e = 0, A = 1, o = 0, s = 0, r = 0, Q = 1) { + this.buffer = [ + t, + n, + i, + e, + A, + o, + s, + r, + Q + ]; + } + equals(t) { + if (this.buffer.length !== t.buffer.length) + return false; + if (this.buffer === t.buffer) + return true; + for (let n = 0; n < this.buffer.length; n++) + if (this.buffer[n] !== t.buffer[n]) + return false; + return true; + } + multiply(t) { + const n = this.buffer, i = t.buffer; + return new __( + i[0] * n[0] + i[3] * n[1] + i[6] * n[2], + i[1] * n[0] + i[4] * n[1] + i[7] * n[2], + i[2] * n[0] + i[5] * n[1] + i[8] * n[2], + i[0] * n[3] + i[3] * n[4] + i[6] * n[5], + i[1] * n[3] + i[4] * n[4] + i[7] * n[5], + i[2] * n[3] + i[5] * n[4] + i[8] * n[5], + i[0] * n[6] + i[3] * n[7] + i[6] * n[8], + i[1] * n[6] + i[4] * n[7] + i[7] * n[8], + i[2] * n[6] + i[5] * n[7] + i[8] * n[8] + ); + } + clone() { + const t = this.buffer; + return new __( + t[0], + t[1], + t[2], + t[3], + t[4], + t[5], + t[6], + t[7], + t[8] + ); + } + static Eye(t = 1) { + return new __(t, 0, 0, 0, t, 0, 0, 0, t); + } + static Diagonal(t) { + return new __(t.x, 0, 0, 0, t.y, 0, 0, 0, t.z); + } + static RotationFromQuaternion(t) { + return new __( + 1 - 2 * t.y * t.y - 2 * t.z * t.z, + 2 * t.x * t.y - 2 * t.z * t.w, + 2 * t.x * t.z + 2 * t.y * t.w, + 2 * t.x * t.y + 2 * t.z * t.w, + 1 - 2 * t.x * t.x - 2 * t.z * t.z, + 2 * t.y * t.z - 2 * t.x * t.w, + 2 * t.x * t.z - 2 * t.y * t.w, + 2 * t.y * t.z + 2 * t.x * t.w, + 1 - 2 * t.x * t.x - 2 * t.y * t.y + ); + } + static RotationFromEuler(t) { + const n = Math.cos(t.x), i = Math.sin(t.x), e = Math.cos(t.y), A = Math.sin(t.y), o = Math.cos(t.z), s = Math.sin(t.z), r = [ + e * o + A * i * s, + -e * s + A * i * o, + A * n, + n * s, + n * o, + -i, + -A * o + e * i * s, + A * s + e * i * o, + e * n + ]; + return new __(...r); + } + toString() { + return `[${this.buffer.join(", ")}]`; + } + }; + var _Y = class _Y { + constructor(t = 0, n = null, i = null, e = null, A = null) { + this.changed = false, this.detached = false, this._vertexCount = t, this._positions = n || new Float32Array(0), this._rotations = i || new Float32Array(0), this._scales = e || new Float32Array(0), this._colors = A || new Uint8Array(0), this._selection = new Uint8Array(this.vertexCount), this.translate = (o) => { + for (let s = 0; s < this.vertexCount; s++) + this.positions[3 * s + 0] += o.x, this.positions[3 * s + 1] += o.y, this.positions[3 * s + 2] += o.z; + this.changed = true; + }, this.rotate = (o) => { + const s = _.RotationFromQuaternion(o).buffer; + for (let r = 0; r < this.vertexCount; r++) { + const Q = this.positions[3 * r + 0], I = this.positions[3 * r + 1], d = this.positions[3 * r + 2]; + this.positions[3 * r + 0] = s[0] * Q + s[1] * I + s[2] * d, this.positions[3 * r + 1] = s[3] * Q + s[4] * I + s[5] * d, this.positions[3 * r + 2] = s[6] * Q + s[7] * I + s[8] * d; + const a = new y( + this.rotations[4 * r + 1], + this.rotations[4 * r + 2], + this.rotations[4 * r + 3], + this.rotations[4 * r + 0] + ), U = o.multiply(a); + this.rotations[4 * r + 1] = U.x, this.rotations[4 * r + 2] = U.y, this.rotations[4 * r + 3] = U.z, this.rotations[4 * r + 0] = U.w; + } + this.changed = true; + }, this.scale = (o) => { + for (let s = 0; s < this.vertexCount; s++) + this.positions[3 * s + 0] *= o.x, this.positions[3 * s + 1] *= o.y, this.positions[3 * s + 2] *= o.z, this.scales[3 * s + 0] *= o.x, this.scales[3 * s + 1] *= o.y, this.scales[3 * s + 2] *= o.z; + this.changed = true; + }, this.serialize = () => { + const o = new Uint8Array(this.vertexCount * _Y.RowLength), s = new Float32Array(o.buffer), r = new Uint8Array(o.buffer); + for (let Q = 0; Q < this.vertexCount; Q++) + s[8 * Q + 0] = this.positions[3 * Q + 0], s[8 * Q + 1] = this.positions[3 * Q + 1], s[8 * Q + 2] = this.positions[3 * Q + 2], r[32 * Q + 24 + 0] = this.colors[4 * Q + 0], r[32 * Q + 24 + 1] = this.colors[4 * Q + 1], r[32 * Q + 24 + 2] = this.colors[4 * Q + 2], r[32 * Q + 24 + 3] = this.colors[4 * Q + 3], s[8 * Q + 3 + 0] = this.scales[3 * Q + 0], s[8 * Q + 3 + 1] = this.scales[3 * Q + 1], s[8 * Q + 3 + 2] = this.scales[3 * Q + 2], r[32 * Q + 28 + 0] = this.rotations[4 * Q + 0] * 128 + 128 & 255, r[32 * Q + 28 + 1] = this.rotations[4 * Q + 1] * 128 + 128 & 255, r[32 * Q + 28 + 2] = this.rotations[4 * Q + 2] * 128 + 128 & 255, r[32 * Q + 28 + 3] = this.rotations[4 * Q + 3] * 128 + 128 & 255; + return o; + }, this.reattach = (o, s, r, Q, I) => { + console.assert( + o.byteLength === this.vertexCount * 3 * 4, + `Expected ${this.vertexCount * 3 * 4} bytes, got ${o.byteLength} bytes` + ), this._positions = new Float32Array(o), this._rotations = new Float32Array(s), this._scales = new Float32Array(r), this._colors = new Uint8Array(Q), this._selection = new Uint8Array(I), this.detached = false; + }; + } + static Deserialize(t) { + const n = t.length / _Y.RowLength, i = new Float32Array(3 * n), e = new Float32Array(4 * n), A = new Float32Array(3 * n), o = new Uint8Array(4 * n), s = new Float32Array(t.buffer), r = new Uint8Array(t.buffer); + for (let Q = 0; Q < n; Q++) + i[3 * Q + 0] = s[8 * Q + 0], i[3 * Q + 1] = s[8 * Q + 1], i[3 * Q + 2] = s[8 * Q + 2], e[4 * Q + 0] = (r[32 * Q + 28 + 0] - 128) / 128, e[4 * Q + 1] = (r[32 * Q + 28 + 1] - 128) / 128, e[4 * Q + 2] = (r[32 * Q + 28 + 2] - 128) / 128, e[4 * Q + 3] = (r[32 * Q + 28 + 3] - 128) / 128, A[3 * Q + 0] = s[8 * Q + 3 + 0], A[3 * Q + 1] = s[8 * Q + 3 + 1], A[3 * Q + 2] = s[8 * Q + 3 + 2], o[4 * Q + 0] = r[32 * Q + 24 + 0], o[4 * Q + 1] = r[32 * Q + 24 + 1], o[4 * Q + 2] = r[32 * Q + 24 + 2], o[4 * Q + 3] = r[32 * Q + 24 + 3]; + return new _Y(n, i, e, A, o); + } + get vertexCount() { + return this._vertexCount; + } + get positions() { + return this._positions; + } + get rotations() { + return this._rotations; + } + get scales() { + return this._scales; + } + get colors() { + return this._colors; + } + get selection() { + return this._selection; + } + clone() { + return new _Y( + this.vertexCount, + new Float32Array(this.positions), + new Float32Array(this.rotations), + new Float32Array(this.scales), + new Uint8Array(this.colors) + ); + } + }; + _Y.RowLength = 3 * 4 + 3 * 4 + 4 + 4; + var Y = _Y; + var _ot = class _ot { + constructor(t, n, i, e, A) { + this._vertexCount = t, this._positions = n, this._data = i, this._width = e, this._height = A, this.serialize = () => new Uint8Array(this._data.buffer); + } + static Deserialize(t, n, i) { + const e = new Uint32Array(t.buffer), A = new Float32Array(t.buffer), o = Math.floor(A.byteLength / this.RowLength), s = new Float32Array(o * 3); + for (let r = 0; r < o; r++) + s[3 * r + 0] = A[16 * r + 0], s[3 * r + 1] = A[16 * r + 1], s[3 * r + 2] = A[16 * r + 2], s[3 * r + 0] = A[16 * r + 3]; + return new _ot(o, s, e, n, i); + } + get vertexCount() { + return this._vertexCount; + } + get positions() { + return this._positions; + } + get data() { + return this._data; + } + get width() { + return this._width; + } + get height() { + return this._height; + } + }; + _ot.RowLength = 64; + var ot = _ot; + var _et = class _et { + static SplatToPLY(t, n) { + let i = `ply +format binary_little_endian 1.0 +`; + i += `element vertex ${n} +`; + const e = ["x", "y", "z", "nx", "ny", "nz", "f_dc_0", "f_dc_1", "f_dc_2"]; + for (let B = 0; B < 45; B++) + e.push(`f_rest_${B}`); + e.push("opacity"), e.push("scale_0"), e.push("scale_1"), e.push("scale_2"), e.push("rot_0"), e.push("rot_1"), e.push("rot_2"), e.push("rot_3"); + for (const B of e) + i += `property float ${B} +`; + i += `end_header +`; + const A = new TextEncoder().encode(i), o = 4 * 3 + 4 * 3 + 4 * 3 + 4 * 45 + 4 + 4 * 3 + 4 * 4, s = n * o, r = new DataView(new ArrayBuffer(A.length + s)); + new Uint8Array(r.buffer).set(A, 0); + const Q = new Float32Array(t), I = new Uint8Array(t), d = A.length, a = 4 * 3 + 4 * 3, U = a + 4 * 3 + 4 * 45, F = U + 4, g = F + 4 * 3; + for (let B = 0; B < n; B++) { + const C = Q[8 * B + 0], c = Q[8 * B + 1], p = Q[8 * B + 2], u = (I[32 * B + 24 + 0] / 255 - 0.5) / this.SH_C0, S = (I[32 * B + 24 + 1] / 255 - 0.5) / this.SH_C0, W = (I[32 * B + 24 + 2] / 255 - 0.5) / this.SH_C0, Z = I[32 * B + 24 + 3] / 255, k = Math.log(Z / (1 - Z)), f = Math.log(Q[8 * B + 3 + 0]), H = Math.log(Q[8 * B + 3 + 1]), L = Math.log(Q[8 * B + 3 + 2]); + let M = new y( + (I[32 * B + 28 + 1] - 128) / 128, + (I[32 * B + 28 + 2] - 128) / 128, + (I[32 * B + 28 + 3] - 128) / 128, + (I[32 * B + 28 + 0] - 128) / 128 + ); + M = M.normalize(); + const V = M.w, w = M.x, P = M.y, T = M.z; + r.setFloat32(d + o * B + 0, C, true), r.setFloat32(d + o * B + 4, c, true), r.setFloat32(d + o * B + 8, p, true), r.setFloat32(d + o * B + a + 0, u, true), r.setFloat32(d + o * B + a + 4, S, true), r.setFloat32(d + o * B + a + 8, W, true), r.setFloat32(d + o * B + U, k, true), r.setFloat32(d + o * B + F + 0, f, true), r.setFloat32(d + o * B + F + 4, H, true), r.setFloat32(d + o * B + F + 8, L, true), r.setFloat32(d + o * B + g + 0, V, true), r.setFloat32(d + o * B + g + 4, w, true), r.setFloat32(d + o * B + g + 8, P, true), r.setFloat32(d + o * B + g + 12, T, true); + } + return r.buffer; + } + }; + _et.SH_C0 = 0.28209479177387814; + var et = _et; + var nt = class { + constructor(t, n) { + this.min = t, this.max = n; + } + contains(t) { + return t.x >= this.min.x && t.x <= this.max.x && t.y >= this.min.y && t.y <= this.max.y && t.z >= this.min.z && t.z <= this.max.z; + } + intersects(t) { + return this.max.x >= t.min.x && this.min.x <= t.max.x && this.max.y >= t.min.y && this.min.y <= t.max.y && this.max.z >= t.min.z && this.min.z <= t.max.z; + } + size() { + return this.max.subtract(this.min); + } + center() { + return this.min.add(this.max).divide(2); + } + expand(t) { + this.min = this.min.min(t), this.max = this.max.max(t); + } + permute() { + const t = this.min, n = this.max; + this.min = new R(Math.min(t.x, n.x), Math.min(t.y, n.y), Math.min(t.z, n.z)), this.max = new R(Math.max(t.x, n.x), Math.max(t.y, n.y), Math.max(t.z, n.z)); + } + }; + var X = class _X extends st { + constructor(t = void 0) { + super(), this.selectedChanged = false, this.colorTransformChanged = false, this._selected = false, this._colorTransforms = [], this._colorTransformsMap = /* @__PURE__ */ new Map(), this._data = t || new Y(), this._bounds = new nt( + new R(1 / 0, 1 / 0, 1 / 0), + new R(-1 / 0, -1 / 0, -1 / 0) + ), this.recalculateBounds = () => { + this._bounds = new nt( + new R(1 / 0, 1 / 0, 1 / 0), + new R(-1 / 0, -1 / 0, -1 / 0) + ); + for (let n = 0; n < this._data.vertexCount; n++) + this._bounds.expand( + new R( + this._data.positions[3 * n], + this._data.positions[3 * n + 1], + this._data.positions[3 * n + 2] + ) + ); + }, this.applyPosition = () => { + this.data.translate(this.position), this.position = new R(); + }, this.applyRotation = () => { + this.data.rotate(this.rotation), this.rotation = new y(); + }, this.applyScale = () => { + this.data.scale(this.scale), this.scale = new R(1, 1, 1); + }, this.recalculateBounds(); + } + saveToFile(t = null, n = "splat") { + if (!document) return; + if (!t) { + const s = /* @__PURE__ */ new Date(); + t = `splat-${s.getFullYear()}-${s.getMonth() + 1}-${s.getDate()}.${n}`; + } + const i = this.clone(); + i.applyRotation(), i.applyScale(), i.applyPosition(); + const e = i.data.serialize(); + let A; + if (n === "ply") { + const s = et.SplatToPLY(e.buffer, i.data.vertexCount); + A = new Blob([s], { type: "application/octet-stream" }); + } else + A = new Blob([e.buffer], { type: "application/octet-stream" }); + const o = document.createElement("a"); + o.download = t, o.href = URL.createObjectURL(A), o.click(); + } + get data() { + return this._data; + } + get selected() { + return this._selected; + } + set selected(t) { + this._selected !== t && (this._selected = t, this.selectedChanged = true, this.dispatchEvent(this._changeEvent)); + } + get colorTransforms() { + return this._colorTransforms; + } + get colorTransformsMap() { + return this._colorTransformsMap; + } + get bounds() { + let t = this._bounds.center(); + t = t.add(this.position); + let n = this._bounds.size(); + return n = n.multiply(this.scale), new nt(t.subtract(n.divide(2)), t.add(n.divide(2))); + } + clone() { + const t = new _X(this.data.clone()); + return t.position = this.position.clone(), t.rotation = this.rotation.clone(), t.scale = this.scale.clone(), t; + } + }; + var tt = class extends st { + constructor(t) { + super(), this._data = t; + } + get data() { + return this._data; + } + }; + var Rt = class { + constructor() { + this._fx = 1132, this._fy = 1132, this._near = 0.1, this._far = 100, this._width = 512, this._height = 512, this._projectionMatrix = new K(), this._viewMatrix = new K(), this._viewProj = new K(), this._updateProjectionMatrix = () => { + this._projectionMatrix = new K( + 2 * this.fx / this.width, + 0, + 0, + 0, + 0, + -2 * this.fy / this.height, + 0, + 0, + 0, + 0, + this.far / (this.far - this.near), + 1, + 0, + 0, + -(this.far * this.near) / (this.far - this.near), + 0 + ), this._viewProj = this.projectionMatrix.multiply(this.viewMatrix); + }, this.update = (t, n) => { + const i = _.RotationFromQuaternion(n).buffer, e = t.flat(); + this._viewMatrix = new K( + i[0], + i[1], + i[2], + 0, + i[3], + i[4], + i[5], + 0, + i[6], + i[7], + i[8], + 0, + -e[0] * i[0] - e[1] * i[3] - e[2] * i[6], + -e[0] * i[1] - e[1] * i[4] - e[2] * i[7], + -e[0] * i[2] - e[1] * i[5] - e[2] * i[8], + 1 + ), this._viewProj = this.projectionMatrix.multiply(this.viewMatrix); + }, this.setSize = (t, n) => { + this._width = t, this._height = n, this._updateProjectionMatrix(); + }; + } + get fx() { + return this._fx; + } + set fx(t) { + this._fx !== t && (this._fx = t, this._updateProjectionMatrix()); + } + get fy() { + return this._fy; + } + set fy(t) { + this._fy !== t && (this._fy = t, this._updateProjectionMatrix()); + } + get near() { + return this._near; + } + set near(t) { + this._near !== t && (this._near = t, this._updateProjectionMatrix()); + } + get far() { + return this._far; + } + set far(t) { + this._far !== t && (this._far = t, this._updateProjectionMatrix()); + } + get width() { + return this._width; + } + get height() { + return this._height; + } + get projectionMatrix() { + return this._projectionMatrix; + } + get viewMatrix() { + return this._viewMatrix; + } + get viewProj() { + return this._viewProj; + } + }; + var z = class _z { + constructor(t = 0, n = 0, i = 0, e = 0) { + this.x = t, this.y = n, this.z = i, this.w = e; + } + equals(t) { + return !(this.x !== t.x || this.y !== t.y || this.z !== t.z || this.w !== t.w); + } + add(t) { + return typeof t == "number" ? new _z(this.x + t, this.y + t, this.z + t, this.w + t) : new _z(this.x + t.x, this.y + t.y, this.z + t.z, this.w + t.w); + } + subtract(t) { + return typeof t == "number" ? new _z(this.x - t, this.y - t, this.z - t, this.w - t) : new _z(this.x - t.x, this.y - t.y, this.z - t.z, this.w - t.w); + } + multiply(t) { + return typeof t == "number" ? new _z(this.x * t, this.y * t, this.z * t, this.w * t) : t instanceof _z ? new _z(this.x * t.x, this.y * t.y, this.z * t.z, this.w * t.w) : new _z( + this.x * t.buffer[0] + this.y * t.buffer[4] + this.z * t.buffer[8] + this.w * t.buffer[12], + this.x * t.buffer[1] + this.y * t.buffer[5] + this.z * t.buffer[9] + this.w * t.buffer[13], + this.x * t.buffer[2] + this.y * t.buffer[6] + this.z * t.buffer[10] + this.w * t.buffer[14], + this.x * t.buffer[3] + this.y * t.buffer[7] + this.z * t.buffer[11] + this.w * t.buffer[15] + ); + } + dot(t) { + return this.x * t.x + this.y * t.y + this.z * t.z + this.w * t.w; + } + lerp(t, n) { + return new _z( + this.x + (t.x - this.x) * n, + this.y + (t.y - this.y) * n, + this.z + (t.z - this.z) * n, + this.w + (t.w - this.w) * n + ); + } + magnitude() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); + } + distanceTo(t) { + return Math.sqrt((this.x - t.x) ** 2 + (this.y - t.y) ** 2 + (this.z - t.z) ** 2 + (this.w - t.w) ** 2); + } + normalize() { + const t = this.magnitude(); + return new _z(this.x / t, this.y / t, this.z / t, this.w / t); + } + flat() { + return [this.x, this.y, this.z, this.w]; + } + clone() { + return new _z(this.x, this.y, this.z, this.w); + } + toString() { + return `[${this.flat().join(", ")}]`; + } + }; + var wt = class extends st { + constructor(t = void 0) { + super(), this._data = t || new Rt(), this._position = new R(0, 0, -5), this.update = () => { + this.data.update(this.position, this.rotation); + }, this.screenPointToRay = (n, i) => { + const e = new z(n, i, -1, 1), A = this._data.projectionMatrix.invert(), o = e.multiply(A), s = this._data.viewMatrix.invert(), r = o.multiply(s); + return new R( + r.x / r.w, + r.y / r.w, + r.z / r.w + ).subtract(this.position).normalize(); + }; + } + get data() { + return this._data; + } + }; + var kt = class extends Ft { + constructor() { + super(), this._objects = [], this.addObject = (t) => { + this.objects.push(t), this.dispatchEvent(new It(t)); + }, this.removeObject = (t) => { + const n = this.objects.indexOf(t); + if (n < 0) + throw new Error("Object not found in scene"); + this.objects.splice(n, 1), this.dispatchEvent(new ht(t)); + }, this.findObject = (t) => { + for (const n of this.objects) + if (t(n)) + return n; + }, this.findObjectOfType = (t) => { + for (const n of this.objects) + if (n instanceof t) + return n; + }, this.reset = () => { + const t = this.objects.slice(); + for (const n of t) + this.removeObject(n); + }, this.reset(); + } + getMergedSceneDataBuffer(t = "splat") { + const n = []; + let i = 0; + for (const o of this.objects) + if (o instanceof X) { + const s = o.clone(); + s.applyRotation(), s.applyScale(), s.applyPosition(); + const r = s.data.serialize(); + n.push(r), i += s.data.vertexCount; + } + const e = new Uint8Array(i * Y.RowLength); + let A = 0; + for (const o of n) + e.set(o, A), A += o.length; + return t === "ply" ? et.SplatToPLY(e.buffer, i) : e.buffer; + } + saveToFile(t = null, n = "splat") { + if (!document) return; + if (!t) { + const o = /* @__PURE__ */ new Date(); + t = `scene-${o.getFullYear()}-${o.getMonth() + 1}-${o.getDate()}.${n}`; + } + const i = this.getMergedSceneDataBuffer(n), e = new Blob([i], { type: "application/octet-stream" }), A = document.createElement("a"); + A.download = t, A.href = URL.createObjectURL(e), A.click(); + } + get objects() { + return this._objects; + } + }; + async function rt(E, t) { + const n = await fetch(E, { + mode: "cors", + credentials: "same-origin", + cache: t ? "force-cache" : "default" + }); + if (n.status != 200) + throw new Error(n.status + " Unable to load " + n.url); + return n; + } + async function At(E, t) { + const n = E.body.getReader(), i = E.headers.get("content-length"), e = i && !isNaN(parseInt(i)) ? parseInt(i) : void 0, A = []; + let o = 0; + for (; ; ) { + const { done: Q, value: I } = await n.read(); + if (Q) break; + if (A.push(I), o += I.length, t && e) { + const d = o / e, a = Math.min(d * 0.95, 0.95); + t(a); + } + } + const s = new Uint8Array(o); + let r = 0; + for (const Q of A) + s.set(Q, r), r += Q.length; + return t && t(1), s; + } + var Tt = class { + static async LoadAsync(t, n, i, e = false) { + const A = await rt(t, e), o = await At(A, i); + return this.LoadFromArrayBuffer(o.buffer, n); + } + static async LoadFromFileAsync(t, n, i) { + const e = new FileReader(); + let A = new X(); + return e.onload = (o) => { + A = this.LoadFromArrayBuffer(o.target.result, n); + }, e.onprogress = (o) => { + i?.(o.loaded / o.total); + }, e.readAsArrayBuffer(t), await new Promise((o) => { + e.onloadend = () => { + o(); + }; + }), A; + } + static LoadFromArrayBuffer(t, n) { + const i = new Uint8Array(t), e = Y.Deserialize(i), A = new X(e); + return n.addObject(A), A; + } + }; + var bt = class { + static async LoadAsync(t, n, i, e = "", A = false) { + const o = await rt(t, A), s = await At(o, i); + if (s[0] !== 112 || s[1] !== 108 || s[2] !== 121 || s[3] !== 10) + throw new Error("Invalid PLY file"); + return this.LoadFromArrayBuffer(s.buffer, n, e); + } + static async LoadFromFileAsync(t, n, i, e = "") { + const A = new FileReader(); + let o = new X(); + return A.onload = (s) => { + o = this.LoadFromArrayBuffer(s.target.result, n, e); + }, A.onprogress = (s) => { + i?.(s.loaded / s.total); + }, A.readAsArrayBuffer(t), await new Promise((s) => { + A.onloadend = () => { + s(); + }; + }), o; + } + static LoadFromArrayBuffer(t, n, i = "") { + const e = new Uint8Array(this._ParsePLYBuffer(t, i)), A = Y.Deserialize(e), o = new X(A); + return n.addObject(o), o; + } + static _ParsePLYBuffer(t, n) { + const i = new Uint8Array(t), e = new TextDecoder().decode(i.slice(0, 1024 * 10)), A = `end_header +`, o = e.indexOf(A); + if (o < 0) throw new Error("Unable to read .ply file header"); + const s = parseInt(/element vertex (\d+)\n/.exec(e)[1]); + let r = 0; + const Q = { + double: 8, + int: 4, + uint: 4, + float: 4, + short: 2, + ushort: 2, + uchar: 1 + }, I = []; + for (const F of e.slice(0, o).split(` +`).filter((g) => g.startsWith("property "))) { + const [g, B, C] = F.split(" "); + if (I.push({ name: C, type: B, offset: r }), !Q[B]) throw new Error(`Unsupported property type: ${B}`); + r += Q[B]; + } + const d = new DataView(t, o + A.length), a = new ArrayBuffer(Y.RowLength * s), U = y.FromEuler(new R(Math.PI / 2, 0, 0)); + for (let F = 0; F < s; F++) { + const g = new Float32Array(a, F * Y.RowLength, 3), B = new Float32Array(a, F * Y.RowLength + 12, 3), C = new Uint8ClampedArray(a, F * Y.RowLength + 24, 4), c = new Uint8ClampedArray(a, F * Y.RowLength + 28, 4); + let p = 255, u = 0, S = 0, W = 0; + I.forEach((k) => { + let f; + switch (k.type) { + case "float": + f = d.getFloat32(k.offset + F * r, true); + break; + case "int": + f = d.getInt32(k.offset + F * r, true); + break; + default: + throw new Error(`Unsupported property type: ${k.type}`); + } + switch (k.name) { + case "x": + g[0] = f; + break; + case "y": + g[1] = f; + break; + case "z": + g[2] = f; + break; + case "scale_0": + case "scaling_0": + B[0] = Math.exp(f); + break; + case "scale_1": + case "scaling_1": + B[1] = Math.exp(f); + break; + case "scale_2": + case "scaling_2": + B[2] = Math.exp(f); + break; + case "red": + C[0] = f; + break; + case "green": + C[1] = f; + break; + case "blue": + C[2] = f; + break; + case "f_dc_0": + case "features_0": + C[0] = (0.5 + et.SH_C0 * f) * 255; + break; + case "f_dc_1": + case "features_1": + C[1] = (0.5 + et.SH_C0 * f) * 255; + break; + case "f_dc_2": + case "features_2": + C[2] = (0.5 + et.SH_C0 * f) * 255; + break; + case "f_dc_3": + C[3] = (0.5 + et.SH_C0 * f) * 255; + break; + case "opacity": + case "opacity_0": + C[3] = 1 / (1 + Math.exp(-f)) * 255; + break; + case "rot_0": + case "rotation_0": + p = f; + break; + case "rot_1": + case "rotation_1": + u = f; + break; + case "rot_2": + case "rotation_2": + S = f; + break; + case "rot_3": + case "rotation_3": + W = f; + break; + } + }); + let Z = new y(u, S, W, p); + switch (n) { + case "polycam": { + const k = g[1]; + g[1] = -g[2], g[2] = k, Z = U.multiply(Z); + break; + } + case "": + break; + default: + throw new Error(`Unsupported format: ${n}`); + } + Z = Z.normalize(), c[0] = Z.w * 128 + 128, c[1] = Z.x * 128 + 128, c[2] = Z.y * 128 + 128, c[3] = Z.z * 128 + 128; + } + return a; + } + }; + var xt = class { + static async LoadAsync(t, n, i, e, A = false) { + const o = await rt(t, A), s = await At(o, e); + return this._ParseSplatvBuffer(s.buffer, n, i); + } + static async LoadFromFileAsync(t, n, i, e) { + const A = new FileReader(); + let o = null; + if (A.onload = (s) => { + o = this._ParseSplatvBuffer(s.target.result, n, i); + }, A.onprogress = (s) => { + e?.(s.loaded / s.total); + }, A.readAsArrayBuffer(t), await new Promise((s) => { + A.onloadend = () => { + s(); + }; + }), !o) + throw new Error("Failed to load splatv file"); + return o; + } + static _ParseSplatvBuffer(t, n, i) { + let e = null; + const A = (a, U, F) => { + if (a.type === "magic") { + const g = new Int32Array(U.buffer); + if (g[0] !== 26443) + throw new Error("Invalid splatv file"); + F.push({ size: g[1], type: "chunks" }); + } else if (a.type === "chunks") { + const g = JSON.parse(new TextDecoder("utf-8").decode(U)); + if (g.length == 0) + throw new Error("Invalid splatv file"); + g.length > 1 && console.warn("Splatv file contains more than one chunk, only the first one will be loaded"); + const B = g[0], C = B.cameras; + if (i && C && C.length) { + const c = C[0], p = new R( + c.position[0], + c.position[1], + c.position[2] + ), u = y.FromMatrix3( + new _( + c.rotation[0][0], + c.rotation[0][1], + c.rotation[0][2], + c.rotation[1][0], + c.rotation[1][1], + c.rotation[1][2], + c.rotation[2][0], + c.rotation[2][1], + c.rotation[2][2] + ) + ); + i.position = p, i.rotation = u; + } + F.push(B); + } else if (a.type === "splat") { + const g = ot.Deserialize(U, a.texwidth, a.texheight), B = new tt(g); + n.addObject(B), e = B; + } + }, o = new Uint8Array(t), s = [ + { size: 8, type: "magic", texwidth: 0, texheight: 0 } + ]; + let r = s.shift(), Q = new Uint8Array(r.size), I = 0, d = 0; + for (; r; ) { + for (; I < r.size; ) { + const a = Math.min(r.size - I, o.length - d); + Q.set(o.subarray(d, d + a), I), I += a, d += a; + } + if (A(r, Q, s), e) + return e; + r = s.shift(), r && (Q = new Uint8Array(r.size), I = 0); + } + throw new Error("Invalid splatv file"); + } + }; + var Bt = "dmFyIGVBID0gZnVuY3Rpb24oQyA9IHt9KSB7CiAgdmFyIHIsIEkgPSBDLCBsID0gaW1wb3J0Lm1ldGEudXJsLCBqID0gIiIsIFU7CiAgewogICAgdHJ5IHsKICAgICAgaiA9IG5ldyBVUkwoIi4iLCBsKS5ocmVmOwogICAgfSBjYXRjaCB7CiAgICB9CiAgICBVID0gKEEpID0+IHsKICAgICAgdmFyIEIgPSBuZXcgWE1MSHR0cFJlcXVlc3QoKTsKICAgICAgcmV0dXJuIEIub3BlbigiR0VUIiwgQSwgITEpLCBCLnJlc3BvbnNlVHlwZSA9ICJhcnJheWJ1ZmZlciIsIEIuc2VuZChudWxsKSwgbmV3IFVpbnQ4QXJyYXkoQi5yZXNwb25zZSk7CiAgICB9OwogIH0KICBjb25zb2xlLmxvZy5iaW5kKGNvbnNvbGUpLCBjb25zb2xlLmVycm9yLmJpbmQoY29uc29sZSk7CiAgdmFyIE0sIHUsIEw7CiAgZnVuY3Rpb24gcSgpIHsKICAgIHZhciBBID0gdS5idWZmZXI7CiAgICBJLkhFQVBVOCA9IEwgPSBuZXcgVWludDhBcnJheShBKSwgSS5IRUFQVTMyID0gbmV3IFVpbnQzMkFycmF5KEEpLCBJLkhFQVBGMzIgPSBuZXcgRmxvYXQzMkFycmF5KEEpLCBuZXcgQmlnSW50NjRBcnJheShBKSwgbmV3IEJpZ1VpbnQ2NEFycmF5KEEpOwogIH0KICBmdW5jdGlvbiBQKCkgewogICAgaWYgKEkucHJlUnVuKQogICAgICBmb3IgKHR5cGVvZiBJLnByZVJ1biA9PSAiZnVuY3Rpb24iICYmIChJLnByZVJ1biA9IFtJLnByZVJ1bl0pOyBJLnByZVJ1bi5sZW5ndGg7ICkKICAgICAgICBDQShJLnByZVJ1bi5zaGlmdCgpKTsKICAgIHgoVCk7CiAgfQogIGZ1bmN0aW9uIGIoKSB7CiAgICB5LmMoKTsKICB9CiAgZnVuY3Rpb24gVygpIHsKICAgIGlmIChJLnBvc3RSdW4pCiAgICAgIGZvciAodHlwZW9mIEkucG9zdFJ1biA9PSAiZnVuY3Rpb24iICYmIChJLnBvc3RSdW4gPSBbSS5wb3N0UnVuXSk7IEkucG9zdFJ1bi5sZW5ndGg7ICkKICAgICAgICBnQShJLnBvc3RSdW4uc2hpZnQoKSk7CiAgICB4KHYpOwogIH0KICB2YXIgcyA9IDAsIGYgPSBudWxsOwogIGZ1bmN0aW9uIF8oQSkgewogICAgcysrLCBJLm1vbml0b3JSdW5EZXBlbmRlbmNpZXM/LihzKTsKICB9CiAgZnVuY3Rpb24geihBKSB7CiAgICBpZiAocy0tLCBJLm1vbml0b3JSdW5EZXBlbmRlbmNpZXM/LihzKSwgcyA9PSAwICYmIGYpIHsKICAgICAgdmFyIEIgPSBmOwogICAgICBmID0gbnVsbCwgQigpOwogICAgfQogIH0KICB2YXIgUzsKICBmdW5jdGlvbiBWKCkgewogICAgcmV0dXJuIEJBKCJBR0Z6YlFFQUFBQUJHUVJnQVg4QmYyQUJmd0JnQ1g5L2YzOS9mMzkvZndCZ0FBQUNCd0VCWVFGaEFBQURCZ1VBQVFBQ0F3VUhBUUdDQW9DQUFnWUlBWDhCUVlDTUJBc0hGUVVCWWdJQUFXTUFCUUZrQUFRQlpRQURBV1lBQWd3QkFRck5PQVZQQVFKL1FZQUlLQUlBSWdFZ0FFRUhha0Y0Y1NJQ2FpRUFBa0FnQWtFQUlBQWdBVTBiUlFSQUlBQS9BRUVRZEUwTkFTQUFFQUFOQVF0QmhBaEJNRFlDQUVGL0R3dEJnQWdnQURZQ0FDQUJDOXdMQVFoL0FrQWdBRVVOQUNBQVFRaHJJZ01nQUVFRWF5Z0NBQ0lDUVhoeElnQnFJUVVDUUNBQ1FRRnhEUUFnQWtFQ2NVVU5BU0FESUFNb0FnQWlCR3NpQTBHWUNDZ0NBRWtOQVNBQUlBUnFJUUFDUUFKQUFrQkJuQWdvQWdBZ0EwY0VRQ0FES0FJTUlRRWdCRUgvQVUwRVFDQUJJQU1vQWdnaUFrY05Ba0dJQ0VHSUNDZ0NBRUYrSUFSQkEzWjNjVFlDQUF3RkN5QURLQUlZSVFjZ0FTQURSd1JBSUFNb0FnZ2lBaUFCTmdJTUlBRWdBallDQ0F3RUN5QURLQUlVSWdJRWZ5QURRUlJxQlNBREtBSVFJZ0pGRFFNZ0EwRVFhZ3NoQkFOQUlBUWhCaUFDSWdGQkZHb2hCQ0FCS0FJVUlnSU5BQ0FCUVJCcUlRUWdBU2dDRUNJQ0RRQUxJQVpCQURZQ0FBd0RDeUFGS0FJRUlnSkJBM0ZCQTBjTkEwR1FDQ0FBTmdJQUlBVWdBa0YrY1RZQ0JDQURJQUJCQVhJMkFnUWdCU0FBTmdJQUR3c2dBaUFCTmdJTUlBRWdBallDQ0F3Q0MwRUFJUUVMSUFkRkRRQUNRQ0FES0FJY0lnUkJBblJCdUFwcUlnSW9BZ0FnQTBZRVFDQUNJQUUyQWdBZ0FRMEJRWXdJUVl3SUtBSUFRWDRnQkhkeE5nSUFEQUlMQWtBZ0F5QUhLQUlRUmdSQUlBY2dBVFlDRUF3QkN5QUhJQUUyQWhRTElBRkZEUUVMSUFFZ0J6WUNHQ0FES0FJUUlnSUVRQ0FCSUFJMkFoQWdBaUFCTmdJWUN5QURLQUlVSWdKRkRRQWdBU0FDTmdJVUlBSWdBVFlDR0FzZ0F5QUZUdzBBSUFVb0FnUWlCRUVCY1VVTkFBSkFBa0FDUUFKQUlBUkJBbkZGQkVCQm9BZ29BZ0FnQlVZRVFFR2dDQ0FETmdJQVFaUUlRWlFJS0FJQUlBQnFJZ0EyQWdBZ0F5QUFRUUZ5TmdJRUlBTkJuQWdvQWdCSERRWkJrQWhCQURZQ0FFR2NDRUVBTmdJQUR3dEJuQWdvQWdBaUJ5QUZSZ1JBUVp3SUlBTTJBZ0JCa0FoQmtBZ29BZ0FnQUdvaUFEWUNBQ0FESUFCQkFYSTJBZ1FnQUNBRGFpQUFOZ0lBRHdzZ0JFRjRjU0FBYWlFQUlBVW9BZ3doQVNBRVFmOEJUUVJBSUFVb0FnZ2lBaUFCUmdSQVFZZ0lRWWdJS0FJQVFYNGdCRUVEZG5keE5nSUFEQVVMSUFJZ0FUWUNEQ0FCSUFJMkFnZ01CQXNnQlNnQ0dDRUlJQUVnQlVjRVFDQUZLQUlJSWdJZ0FUWUNEQ0FCSUFJMkFnZ01Bd3NnQlNnQ0ZDSUNCSDhnQlVFVWFnVWdCU2dDRUNJQ1JRMENJQVZCRUdvTElRUURRQ0FFSVFZZ0FpSUJRUlJxSVFRZ0FTZ0NGQ0lDRFFBZ0FVRVFhaUVFSUFFb0FoQWlBZzBBQ3lBR1FRQTJBZ0FNQWdzZ0JTQUVRWDV4TmdJRUlBTWdBRUVCY2pZQ0JDQUFJQU5xSUFBMkFnQU1Bd3RCQUNFQkN5QUlSUTBBQWtBZ0JTZ0NIQ0lFUVFKMFFiZ0thaUlDS0FJQUlBVkdCRUFnQWlBQk5nSUFJQUVOQVVHTUNFR01DQ2dDQUVGK0lBUjNjVFlDQUF3Q0N3SkFJQVVnQ0NnQ0VFWUVRQ0FJSUFFMkFoQU1BUXNnQ0NBQk5nSVVDeUFCUlEwQkN5QUJJQWcyQWhnZ0JTZ0NFQ0lDQkVBZ0FTQUNOZ0lRSUFJZ0FUWUNHQXNnQlNnQ0ZDSUNSUTBBSUFFZ0FqWUNGQ0FDSUFFMkFoZ0xJQU1nQUVFQmNqWUNCQ0FBSUFOcUlBQTJBZ0FnQXlBSFJ3MEFRWkFJSUFBMkFnQVBDeUFBUWY4QlRRUkFJQUJCZUhGQnNBaHFJUUlDZjBHSUNDZ0NBQ0lFUVFFZ0FFRURkblFpQUhGRkJFQkJpQWdnQUNBRWNqWUNBQ0FDREFFTElBSW9BZ2dMSVFBZ0FpQUROZ0lJSUFBZ0F6WUNEQ0FESUFJMkFnd2dBeUFBTmdJSUR3dEJIeUVCSUFCQi8vLy9CMDBFUUNBQVFTWWdBRUVJZG1jaUFtdDJRUUZ4SUFKQkFYUnJRVDVxSVFFTElBTWdBVFlDSENBRFFnQTNBaEFnQVVFQ2RFRzRDbW9oQkFKL0FrQUNmMEdNQ0NnQ0FDSUdRUUVnQVhRaUFuRkZCRUJCakFnZ0FpQUdjallDQUNBRUlBTTJBZ0JCR0NFQlFRZ01BUXNnQUVFWklBRkJBWFpyUVFBZ0FVRWZSeHQwSVFFZ0JDZ0NBQ0VFQTBBZ0JDSUNLQUlFUVhoeElBQkdEUUlnQVVFZGRpRUVJQUZCQVhRaEFTQUNJQVJCQkhGcUlnWW9BaEFpQkEwQUN5QUdJQU0yQWhCQkdDRUJJQUloQkVFSUN5RUFJQU1pQWd3QkN5QUNLQUlJSWdRZ0F6WUNEQ0FDSUFNMkFnaEJHQ0VBUVFnaEFVRUFDeUVHSUFFZ0Eyb2dCRFlDQUNBRElBSTJBZ3dnQUNBRGFpQUdOZ0lBUWFnSVFhZ0lLQUlBUVFGcklnQkJmeUFBR3pZQ0FBc0wwU2NCQzM4akFFRVFheUlLSkFBQ1FBSkFBa0FDUUFKQUFrQUNRQUpBQWtBQ1FDQUFRZlFCVFFSQVFZZ0lLQUlBSWdSQkVDQUFRUXRxUWZnRGNTQUFRUXRKR3lJR1FRTjJJZ0IySWdGQkEzRUVRQUpBSUFGQmYzTkJBWEVnQUdvaUFrRURkQ0lCUWJBSWFpSUFJQUZCdUFocUtBSUFJZ0VvQWdnaUJVWUVRRUdJQ0NBRVFYNGdBbmR4TmdJQURBRUxJQVVnQURZQ0RDQUFJQVUyQWdnTElBRkJDR29oQUNBQklBSkJBM1FpQWtFRGNqWUNCQ0FCSUFKcUlnRWdBU2dDQkVFQmNqWUNCQXdMQ3lBR1FaQUlLQUlBSWdoTkRRRWdBUVJBQWtCQkFpQUFkQ0lDUVFBZ0FtdHlJQUVnQUhSeGFDSUJRUU4wSWdCQnNBaHFJZ0lnQUVHNENHb29BZ0FpQUNnQ0NDSUZSZ1JBUVlnSUlBUkJmaUFCZDNFaUJEWUNBQXdCQ3lBRklBSTJBZ3dnQWlBRk5nSUlDeUFBSUFaQkEzSTJBZ1FnQUNBR2FpSUhJQUZCQTNRaUFTQUdheUlGUVFGeU5nSUVJQUFnQVdvZ0JUWUNBQ0FJQkVBZ0NFRjRjVUd3Q0dvaEFVR2NDQ2dDQUNFQ0FuOGdCRUVCSUFoQkEzWjBJZ054UlFSQVFZZ0lJQU1nQkhJMkFnQWdBUXdCQ3lBQktBSUlDeUVESUFFZ0FqWUNDQ0FESUFJMkFnd2dBaUFCTmdJTUlBSWdBellDQ0FzZ0FFRUlhaUVBUVp3SUlBYzJBZ0JCa0FnZ0JUWUNBQXdMQzBHTUNDZ0NBQ0lMUlEwQklBdG9RUUowUWJnS2FpZ0NBQ0lDS0FJRVFYaHhJQVpySVFNZ0FpRUJBMEFDUUNBQktBSVFJZ0JGQkVBZ0FTZ0NGQ0lBUlEwQkN5QUFLQUlFUVhoeElBWnJJZ0VnQXlBQklBTkpJZ0ViSVFNZ0FDQUNJQUViSVFJZ0FDRUJEQUVMQ3lBQ0tBSVlJUWtnQWlBQ0tBSU1JZ0JIQkVBZ0FpZ0NDQ0lCSUFBMkFnd2dBQ0FCTmdJSURBb0xJQUlvQWhRaUFRUi9JQUpCRkdvRklBSW9BaEFpQVVVTkF5QUNRUkJxQ3lFRkEwQWdCU0VISUFFaUFFRVVhaUVGSUFBb0FoUWlBUTBBSUFCQkVHb2hCU0FBS0FJUUlnRU5BQXNnQjBFQU5nSUFEQWtMUVg4aEJpQUFRYjkvU3cwQUlBQkJDMm9pQVVGNGNTRUdRWXdJS0FJQUlnZEZEUUJCSHlFSVFRQWdCbXNoQXlBQVFmVC8vd2ROQkVBZ0JrRW1JQUZCQ0habklnQnJka0VCY1NBQVFRRjBhMEUrYWlFSUN3SkFBa0FDUUNBSVFRSjBRYmdLYWlnQ0FDSUJSUVJBUVFBaEFBd0JDMEVBSVFBZ0JrRVpJQWhCQVhaclFRQWdDRUVmUnh0MElRSURRQUpBSUFFb0FnUkJlSEVnQm1zaUJDQURUdzBBSUFFaEJTQUVJZ01OQUVFQUlRTWdBU0VBREFNTElBQWdBU2dDRkNJRUlBUWdBU0FDUVIxMlFRUnhhaWdDRUNJQlJoc2dBQ0FFR3lFQUlBSkJBWFFoQWlBQkRRQUxDeUFBSUFWeVJRUkFRUUFoQlVFQ0lBaDBJZ0JCQUNBQWEzSWdCM0VpQUVVTkF5QUFhRUVDZEVHNENtb29BZ0FoQUFzZ0FFVU5BUXNEUUNBQUtBSUVRWGh4SUFacklnSWdBMGtoQVNBQ0lBTWdBUnNoQXlBQUlBVWdBUnNoQlNBQUtBSVFJZ0VFZnlBQkJTQUFLQUlVQ3lJQURRQUxDeUFGUlEwQUlBTkJrQWdvQWdBZ0JtdFBEUUFnQlNnQ0dDRUlJQVVnQlNnQ0RDSUFSd1JBSUFVb0FnZ2lBU0FBTmdJTUlBQWdBVFlDQ0F3SUN5QUZLQUlVSWdFRWZ5QUZRUlJxQlNBRktBSVFJZ0ZGRFFNZ0JVRVFhZ3NoQWdOQUlBSWhCQ0FCSWdCQkZHb2hBaUFBS0FJVUlnRU5BQ0FBUVJCcUlRSWdBQ2dDRUNJQkRRQUxJQVJCQURZQ0FBd0hDeUFHUVpBSUtBSUFJZ1ZOQkVCQm5BZ29BZ0FoQUFKQUlBVWdCbXNpQVVFUVR3UkFJQUFnQm1vaUFpQUJRUUZ5TmdJRUlBQWdCV29nQVRZQ0FDQUFJQVpCQTNJMkFnUU1BUXNnQUNBRlFRTnlOZ0lFSUFBZ0JXb2lBU0FCS0FJRVFRRnlOZ0lFUVFBaEFrRUFJUUVMUVpBSUlBRTJBZ0JCbkFnZ0FqWUNBQ0FBUVFocUlRQU1DUXNnQmtHVUNDZ0NBQ0lDU1FSQVFaUUlJQUlnQm1zaUFUWUNBRUdnQ0VHZ0NDZ0NBQ0lBSUFacUlnSTJBZ0FnQWlBQlFRRnlOZ0lFSUFBZ0JrRURjallDQkNBQVFRaHFJUUFNQ1F0QkFDRUFJQVpCTDJvaUF3Si9RZUFMS0FJQUJFQkI2QXNvQWdBTUFRdEI3QXRDZnpjQ0FFSGtDMEtBb0lDQWdJQUVOd0lBUWVBTElBcEJER3BCY0hGQjJLclZxZ1Z6TmdJQVFmUUxRUUEyQWdCQnhBdEJBRFlDQUVHQUlBc2lBV29pQkVFQUlBRnJJZ2R4SWdFZ0JrME5DRUhBQ3lnQ0FDSUZCRUJCdUFzb0FnQWlDQ0FCYWlJSklBaE5JQVVnQ1VseURRa0xBa0JCeEFzdEFBQkJCSEZGQkVBQ1FBSkFBa0FDUUVHZ0NDZ0NBQ0lGQkVCQnlBc2hBQU5BSUFBb0FnQWlDQ0FGVFFSQUlBVWdDQ0FBS0FJRWFra05Bd3NnQUNnQ0NDSUFEUUFMQzBFQUVBRWlBa0YvUmcwRElBRWhCRUhrQ3lnQ0FDSUFRUUZySWdVZ0FuRUVRQ0FCSUFKcklBSWdCV3BCQUNBQWEzRnFJUVFMSUFRZ0JrME5BMEhBQ3lnQ0FDSUFCRUJCdUFzb0FnQWlCU0FFYWlJSElBVk5JQUFnQjBseURRUUxJQVFRQVNJQUlBSkhEUUVNQlFzZ0JDQUNheUFIY1NJRUVBRWlBaUFBS0FJQUlBQW9BZ1JxUmcwQklBSWhBQXNnQUVGL1JnMEJJQVpCTUdvZ0JFMEVRQ0FBSVFJTUJBdEI2QXNvQWdBaUFpQURJQVJyYWtFQUlBSnJjU0lDRUFGQmYwWU5BU0FDSUFScUlRUWdBQ0VDREFNTElBSkJmMGNOQWd0QnhBdEJ4QXNvQWdCQkJISTJBZ0FMSUFFUUFTSUNRWDlHUVFBUUFTSUFRWDlHY2lBQUlBSk5jZzBGSUFBZ0Ftc2lCQ0FHUVNocVRRMEZDMEc0QzBHNEN5Z0NBQ0FFYWlJQU5nSUFRYndMS0FJQUlBQkpCRUJCdkFzZ0FEWUNBQXNDUUVHZ0NDZ0NBQ0lEQkVCQnlBc2hBQU5BSUFJZ0FDZ0NBQ0lCSUFBb0FnUWlCV3BHRFFJZ0FDZ0NDQ0lBRFFBTERBUUxRWmdJS0FJQUlnQkJBQ0FBSUFKTkcwVUVRRUdZQ0NBQ05nSUFDMEVBSVFCQnpBc2dCRFlDQUVISUN5QUNOZ0lBUWFnSVFYODJBZ0JCckFoQjRBc29BZ0EyQWdCQjFBdEJBRFlDQUFOQUlBQkJBM1FpQVVHNENHb2dBVUd3Q0dvaUJUWUNBQ0FCUWJ3SWFpQUZOZ0lBSUFCQkFXb2lBRUVnUncwQUMwR1VDQ0FFUVNocklnQkJlQ0FDYTBFSGNTSUJheUlGTmdJQVFhQUlJQUVnQW1vaUFUWUNBQ0FCSUFWQkFYSTJBZ1FnQUNBQ2FrRW9OZ0lFUWFRSVFmQUxLQUlBTmdJQURBUUxJQUlnQTAwZ0FTQURTM0lOQWlBQUtBSU1RUWh4RFFJZ0FDQUVJQVZxTmdJRVFhQUlJQU5CZUNBRGEwRUhjU0lBYWlJQk5nSUFRWlFJUVpRSUtBSUFJQVJxSWdJZ0FHc2lBRFlDQUNBQklBQkJBWEkyQWdRZ0FpQURha0VvTmdJRVFhUUlRZkFMS0FJQU5nSUFEQU1MUVFBaEFBd0dDMEVBSVFBTUJBdEJtQWdvQWdBZ0Frc0VRRUdZQ0NBQ05nSUFDeUFDSUFScUlRVkJ5QXNoQUFKQUEwQWdCU0FBS0FJQUlnRkhCRUFnQUNnQ0NDSUFEUUVNQWdzTElBQXRBQXhCQ0hGRkRRTUxRY2dMSVFBRFFBSkFJQUFvQWdBaUFTQURUUVJBSUFNZ0FTQUFLQUlFYWlJRlNRMEJDeUFBS0FJSUlRQU1BUXNMUVpRSUlBUkJLR3NpQUVGNElBSnJRUWR4SWdGcklnYzJBZ0JCb0FnZ0FTQUNhaUlCTmdJQUlBRWdCMEVCY2pZQ0JDQUFJQUpxUVNnMkFnUkJwQWhCOEFzb0FnQTJBZ0FnQXlBRlFTY2dCV3RCQjNGcVFTOXJJZ0FnQUNBRFFSQnFTUnNpQVVFYk5nSUVJQUZCMEFzcEFnQTNBaEFnQVVISUN5a0NBRGNDQ0VIUUN5QUJRUWhxTmdJQVFjd0xJQVEyQWdCQnlBc2dBallDQUVIVUMwRUFOZ0lBSUFGQkdHb2hBQU5BSUFCQkJ6WUNCQ0FBUVFocUlBQkJCR29oQUNBRlNRMEFDeUFCSUFOR0RRQWdBU0FCS0FJRVFYNXhOZ0lFSUFNZ0FTQURheUlDUVFGeU5nSUVJQUVnQWpZQ0FBSi9JQUpCL3dGTkJFQWdBa0Y0Y1VHd0NHb2hBQUovUVlnSUtBSUFJZ0ZCQVNBQ1FRTjJkQ0lDY1VVRVFFR0lDQ0FCSUFKeU5nSUFJQUFNQVFzZ0FDZ0NDQXNoQVNBQUlBTTJBZ2dnQVNBRE5nSU1RUXdoQWtFSURBRUxRUjhoQUNBQ1FmLy8vd2ROQkVBZ0FrRW1JQUpCQ0habklnQnJka0VCY1NBQVFRRjBhMEUrYWlFQUN5QURJQUEyQWh3Z0EwSUFOd0lRSUFCQkFuUkJ1QXBxSVFFQ1FBSkFRWXdJS0FJQUlnVkJBU0FBZENJRWNVVUVRRUdNQ0NBRUlBVnlOZ0lBSUFFZ0F6WUNBQXdCQ3lBQ1FSa2dBRUVCZG10QkFDQUFRUjlIRzNRaEFDQUJLQUlBSVFVRFFDQUZJZ0VvQWdSQmVIRWdBa1lOQWlBQVFSMTJJUVVnQUVFQmRDRUFJQUVnQlVFRWNXb2lCQ2dDRUNJRkRRQUxJQVFnQXpZQ0VBc2dBeUFCTmdJWVFRZ2hBaUFESWdFaEFFRU1EQUVMSUFFb0FnZ2lBQ0FETmdJTUlBRWdBellDQ0NBRElBQTJBZ2hCQUNFQVFSZ2hBa0VNQ3lBRGFpQUJOZ0lBSUFJZ0Eyb2dBRFlDQUF0QmxBZ29BZ0FpQUNBR1RRMEFRWlFJSUFBZ0Jtc2lBVFlDQUVHZ0NFR2dDQ2dDQUNJQUlBWnFJZ0kyQWdBZ0FpQUJRUUZ5TmdJRUlBQWdCa0VEY2pZQ0JDQUFRUWhxSVFBTUJBdEJoQWhCTURZQ0FFRUFJUUFNQXdzZ0FDQUNOZ0lBSUFBZ0FDZ0NCQ0FFYWpZQ0JDQUNRWGdnQW10QkIzRnFJZ2dnQmtFRGNqWUNCQ0FCUVhnZ0FXdEJCM0ZxSWdRZ0JpQUlhaUlEYXlFSEFrQkJvQWdvQWdBZ0JFWUVRRUdnQ0NBRE5nSUFRWlFJUVpRSUtBSUFJQWRxSWdBMkFnQWdBeUFBUVFGeU5nSUVEQUVMUVp3SUtBSUFJQVJHQkVCQm5BZ2dBellDQUVHUUNFR1FDQ2dDQUNBSGFpSUFOZ0lBSUFNZ0FFRUJjallDQkNBQUlBTnFJQUEyQWdBTUFRc2dCQ2dDQkNJQVFRTnhRUUZHQkVBZ0FFRjRjU0VKSUFRb0Fnd2hBZ0pBSUFCQi93Rk5CRUFnQkNnQ0NDSUJJQUpHQkVCQmlBaEJpQWdvQWdCQmZpQUFRUU4yZDNFMkFnQU1BZ3NnQVNBQ05nSU1JQUlnQVRZQ0NBd0JDeUFFS0FJWUlRWUNRQ0FDSUFSSEJFQWdCQ2dDQ0NJQUlBSTJBZ3dnQWlBQU5nSUlEQUVMQWtBZ0JDZ0NGQ0lBQkg4Z0JFRVVhZ1VnQkNnQ0VDSUFSUTBCSUFSQkVHb0xJUUVEUUNBQklRVWdBQ0lDUVJScUlRRWdBQ2dDRkNJQURRQWdBa0VRYWlFQklBSW9BaEFpQUEwQUN5QUZRUUEyQWdBTUFRdEJBQ0VDQ3lBR1JRMEFBa0FnQkNnQ0hDSUFRUUowUWJnS2FpSUJLQUlBSUFSR0JFQWdBU0FDTmdJQUlBSU5BVUdNQ0VHTUNDZ0NBRUYrSUFCM2NUWUNBQXdDQ3dKQUlBUWdCaWdDRUVZRVFDQUdJQUkyQWhBTUFRc2dCaUFDTmdJVUN5QUNSUTBCQ3lBQ0lBWTJBaGdnQkNnQ0VDSUFCRUFnQWlBQU5nSVFJQUFnQWpZQ0dBc2dCQ2dDRkNJQVJRMEFJQUlnQURZQ0ZDQUFJQUkyQWhnTElBY2dDV29oQnlBRUlBbHFJZ1FvQWdRaEFBc2dCQ0FBUVg1eE5nSUVJQU1nQjBFQmNqWUNCQ0FESUFkcUlBYzJBZ0FnQjBIL0FVMEVRQ0FIUVhoeFFiQUlhaUVBQW45QmlBZ29BZ0FpQVVFQklBZEJBM1owSWdKeFJRUkFRWWdJSUFFZ0FuSTJBZ0FnQUF3QkN5QUFLQUlJQ3lFQklBQWdBellDQ0NBQklBTTJBZ3dnQXlBQU5nSU1JQU1nQVRZQ0NBd0JDMEVmSVFJZ0IwSC8vLzhIVFFSQUlBZEJKaUFIUVFoMlp5SUFhM1pCQVhFZ0FFRUJkR3RCUG1vaEFnc2dBeUFDTmdJY0lBTkNBRGNDRUNBQ1FRSjBRYmdLYWlFQUFrQUNRRUdNQ0NnQ0FDSUJRUUVnQW5RaUJYRkZCRUJCakFnZ0FTQUZjallDQUNBQUlBTTJBZ0FNQVFzZ0IwRVpJQUpCQVhaclFRQWdBa0VmUnh0MElRSWdBQ2dDQUNFQkEwQWdBU0lBS0FJRVFYaHhJQWRHRFFJZ0FrRWRkaUVCSUFKQkFYUWhBaUFBSUFGQkJIRnFJZ1VvQWhBaUFRMEFDeUFGSUFNMkFoQUxJQU1nQURZQ0dDQURJQU0yQWd3Z0F5QUROZ0lJREFFTElBQW9BZ2dpQVNBRE5nSU1JQUFnQXpZQ0NDQURRUUEyQWhnZ0F5QUFOZ0lNSUFNZ0FUWUNDQXNnQ0VFSWFpRUFEQUlMQWtBZ0NFVU5BQUpBSUFVb0Fod2lBVUVDZEVHNENtb2lBaWdDQUNBRlJnUkFJQUlnQURZQ0FDQUFEUUZCakFnZ0IwRitJQUYzY1NJSE5nSUFEQUlMQWtBZ0JTQUlLQUlRUmdSQUlBZ2dBRFlDRUF3QkN5QUlJQUEyQWhRTElBQkZEUUVMSUFBZ0NEWUNHQ0FGS0FJUUlnRUVRQ0FBSUFFMkFoQWdBU0FBTmdJWUN5QUZLQUlVSWdGRkRRQWdBQ0FCTmdJVUlBRWdBRFlDR0FzQ1FDQURRUTlOQkVBZ0JTQURJQVpxSWdCQkEzSTJBZ1FnQUNBRmFpSUFJQUFvQWdSQkFYSTJBZ1FNQVFzZ0JTQUdRUU55TmdJRUlBVWdCbW9pQkNBRFFRRnlOZ0lFSUFNZ0JHb2dBellDQUNBRFFmOEJUUVJBSUFOQmVIRkJzQWhxSVFBQ2YwR0lDQ2dDQUNJQlFRRWdBMEVEZG5RaUFuRkZCRUJCaUFnZ0FTQUNjallDQUNBQURBRUxJQUFvQWdnTElRRWdBQ0FFTmdJSUlBRWdCRFlDRENBRUlBQTJBZ3dnQkNBQk5nSUlEQUVMUVI4aEFDQURRZi8vL3dkTkJFQWdBMEVtSUFOQkNIWm5JZ0JyZGtFQmNTQUFRUUYwYTBFK2FpRUFDeUFFSUFBMkFod2dCRUlBTndJUUlBQkJBblJCdUFwcUlRRUNRQUpBSUFkQkFTQUFkQ0lDY1VVRVFFR01DQ0FDSUFkeU5nSUFJQUVnQkRZQ0FDQUVJQUUyQWhnTUFRc2dBMEVaSUFCQkFYWnJRUUFnQUVFZlJ4dDBJUUFnQVNnQ0FDRUJBMEFnQVNJQ0tBSUVRWGh4SUFOR0RRSWdBRUVkZGlFQklBQkJBWFFoQUNBQ0lBRkJCSEZxSWdjb0FoQWlBUTBBQ3lBSElBUTJBaEFnQkNBQ05nSVlDeUFFSUFRMkFnd2dCQ0FFTmdJSURBRUxJQUlvQWdnaUFDQUVOZ0lNSUFJZ0JEWUNDQ0FFUVFBMkFoZ2dCQ0FDTmdJTUlBUWdBRFlDQ0FzZ0JVRUlhaUVBREFFTEFrQWdDVVVOQUFKQUlBSW9BaHdpQVVFQ2RFRzRDbW9pQlNnQ0FDQUNSZ1JBSUFVZ0FEWUNBQ0FBRFFGQmpBZ2dDMEYrSUFGM2NUWUNBQXdDQ3dKQUlBSWdDU2dDRUVZRVFDQUpJQUEyQWhBTUFRc2dDU0FBTmdJVUN5QUFSUTBCQ3lBQUlBazJBaGdnQWlnQ0VDSUJCRUFnQUNBQk5nSVFJQUVnQURZQ0dBc2dBaWdDRkNJQlJRMEFJQUFnQVRZQ0ZDQUJJQUEyQWhnTEFrQWdBMEVQVFFSQUlBSWdBeUFHYWlJQVFRTnlOZ0lFSUFBZ0Ftb2lBQ0FBS0FJRVFRRnlOZ0lFREFFTElBSWdCa0VEY2pZQ0JDQUNJQVpxSWdVZ0EwRUJjallDQkNBRElBVnFJQU0yQWdBZ0NBUkFJQWhCZUhGQnNBaHFJUUJCbkFnb0FnQWhBUUovUVFFZ0NFRURkblFpQnlBRWNVVUVRRUdJQ0NBRUlBZHlOZ0lBSUFBTUFRc2dBQ2dDQ0FzaEJDQUFJQUUyQWdnZ0JDQUJOZ0lNSUFFZ0FEWUNEQ0FCSUFRMkFnZ0xRWndJSUFVMkFnQkJrQWdnQXpZQ0FBc2dBa0VJYWlFQUN5QUtRUkJxSkFBZ0FBdkdCQUlHZndwOVFmLy8vLzhISVF4QmdJQ0FnSGdoRFVGL0lRa0RRQ0FESUFwR0JFQkJBQ0VBSUFoQkFFR0FnQkQ4Q3dCREFQOS9SeUFOSUF4cnNwVWhEd1VnQkNBS1FReHNhaUlMS2dJQUlSTWdDeW9DQ0NFVUlBc3FBZ1FoRlNBSklBSWdDa0VDZENJT2FpZ0NBQ0lMUndSQUlBRWdDMEhRQUd4cUlna3FBandnQUNvQ09DSVBsQ0FKS2dJNElBQXFBaWdpRUpRZ0NTb0NNQ0FBS2dJSUloR1VJQUFxQWhnaUVpQUpLZ0kwbEpLU2tpRVdJQWtxQWl3Z0Q1UWdDU29DS0NBUWxDQUpLZ0lnSUJHVUlCSWdDU29DSkpTU2twSWhGeUFKS2dJY0lBK1VJQWtxQWhnZ0VKUWdDU29DRUNBUmxDQVNJQWtxQWhTVWtwS1NJUmdnQ1NvQ0RDQVBsQ0FKS2dJSUlCQ1VJQWtxQWdBZ0VaUWdDU29DQkNBU2xKS1NraUVQSUFzaENRc2dCU0FPYWlBV0lCY2dGSlFnRHlBVGxDQVZJQmlVa3BLU1F3QUFnRVdVL0FBaUN6WUNBQ0FNSUFzZ0N5QU1TaHNoRENBTklBc2dDeUFOU0JzaERTQUtRUUZxSVFvTUFRc0xBMEFnQUNBRFJrVUVRQ0FGSUFCQkFuUnFJZ0VnRHlBQktBSUFJQXhyczVUOEFTSUJOZ0lBSUFnZ0FVRUNkR29pQVNBQktBSUFRUUZxTmdJQUlBQkJBV29oQUF3QkN3dEJBQ0VBSUFkQkFEWUNBQ0FJUVFScklRRkJBQ0VNUVFFaENnTkFJQXBCZ0lBRVJnUkFBMEFDUUNBQUlBTkdEUUFnQnlBRklBQkJBblJxS0FJQVFRSjBhaUlCSUFFb0FnQWlBVUVCYWpZQ0FDQUdJQUZCQW5ScUlBQTJBZ0FnQUVFQmFpRUFEQUVMQ3dVZ0J5QUtRUUowSWdKcUlBRWdBbW9vQWdBZ0RHb2lERFlDQUNBS1FRRnFJUW9NQVFzTEN3SUFDd3NKQVFCQmdRZ0xBZ1lCIik7CiAgfQogIGZ1bmN0aW9uIE8oQSkgewogICAgaWYgKEFycmF5QnVmZmVyLmlzVmlldyhBKSkKICAgICAgcmV0dXJuIEE7CiAgICBpZiAoQSA9PSBTICYmIE0pCiAgICAgIHJldHVybiBuZXcgVWludDhBcnJheShNKTsKICAgIGlmIChVKQogICAgICByZXR1cm4gVShBKTsKICAgIHRocm93ICdzeW5jIGZldGNoaW5nIG9mIHRoZSB3YXNtIGZhaWxlZDogeW91IGNhbiBwcmVsb2FkIGl0IHRvIE1vZHVsZVsid2FzbUJpbmFyeSJdIG1hbnVhbGx5LCBvciBlbWNjLnB5IHdpbGwgZG8gdGhhdCBmb3IgeW91IHdoZW4gZ2VuZXJhdGluZyBIVE1MIChidXQgbm90IEpTKSc7CiAgfQogIGZ1bmN0aW9uICQoQSwgQikgewogICAgdmFyIHQsIEUgPSBPKEEpOwogICAgdCA9IG5ldyBXZWJBc3NlbWJseS5Nb2R1bGUoRSk7CiAgICB2YXIgaSA9IG5ldyBXZWJBc3NlbWJseS5JbnN0YW5jZSh0LCBCKTsKICAgIHJldHVybiBbaSwgdF07CiAgfQogIGZ1bmN0aW9uIEFBKCkgewogICAgcmV0dXJuIHsgYTogbkEgfTsKICB9CiAgZnVuY3Rpb24gSUEoKSB7CiAgICBmdW5jdGlvbiBBKEUsIGkpIHsKICAgICAgcmV0dXJuIHkgPSBFLmV4cG9ydHMsIHUgPSB5LmIsIHEoKSwgckEoeSksIHooKSwgeTsKICAgIH0KICAgIF8oKTsKICAgIHZhciBCID0gQUEoKTsKICAgIGlmIChJLmluc3RhbnRpYXRlV2FzbSkKICAgICAgcmV0dXJuIG5ldyBQcm9taXNlKChFLCBpKSA9PiB7CiAgICAgICAgSS5pbnN0YW50aWF0ZVdhc20oQiwgKG8sIGgpID0+IHsKICAgICAgICAgIEUoQShvKSk7CiAgICAgICAgfSk7CiAgICAgIH0pOwogICAgUyA/Pz0gVigpOwogICAgdmFyIHQgPSAkKFMsIEIpOwogICAgcmV0dXJuIEEodFswXSk7CiAgfQogIGZvciAodmFyIHggPSAoQSkgPT4gewogICAgZm9yICg7IEEubGVuZ3RoID4gMDsgKQogICAgICBBLnNoaWZ0KCkoSSk7CiAgfSwgdiA9IFtdLCBnQSA9IChBKSA9PiB2LnB1c2goQSksIFQgPSBbXSwgQ0EgPSAoQSkgPT4gVC5wdXNoKEEpLCBCQSA9IChBKSA9PiB7CiAgICBmb3IgKHZhciBCLCB0LCBFID0gMCwgaSA9IDAsIG8gPSBBLmxlbmd0aCwgaCA9IG5ldyBVaW50OEFycmF5KChvICogMyA+PiAyKSAtIChBW28gLSAyXSA9PSAiPSIpIC0gKEFbbyAtIDFdID09ICI9IikpOyBFIDwgbzsgRSArPSA0LCBpICs9IDMpCiAgICAgIEIgPSBuW0EuY2hhckNvZGVBdChFICsgMSldLCB0ID0gbltBLmNoYXJDb2RlQXQoRSArIDIpXSwgaFtpXSA9IG5bQS5jaGFyQ29kZUF0KEUpXSA8PCAyIHwgQiA+PiA0LCBoW2kgKyAxXSA9IEIgPDwgNCB8IHQgPj4gMiwgaFtpICsgMl0gPSB0IDw8IDYgfCBuW0EuY2hhckNvZGVBdChFICsgMyldOwogICAgcmV0dXJuIGg7CiAgfSwgUUEgPSAoKSA9PiAyMTQ3NDgzNjQ4LCBFQSA9IChBLCBCKSA9PiBNYXRoLmNlaWwoQSAvIEIpICogQiwgdEEgPSAoQSkgPT4gewogICAgdmFyIEIgPSB1LmJ1ZmZlciwgdCA9IChBIC0gQi5ieXRlTGVuZ3RoICsgNjU1MzUpIC8gNjU1MzYgfCAwOwogICAgdHJ5IHsKICAgICAgcmV0dXJuIHUuZ3Jvdyh0KSwgcSgpLCAxOwogICAgfSBjYXRjaCB7CiAgICB9CiAgfSwgaUEgPSAoQSkgPT4gewogICAgdmFyIEIgPSBMLmxlbmd0aDsKICAgIEEgPj4+PSAwOwogICAgdmFyIHQgPSBRQSgpOwogICAgaWYgKEEgPiB0KQogICAgICByZXR1cm4gITE7CiAgICBmb3IgKHZhciBFID0gMTsgRSA8PSA0OyBFICo9IDIpIHsKICAgICAgdmFyIGkgPSBCICogKDEgKyAwLjIgLyBFKTsKICAgICAgaSA9IE1hdGgubWluKGksIEEgKyAxMDA2NjMyOTYpOwogICAgICB2YXIgbyA9IE1hdGgubWluKHQsIEVBKE1hdGgubWF4KEEsIGkpLCA2NTUzNikpLCBoID0gdEEobyk7CiAgICAgIGlmIChoKQogICAgICAgIHJldHVybiAhMDsKICAgIH0KICAgIHJldHVybiAhMTsKICB9LCBuID0gbmV3IFVpbnQ4QXJyYXkoMTIzKSwgZSA9IDI1OyBlID49IDA7IC0tZSkKICAgIG5bNDggKyBlXSA9IDUyICsgZSwgbls2NSArIGVdID0gZSwgbls5NyArIGVdID0gMjYgKyBlOwogIG5bNDNdID0gNjIsIG5bNDddID0gNjMsIEkubm9FeGl0UnVudGltZSAmJiBJLm5vRXhpdFJ1bnRpbWUsIEkucHJpbnQgJiYgSS5wcmludCwgSS5wcmludEVyciAmJiBJLnByaW50RXJyLCBJLndhc21CaW5hcnkgJiYgKE0gPSBJLndhc21CaW5hcnkpLCBJLmFyZ3VtZW50cyAmJiBJLmFyZ3VtZW50cywgSS50aGlzUHJvZ3JhbSAmJiBJLnRoaXNQcm9ncmFtOwogIGZ1bmN0aW9uIHJBKEEpIHsKICAgIEkuX3NvcnQgPSBBLmQsIEkuX21hbGxvYyA9IEEuZSwgSS5fZnJlZSA9IEEuZjsKICB9CiAgdmFyIG5BID0geyBhOiBpQSB9LCB5ID0gSUEoKTsKICBmdW5jdGlvbiBtKCkgewogICAgaWYgKHMgPiAwKSB7CiAgICAgIGYgPSBtOwogICAgICByZXR1cm47CiAgICB9CiAgICBpZiAoUCgpLCBzID4gMCkgewogICAgICBmID0gbTsKICAgICAgcmV0dXJuOwogICAgfQogICAgZnVuY3Rpb24gQSgpIHsKICAgICAgSS5jYWxsZWRSdW4gPSAhMCwgYigpLCBJLm9uUnVudGltZUluaXRpYWxpemVkPy4oKSwgVygpOwogICAgfQogICAgSS5zZXRTdGF0dXMgPyAoSS5zZXRTdGF0dXMoIlJ1bm5pbmcuLi4iKSwgc2V0VGltZW91dCgoKSA9PiB7CiAgICAgIHNldFRpbWVvdXQoKCkgPT4gSS5zZXRTdGF0dXMoIiIpLCAxKSwgQSgpOwogICAgfSwgMSkpIDogQSgpOwogIH0KICBmdW5jdGlvbiBhQSgpIHsKICAgIGlmIChJLnByZUluaXQpCiAgICAgIGZvciAodHlwZW9mIEkucHJlSW5pdCA9PSAiZnVuY3Rpb24iICYmIChJLnByZUluaXQgPSBbSS5wcmVJbml0XSk7IEkucHJlSW5pdC5sZW5ndGggPiAwOyApCiAgICAgICAgSS5wcmVJbml0LnNoaWZ0KCkoKTsKICB9CiAgcmV0dXJuIGFBKCksIG0oKSwgciA9IEksIHI7Cn07CmxldCBnLCBRLCBkLCBjLCBOLCB3LCBwLCBSLCBrLCBKLCBhID0gMCwgWSA9IDAsIEggPSBbXSwgRyA9ICEwLCBEID0gITEsIEYgPSAhMSwgSyA9ICExOwphc3luYyBmdW5jdGlvbiBvQSgpIHsKICBpZiAoIWcgJiYgKGcgPSBhd2FpdCBlQSgpLCAhZyB8fCAhZy5IRUFQRjMyIHx8ICFnLl9zb3J0KSkKICAgIHRocm93IG5ldyBFcnJvcigiV0FTTSBtb2R1bGUgZmFpbGVkIHRvIGluaXRpYWxpemUgcHJvcGVybHkiKTsKfQpjb25zdCBaID0gYXN5bmMgKCkgPT4gewogIGlmIChEKSB7CiAgICBGID0gITA7CiAgICByZXR1cm47CiAgfQogIEQgPSAhMCwgRiA9ICExLCBnIHx8IGF3YWl0IG9BKCk7CiAgY29uc3QgQyA9IE1hdGgucG93KDIsIE1hdGguY2VpbChNYXRoLmxvZzIoUS52ZXJ0ZXhDb3VudCkpKTsKICBhIDwgQyAmJiAoYSA+IDAgJiYgKGcuX2ZyZWUoZCksIGcuX2ZyZWUoTiksIGcuX2ZyZWUodyksIGcuX2ZyZWUocCksIGcuX2ZyZWUoUiksIGcuX2ZyZWUoayksIGcuX2ZyZWUoSikpLCBhID0gQywgZCA9IGcuX21hbGxvYygxNiAqIDQpLCBOID0gZy5fbWFsbG9jKGEgKiA0KSwgdyA9IGcuX21hbGxvYygzICogYSAqIDQpLCBwID0gZy5fbWFsbG9jKGEgKiA0KSwgUiA9IGcuX21hbGxvYyhhICogNCksIGsgPSBnLl9tYWxsb2MoYSAqIDQpLCBKID0gZy5fbWFsbG9jKGEgKiA0KSksIFkgPCBRLnRyYW5zZm9ybXMubGVuZ3RoICYmIChZID4gMCAmJiBnLl9mcmVlKGMpLCBZID0gUS50cmFuc2Zvcm1zLmxlbmd0aCwgYyA9IGcuX21hbGxvYyhZICogNCkpLCBEID0gITEsIEYgJiYgKEYgPSAhMSwgYXdhaXQgWigpKTsKfSwgc0EgPSAoKSA9PiB7CiAgaWYgKCEoRCB8fCBGIHx8ICFnIHx8ICFRKSkgewogICAgRCA9ICEwOwogICAgdHJ5IHsKICAgICAgY29uc3QgQyA9IGcuSEVBUEYzMiwgciA9IGcuSEVBUFUzMjsKICAgICAgaWYgKHcgLyA0ICsgUS5wb3NpdGlvbnMubGVuZ3RoID4gQy5sZW5ndGgpCiAgICAgICAgdGhyb3cgbmV3IEVycm9yKCJQb3NpdGlvbnMgYnVmZmVyIG92ZXJmbG93Iik7CiAgICAgIGlmIChjIC8gNCArIFEudHJhbnNmb3Jtcy5sZW5ndGggPiBDLmxlbmd0aCkKICAgICAgICB0aHJvdyBuZXcgRXJyb3IoIlRyYW5zZm9ybXMgYnVmZmVyIG92ZXJmbG93Iik7CiAgICAgIGlmIChOIC8gNCArIFEudHJhbnNmb3JtSW5kaWNlcy5sZW5ndGggPiByLmxlbmd0aCkKICAgICAgICB0aHJvdyBuZXcgRXJyb3IoIlRyYW5zZm9ybSBpbmRpY2VzIGJ1ZmZlciBvdmVyZmxvdyIpOwogICAgICBpZiAoQy5zZXQoUS5wb3NpdGlvbnMsIHcgLyA0KSwgQy5zZXQoUS50cmFuc2Zvcm1zLCBjIC8gNCksIHIuc2V0KFEudHJhbnNmb3JtSW5kaWNlcywgTiAvIDQpLCBDLnNldChuZXcgRmxvYXQzMkFycmF5KEgpLCBkIC8gNCksIGcuX3NvcnQoCiAgICAgICAgZCwKICAgICAgICBjLAogICAgICAgIE4sCiAgICAgICAgUS52ZXJ0ZXhDb3VudCwKICAgICAgICB3LAogICAgICAgIHAsCiAgICAgICAgUiwKICAgICAgICBrLAogICAgICAgIEoKICAgICAgKSwgUiArIFEudmVydGV4Q291bnQgKiA0ID4gci5idWZmZXIuYnl0ZUxlbmd0aCkKICAgICAgICB0aHJvdyBuZXcgRXJyb3IoIkRlcHRoIGluZGV4IGJ1ZmZlciBvdmVyZmxvdyIpOwogICAgICBjb25zdCBJID0gbmV3IFVpbnQzMkFycmF5KHIuYnVmZmVyLCBSLCBRLnZlcnRleENvdW50KSwgbCA9IG5ldyBVaW50MzJBcnJheShJLnNsaWNlKCkuYnVmZmVyKTsKICAgICAgc2VsZi5wb3N0TWVzc2FnZSh7IGRlcHRoSW5kZXg6IGwgfSwgW2wuYnVmZmVyXSk7CiAgICB9IGNhdGNoIHsKICAgICAgc2VsZi5wb3N0TWVzc2FnZSh7IGRlcHRoSW5kZXg6IG5ldyBVaW50MzJBcnJheSgwKSB9LCBbXSk7CiAgICB9CiAgICBEID0gITEsIEcgPSAhMTsKICB9Cn0sIFggPSAoKSA9PiB7CiAgSyB8fCAoSyA9ICEwLCBHICYmIHNBKCksIHNldFRpbWVvdXQoKCkgPT4gewogICAgSyA9ICExLCBYKCk7CiAgfSkpOwp9OwpzZWxmLm9ubWVzc2FnZSA9IChDKSA9PiB7CiAgQy5kYXRhLnNvcnREYXRhICYmIChRID8gKFEucG9zaXRpb25zLnNldChDLmRhdGEuc29ydERhdGEucG9zaXRpb25zKSwgUS50cmFuc2Zvcm1zLnNldChDLmRhdGEuc29ydERhdGEudHJhbnNmb3JtcyksIFEudHJhbnNmb3JtSW5kaWNlcy5zZXQoQy5kYXRhLnNvcnREYXRhLnRyYW5zZm9ybUluZGljZXMpLCBRLnZlcnRleENvdW50ID0gQy5kYXRhLnNvcnREYXRhLnZlcnRleENvdW50KSA6IFEgPSB7CiAgICBwb3NpdGlvbnM6IG5ldyBGbG9hdDMyQXJyYXkoQy5kYXRhLnNvcnREYXRhLnBvc2l0aW9ucyksCiAgICB0cmFuc2Zvcm1zOiBuZXcgRmxvYXQzMkFycmF5KEMuZGF0YS5zb3J0RGF0YS50cmFuc2Zvcm1zKSwKICAgIHRyYW5zZm9ybUluZGljZXM6IG5ldyBVaW50MzJBcnJheShDLmRhdGEuc29ydERhdGEudHJhbnNmb3JtSW5kaWNlcyksCiAgICB2ZXJ0ZXhDb3VudDogQy5kYXRhLnNvcnREYXRhLnZlcnRleENvdW50CiAgfSwgRyA9ICEwLCBaKCkpLCBDLmRhdGEudmlld1Byb2ogJiYgKEMuZGF0YS52aWV3UHJvai5ldmVyeSgocikgPT4gSC5pbmNsdWRlcyhyKSkgPT09ICExICYmIChIID0gQy5kYXRhLnZpZXdQcm9qLCBHID0gITApLCBYKCkpOwp9OwovLyMgc291cmNlTWFwcGluZ1VSTD1Tb3J0V29ya2VyLURRTDdVVEVoLmpzLm1hcAo="; + var Et = (E) => Uint8Array.from(atob(E), (t) => t.charCodeAt(0)); + var Qt = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", Et(Bt)], { type: "text/javascript;charset=utf-8" }); + function St(E) { + let t; + try { + if (t = Qt && (self.URL || self.webkitURL).createObjectURL(Qt), !t) throw ""; + const n = new Worker(t, { + type: "module", + name: E?.name + }); + return n.addEventListener("error", () => { + (self.URL || self.webkitURL).revokeObjectURL(t); + }), n; + } catch { + return new Worker( + "data:text/javascript;base64," + Bt, + { + type: "module", + name: E?.name + } + ); + } + } + var lt = class { + constructor(t, n) { + this._scene = null, this._camera = null, this._started = false, this._initialized = false, this._renderer = t; + const i = t.gl; + this._program = i.createProgram(), this._passes = n || []; + const e = i.createShader(i.VERTEX_SHADER); + i.shaderSource(e, this._getVertexSource()), i.compileShader(e), i.getShaderParameter(e, i.COMPILE_STATUS) || console.error(i.getShaderInfoLog(e)); + const A = i.createShader(i.FRAGMENT_SHADER); + i.shaderSource(A, this._getFragmentSource()), i.compileShader(A), i.getShaderParameter(A, i.COMPILE_STATUS) || console.error(i.getShaderInfoLog(A)), i.attachShader(this.program, e), i.attachShader(this.program, A), i.linkProgram(this.program), i.getProgramParameter(this.program, i.LINK_STATUS) || console.error(i.getProgramInfoLog(this.program)), this.resize = () => { + i.useProgram(this._program), this._resize(); + }, this.initialize = () => { + console.assert(!this._initialized, "ShaderProgram already initialized"), i.useProgram(this._program), this._initialize(); + for (const o of this.passes) + o.initialize(this); + this._initialized = true, this._started = true; + }, this.render = (o, s) => { + i.useProgram(this._program), (this._scene !== o || this._camera !== s) && (this.dispose(), this._scene = o, this._camera = s, this.initialize()); + for (const r of this.passes) + r.render(); + this._render(); + }, this.dispose = () => { + if (this._initialized) { + i.useProgram(this._program); + for (const o of this.passes) + o.dispose(); + this._dispose(), this._scene = null, this._camera = null, this._initialized = false; + } + }; + } + get renderer() { + return this._renderer; + } + get scene() { + return this._scene; + } + get camera() { + return this._camera; + } + get program() { + return this._program; + } + get passes() { + return this._passes; + } + get started() { + return this._started; + } + }; + var gt = "dmFyIG9BID0gZnVuY3Rpb24oQyA9IHt9KSB7CiAgdmFyIGUsIEEgPSBDLCBoID0gaW1wb3J0Lm1ldGEudXJsLCBrID0gIiIsIHk7CiAgewogICAgdHJ5IHsKICAgICAgayA9IG5ldyBVUkwoIi4iLCBoKS5ocmVmOwogICAgfSBjYXRjaCB7CiAgICB9CiAgICB5ID0gKGcpID0+IHsKICAgICAgdmFyIEIgPSBuZXcgWE1MSHR0cFJlcXVlc3QoKTsKICAgICAgcmV0dXJuIEIub3BlbigiR0VUIiwgZywgITEpLCBCLnJlc3BvbnNlVHlwZSA9ICJhcnJheWJ1ZmZlciIsIEIuc2VuZChudWxsKSwgbmV3IFVpbnQ4QXJyYXkoQi5yZXNwb25zZSk7CiAgICB9OwogIH0KICBjb25zb2xlLmxvZy5iaW5kKGNvbnNvbGUpLCBjb25zb2xlLmVycm9yLmJpbmQoY29uc29sZSk7CiAgdmFyIEYsIEQsIE47CiAgZnVuY3Rpb24gVSgpIHsKICAgIHZhciBnID0gRC5idWZmZXI7CiAgICBBLkhFQVBVOCA9IE4gPSBuZXcgVWludDhBcnJheShnKSwgQS5IRUFQVTMyID0gbmV3IFVpbnQzMkFycmF5KGcpLCBBLkhFQVBGMzIgPSBuZXcgRmxvYXQzMkFycmF5KGcpLCBuZXcgQmlnSW50NjRBcnJheShnKSwgbmV3IEJpZ1VpbnQ2NEFycmF5KGcpOwogIH0KICBmdW5jdGlvbiBpKCkgewogICAgaWYgKEEucHJlUnVuKQogICAgICBmb3IgKHR5cGVvZiBBLnByZVJ1biA9PSAiZnVuY3Rpb24iICYmIChBLnByZVJ1biA9IFtBLnByZVJ1bl0pOyBBLnByZVJ1bi5sZW5ndGg7ICkKICAgICAgICAkKEEucHJlUnVuLnNoaWZ0KCkpOwogICAgeChUKTsKICB9CiAgZnVuY3Rpb24gSCgpIHsKICAgIGYuYygpOwogIH0KICBmdW5jdGlvbiBiKCkgewogICAgaWYgKEEucG9zdFJ1bikKICAgICAgZm9yICh0eXBlb2YgQS5wb3N0UnVuID09ICJmdW5jdGlvbiIgJiYgKEEucG9zdFJ1biA9IFtBLnBvc3RSdW5dKTsgQS5wb3N0UnVuLmxlbmd0aDsgKQogICAgICAgIE8oQS5wb3N0UnVuLnNoaWZ0KCkpOwogICAgeChqKTsKICB9CiAgdmFyIHMgPSAwLCB3ID0gbnVsbDsKICBmdW5jdGlvbiB2KGcpIHsKICAgIHMrKywgQS5tb25pdG9yUnVuRGVwZW5kZW5jaWVzPy4ocyk7CiAgfQogIGZ1bmN0aW9uIFAoZykgewogICAgaWYgKHMtLSwgQS5tb25pdG9yUnVuRGVwZW5kZW5jaWVzPy4ocyksIHMgPT0gMCAmJiB3KSB7CiAgICAgIHZhciBCID0gdzsKICAgICAgdyA9IG51bGwsIEIoKTsKICAgIH0KICB9CiAgdmFyIG07CiAgZnVuY3Rpb24gWCgpIHsKICAgIHJldHVybiBBQSgiQUdGemJRRUFBQUFCSmdaZ0FYOEJmMkFDZlgwQmYyQUJmUUYvWUFGL0FHQUxmMzkvZjM5L2YzOS9mMzhBWUFBQUFnY0JBV0VCWVFBQUF3Z0hBQUVDQXdBRUJRVUhBUUdDQW9DQUFnWUlBWDhCUVlDTUJBc0hGUVVCWWdJQUFXTUFCd0ZrQUFZQlpRQUZBV1lBQkF3QkFRcXFRQWRQQVFKL1FZQUlLQUlBSWdFZ0FFRUhha0Y0Y1NJQ2FpRUFBa0FnQWtFQUlBQWdBVTBiUlFSQUlBQS9BRUVRZEUwTkFTQUFFQUFOQVF0QmhBaEJNRFlDQUVGL0R3dEJnQWdnQURZQ0FDQUJDdzRBSUFBUUF5QUJFQU5CRUhSeUMzSUJCSDhnQUx3aUJFSC8vLzhEY1NFQkFrQWdCRUVYZGtIL0FYRWlBa1VOQUNBQ1FmQUFUUVJBSUFGQmdJQ0FCSEpCOFFBZ0FtdDJJUUVNQVFzZ0FrR05BVXNFUUVHQStBRWhBMEVBSVFFTUFRc2dBa0VLZEVHQWdBZHJJUU1MSUFNZ0JFRVFka0dBZ0FKeGNpQUJRUTEyY2d2Y0N3RUlmd0pBSUFCRkRRQWdBRUVJYXlJRElBQkJCR3NvQWdBaUFrRjRjU0lBYWlFRkFrQWdBa0VCY1EwQUlBSkJBbkZGRFFFZ0F5QURLQUlBSWdScklnTkJtQWdvQWdCSkRRRWdBQ0FFYWlFQUFrQUNRQUpBUVp3SUtBSUFJQU5IQkVBZ0F5Z0NEQ0VCSUFSQi93Rk5CRUFnQVNBREtBSUlJZ0pIRFFKQmlBaEJpQWdvQWdCQmZpQUVRUU4yZDNFMkFnQU1CUXNnQXlnQ0dDRUhJQUVnQTBjRVFDQURLQUlJSWdJZ0FUWUNEQ0FCSUFJMkFnZ01CQXNnQXlnQ0ZDSUNCSDhnQTBFVWFnVWdBeWdDRUNJQ1JRMERJQU5CRUdvTElRUURRQ0FFSVFZZ0FpSUJRUlJxSVFRZ0FTZ0NGQ0lDRFFBZ0FVRVFhaUVFSUFFb0FoQWlBZzBBQ3lBR1FRQTJBZ0FNQXdzZ0JTZ0NCQ0lDUVFOeFFRTkhEUU5Ca0FnZ0FEWUNBQ0FGSUFKQmZuRTJBZ1FnQXlBQVFRRnlOZ0lFSUFVZ0FEWUNBQThMSUFJZ0FUWUNEQ0FCSUFJMkFnZ01BZ3RCQUNFQkN5QUhSUTBBQWtBZ0F5Z0NIQ0lFUVFKMFFiZ0thaUlDS0FJQUlBTkdCRUFnQWlBQk5nSUFJQUVOQVVHTUNFR01DQ2dDQUVGK0lBUjNjVFlDQUF3Q0N3SkFJQU1nQnlnQ0VFWUVRQ0FISUFFMkFoQU1BUXNnQnlBQk5nSVVDeUFCUlEwQkN5QUJJQWMyQWhnZ0F5Z0NFQ0lDQkVBZ0FTQUNOZ0lRSUFJZ0FUWUNHQXNnQXlnQ0ZDSUNSUTBBSUFFZ0FqWUNGQ0FDSUFFMkFoZ0xJQU1nQlU4TkFDQUZLQUlFSWdSQkFYRkZEUUFDUUFKQUFrQUNRQ0FFUVFKeFJRUkFRYUFJS0FJQUlBVkdCRUJCb0FnZ0F6WUNBRUdVQ0VHVUNDZ0NBQ0FBYWlJQU5nSUFJQU1nQUVFQmNqWUNCQ0FEUVp3SUtBSUFSdzBHUVpBSVFRQTJBZ0JCbkFoQkFEWUNBQThMUVp3SUtBSUFJZ2NnQlVZRVFFR2NDQ0FETmdJQVFaQUlRWkFJS0FJQUlBQnFJZ0EyQWdBZ0F5QUFRUUZ5TmdJRUlBQWdBMm9nQURZQ0FBOExJQVJCZUhFZ0FHb2hBQ0FGS0FJTUlRRWdCRUgvQVUwRVFDQUZLQUlJSWdJZ0FVWUVRRUdJQ0VHSUNDZ0NBRUYrSUFSQkEzWjNjVFlDQUF3RkN5QUNJQUUyQWd3Z0FTQUNOZ0lJREFRTElBVW9BaGdoQ0NBQklBVkhCRUFnQlNnQ0NDSUNJQUUyQWd3Z0FTQUNOZ0lJREFNTElBVW9BaFFpQWdSL0lBVkJGR29GSUFVb0FoQWlBa1VOQWlBRlFSQnFDeUVFQTBBZ0JDRUdJQUlpQVVFVWFpRUVJQUVvQWhRaUFnMEFJQUZCRUdvaEJDQUJLQUlRSWdJTkFBc2dCa0VBTmdJQURBSUxJQVVnQkVGK2NUWUNCQ0FESUFCQkFYSTJBZ1FnQUNBRGFpQUFOZ0lBREFNTFFRQWhBUXNnQ0VVTkFBSkFJQVVvQWh3aUJFRUNkRUc0Q21vaUFpZ0NBQ0FGUmdSQUlBSWdBVFlDQUNBQkRRRkJqQWhCakFnb0FnQkJmaUFFZDNFMkFnQU1BZ3NDUUNBRklBZ29BaEJHQkVBZ0NDQUJOZ0lRREFFTElBZ2dBVFlDRkFzZ0FVVU5BUXNnQVNBSU5nSVlJQVVvQWhBaUFnUkFJQUVnQWpZQ0VDQUNJQUUyQWhnTElBVW9BaFFpQWtVTkFDQUJJQUkyQWhRZ0FpQUJOZ0lZQ3lBRElBQkJBWEkyQWdRZ0FDQURhaUFBTmdJQUlBTWdCMGNOQUVHUUNDQUFOZ0lBRHdzZ0FFSC9BVTBFUUNBQVFYaHhRYkFJYWlFQ0FuOUJpQWdvQWdBaUJFRUJJQUJCQTNaMElnQnhSUVJBUVlnSUlBQWdCSEkyQWdBZ0Fnd0JDeUFDS0FJSUN5RUFJQUlnQXpZQ0NDQUFJQU0yQWd3Z0F5QUNOZ0lNSUFNZ0FEWUNDQThMUVI4aEFTQUFRZi8vL3dkTkJFQWdBRUVtSUFCQkNIWm5JZ0pyZGtFQmNTQUNRUUYwYTBFK2FpRUJDeUFESUFFMkFod2dBMElBTndJUUlBRkJBblJCdUFwcUlRUUNmd0pBQW45QmpBZ29BZ0FpQmtFQklBRjBJZ0p4UlFSQVFZd0lJQUlnQm5JMkFnQWdCQ0FETmdJQVFSZ2hBVUVJREFFTElBQkJHU0FCUVFGMmEwRUFJQUZCSDBjYmRDRUJJQVFvQWdBaEJBTkFJQVFpQWlnQ0JFRjRjU0FBUmcwQ0lBRkJIWFloQkNBQlFRRjBJUUVnQWlBRVFRUnhhaUlHS0FJUUlnUU5BQXNnQmlBRE5nSVFRUmdoQVNBQ0lRUkJDQXNoQUNBRElnSU1BUXNnQWlnQ0NDSUVJQU0yQWd3Z0FpQUROZ0lJUVJnaEFFRUlJUUZCQUFzaEJpQUJJQU5xSUFRMkFnQWdBeUFDTmdJTUlBQWdBMm9nQmpZQ0FFR29DRUdvQ0NnQ0FFRUJheUlBUVg4Z0FCczJBZ0FMQzlFbkFRdC9Jd0JCRUdzaUNpUUFBa0FDUUFKQUFrQUNRQUpBQWtBQ1FBSkFBa0FnQUVIMEFVMEVRRUdJQ0NnQ0FDSUVRUkFnQUVFTGFrSDRBM0VnQUVFTFNSc2lCa0VEZGlJQWRpSUJRUU54QkVBQ1FDQUJRWDl6UVFGeElBQnFJZ0pCQTNRaUFVR3dDR29pQUNBQlFiZ0lhaWdDQUNJQktBSUlJZ1ZHQkVCQmlBZ2dCRUYrSUFKM2NUWUNBQXdCQ3lBRklBQTJBZ3dnQUNBRk5nSUlDeUFCUVFocUlRQWdBU0FDUVFOMElnSkJBM0kyQWdRZ0FTQUNhaUlCSUFFb0FnUkJBWEkyQWdRTUN3c2dCa0dRQ0NnQ0FDSUlUUTBCSUFFRVFBSkFRUUlnQUhRaUFrRUFJQUpyY2lBQklBQjBjV2dpQVVFRGRDSUFRYkFJYWlJQ0lBQkJ1QWhxS0FJQUlnQW9BZ2dpQlVZRVFFR0lDQ0FFUVg0Z0FYZHhJZ1EyQWdBTUFRc2dCU0FDTmdJTUlBSWdCVFlDQ0FzZ0FDQUdRUU55TmdJRUlBQWdCbW9pQnlBQlFRTjBJZ0VnQm1zaUJVRUJjallDQkNBQUlBRnFJQVUyQWdBZ0NBUkFJQWhCZUhGQnNBaHFJUUZCbkFnb0FnQWhBZ0ovSUFSQkFTQUlRUU4yZENJRGNVVUVRRUdJQ0NBRElBUnlOZ0lBSUFFTUFRc2dBU2dDQ0FzaEF5QUJJQUkyQWdnZ0F5QUNOZ0lNSUFJZ0FUWUNEQ0FDSUFNMkFnZ0xJQUJCQ0dvaEFFR2NDQ0FITmdJQVFaQUlJQVUyQWdBTUN3dEJqQWdvQWdBaUMwVU5BU0FMYUVFQ2RFRzRDbW9vQWdBaUFpZ0NCRUY0Y1NBR2F5RURJQUloQVFOQUFrQWdBU2dDRUNJQVJRUkFJQUVvQWhRaUFFVU5BUXNnQUNnQ0JFRjRjU0FHYXlJQklBTWdBU0FEU1NJQkd5RURJQUFnQWlBQkd5RUNJQUFoQVF3QkN3c2dBaWdDR0NFSklBSWdBaWdDRENJQVJ3UkFJQUlvQWdnaUFTQUFOZ0lNSUFBZ0FUWUNDQXdLQ3lBQ0tBSVVJZ0VFZnlBQ1FSUnFCU0FDS0FJUUlnRkZEUU1nQWtFUWFnc2hCUU5BSUFVaEJ5QUJJZ0JCRkdvaEJTQUFLQUlVSWdFTkFDQUFRUkJxSVFVZ0FDZ0NFQ0lCRFFBTElBZEJBRFlDQUF3SkMwRi9JUVlnQUVHL2Ywc05BQ0FBUVF0cUlnRkJlSEVoQmtHTUNDZ0NBQ0lIUlEwQVFSOGhDRUVBSUFacklRTWdBRUgwLy84SFRRUkFJQVpCSmlBQlFRaDJaeUlBYTNaQkFYRWdBRUVCZEd0QlBtb2hDQXNDUUFKQUFrQWdDRUVDZEVHNENtb29BZ0FpQVVVRVFFRUFJUUFNQVF0QkFDRUFJQVpCR1NBSVFRRjJhMEVBSUFoQkgwY2JkQ0VDQTBBQ1FDQUJLQUlFUVhoeElBWnJJZ1FnQTA4TkFDQUJJUVVnQkNJRERRQkJBQ0VESUFFaEFBd0RDeUFBSUFFb0FoUWlCQ0FFSUFFZ0FrRWRka0VFY1dvb0FoQWlBVVliSUFBZ0JCc2hBQ0FDUVFGMElRSWdBUTBBQ3dzZ0FDQUZja1VFUUVFQUlRVkJBaUFJZENJQVFRQWdBR3R5SUFkeElnQkZEUU1nQUdoQkFuUkJ1QXBxS0FJQUlRQUxJQUJGRFFFTEEwQWdBQ2dDQkVGNGNTQUdheUlDSUFOSklRRWdBaUFESUFFYklRTWdBQ0FGSUFFYklRVWdBQ2dDRUNJQkJIOGdBUVVnQUNnQ0ZBc2lBQTBBQ3dzZ0JVVU5BQ0FEUVpBSUtBSUFJQVpyVHcwQUlBVW9BaGdoQ0NBRklBVW9BZ3dpQUVjRVFDQUZLQUlJSWdFZ0FEWUNEQ0FBSUFFMkFnZ01DQXNnQlNnQ0ZDSUJCSDhnQlVFVWFnVWdCU2dDRUNJQlJRMERJQVZCRUdvTElRSURRQ0FDSVFRZ0FTSUFRUlJxSVFJZ0FDZ0NGQ0lCRFFBZ0FFRVFhaUVDSUFBb0FoQWlBUTBBQ3lBRVFRQTJBZ0FNQndzZ0JrR1FDQ2dDQUNJRlRRUkFRWndJS0FJQUlRQUNRQ0FGSUFacklnRkJFRThFUUNBQUlBWnFJZ0lnQVVFQmNqWUNCQ0FBSUFWcUlBRTJBZ0FnQUNBR1FRTnlOZ0lFREFFTElBQWdCVUVEY2pZQ0JDQUFJQVZxSWdFZ0FTZ0NCRUVCY2pZQ0JFRUFJUUpCQUNFQkMwR1FDQ0FCTmdJQVFad0lJQUkyQWdBZ0FFRUlhaUVBREFrTElBWkJsQWdvQWdBaUFra0VRRUdVQ0NBQ0lBWnJJZ0UyQWdCQm9BaEJvQWdvQWdBaUFDQUdhaUlDTmdJQUlBSWdBVUVCY2pZQ0JDQUFJQVpCQTNJMkFnUWdBRUVJYWlFQURBa0xRUUFoQUNBR1FTOXFJZ01DZjBIZ0N5Z0NBQVJBUWVnTEtBSUFEQUVMUWV3TFFuODNBZ0JCNUF0Q2dLQ0FnSUNBQkRjQ0FFSGdDeUFLUVF4cVFYQnhRZGlxMWFvRmN6WUNBRUgwQzBFQU5nSUFRY1FMUVFBMkFnQkJnQ0FMSWdGcUlnUkJBQ0FCYXlJSGNTSUJJQVpORFFoQndBc29BZ0FpQlFSQVFiZ0xLQUlBSWdnZ0FXb2lDU0FJVFNBRklBbEpjZzBKQ3dKQVFjUUxMUUFBUVFSeFJRUkFBa0FDUUFKQUFrQkJvQWdvQWdBaUJRUkFRY2dMSVFBRFFDQUFLQUlBSWdnZ0JVMEVRQ0FGSUFnZ0FDZ0NCR3BKRFFNTElBQW9BZ2dpQUEwQUN3dEJBQkFCSWdKQmYwWU5BeUFCSVFSQjVBc29BZ0FpQUVFQmF5SUZJQUp4QkVBZ0FTQUNheUFDSUFWcVFRQWdBR3R4YWlFRUN5QUVJQVpORFFOQndBc29BZ0FpQUFSQVFiZ0xLQUlBSWdVZ0JHb2lCeUFGVFNBQUlBZEpjZzBFQ3lBRUVBRWlBQ0FDUncwQkRBVUxJQVFnQW1zZ0IzRWlCQkFCSWdJZ0FDZ0NBQ0FBS0FJRWFrWU5BU0FDSVFBTElBQkJmMFlOQVNBR1FUQnFJQVJOQkVBZ0FDRUNEQVFMUWVnTEtBSUFJZ0lnQXlBRWEycEJBQ0FDYTNFaUFoQUJRWDlHRFFFZ0FpQUVhaUVFSUFBaEFnd0RDeUFDUVg5SERRSUxRY1FMUWNRTEtBSUFRUVJ5TmdJQUN5QUJFQUVpQWtGL1JrRUFFQUVpQUVGL1JuSWdBQ0FDVFhJTkJTQUFJQUpySWdRZ0JrRW9hazBOQlF0QnVBdEJ1QXNvQWdBZ0JHb2lBRFlDQUVHOEN5Z0NBQ0FBU1FSQVFid0xJQUEyQWdBTEFrQkJvQWdvQWdBaUF3UkFRY2dMSVFBRFFDQUNJQUFvQWdBaUFTQUFLQUlFSWdWcVJnMENJQUFvQWdnaUFBMEFDd3dFQzBHWUNDZ0NBQ0lBUVFBZ0FDQUNUUnRGQkVCQm1BZ2dBallDQUF0QkFDRUFRY3dMSUFRMkFnQkJ5QXNnQWpZQ0FFR29DRUYvTmdJQVFhd0lRZUFMS0FJQU5nSUFRZFFMUVFBMkFnQURRQ0FBUVFOMElnRkJ1QWhxSUFGQnNBaHFJZ1UyQWdBZ0FVRzhDR29nQlRZQ0FDQUFRUUZxSWdCQklFY05BQXRCbEFnZ0JFRW9heUlBUVhnZ0FtdEJCM0VpQVdzaUJUWUNBRUdnQ0NBQklBSnFJZ0UyQWdBZ0FTQUZRUUZ5TmdJRUlBQWdBbXBCS0RZQ0JFR2tDRUh3Q3lnQ0FEWUNBQXdFQ3lBQ0lBTk5JQUVnQTB0eURRSWdBQ2dDREVFSWNRMENJQUFnQkNBRmFqWUNCRUdnQ0NBRFFYZ2dBMnRCQjNFaUFHb2lBVFlDQUVHVUNFR1VDQ2dDQUNBRWFpSUNJQUJySWdBMkFnQWdBU0FBUVFGeU5nSUVJQUlnQTJwQktEWUNCRUdrQ0VId0N5Z0NBRFlDQUF3REMwRUFJUUFNQmd0QkFDRUFEQVFMUVpnSUtBSUFJQUpMQkVCQm1BZ2dBallDQUFzZ0FpQUVhaUVGUWNnTElRQUNRQU5BSUFVZ0FDZ0NBQ0lCUndSQUlBQW9BZ2dpQUEwQkRBSUxDeUFBTFFBTVFRaHhSUTBEQzBISUN5RUFBMEFDUUNBQUtBSUFJZ0VnQTAwRVFDQURJQUVnQUNnQ0JHb2lCVWtOQVFzZ0FDZ0NDQ0VBREFFTEMwR1VDQ0FFUVNocklnQkJlQ0FDYTBFSGNTSUJheUlITmdJQVFhQUlJQUVnQW1vaUFUWUNBQ0FCSUFkQkFYSTJBZ1FnQUNBQ2FrRW9OZ0lFUWFRSVFmQUxLQUlBTmdJQUlBTWdCVUVuSUFWclFRZHhha0V2YXlJQUlBQWdBMEVRYWtrYklnRkJHellDQkNBQlFkQUxLUUlBTndJUUlBRkJ5QXNwQWdBM0FnaEIwQXNnQVVFSWFqWUNBRUhNQ3lBRU5nSUFRY2dMSUFJMkFnQkIxQXRCQURZQ0FDQUJRUmhxSVFBRFFDQUFRUWMyQWdRZ0FFRUlhaUFBUVFScUlRQWdCVWtOQUFzZ0FTQURSZzBBSUFFZ0FTZ0NCRUYrY1RZQ0JDQURJQUVnQTJzaUFrRUJjallDQkNBQklBSTJBZ0FDZnlBQ1FmOEJUUVJBSUFKQmVIRkJzQWhxSVFBQ2YwR0lDQ2dDQUNJQlFRRWdBa0VEZG5RaUFuRkZCRUJCaUFnZ0FTQUNjallDQUNBQURBRUxJQUFvQWdnTElRRWdBQ0FETmdJSUlBRWdBellDREVFTUlRSkJDQXdCQzBFZklRQWdBa0gvLy84SFRRUkFJQUpCSmlBQ1FRaDJaeUlBYTNaQkFYRWdBRUVCZEd0QlBtb2hBQXNnQXlBQU5nSWNJQU5DQURjQ0VDQUFRUUowUWJnS2FpRUJBa0FDUUVHTUNDZ0NBQ0lGUVFFZ0FIUWlCSEZGQkVCQmpBZ2dCQ0FGY2pZQ0FDQUJJQU0yQWdBTUFRc2dBa0VaSUFCQkFYWnJRUUFnQUVFZlJ4dDBJUUFnQVNnQ0FDRUZBMEFnQlNJQktBSUVRWGh4SUFKR0RRSWdBRUVkZGlFRklBQkJBWFFoQUNBQklBVkJCSEZxSWdRb0FoQWlCUTBBQ3lBRUlBTTJBaEFMSUFNZ0FUWUNHRUVJSVFJZ0F5SUJJUUJCREF3QkN5QUJLQUlJSWdBZ0F6WUNEQ0FCSUFNMkFnZ2dBeUFBTmdJSVFRQWhBRUVZSVFKQkRBc2dBMm9nQVRZQ0FDQUNJQU5xSUFBMkFnQUxRWlFJS0FJQUlnQWdCazBOQUVHVUNDQUFJQVpySWdFMkFnQkJvQWhCb0Fnb0FnQWlBQ0FHYWlJQ05nSUFJQUlnQVVFQmNqWUNCQ0FBSUFaQkEzSTJBZ1FnQUVFSWFpRUFEQVFMUVlRSVFUQTJBZ0JCQUNFQURBTUxJQUFnQWpZQ0FDQUFJQUFvQWdRZ0JHbzJBZ1FnQWtGNElBSnJRUWR4YWlJSUlBWkJBM0kyQWdRZ0FVRjRJQUZyUVFkeGFpSUVJQVlnQ0dvaUEyc2hCd0pBUWFBSUtBSUFJQVJHQkVCQm9BZ2dBellDQUVHVUNFR1VDQ2dDQUNBSGFpSUFOZ0lBSUFNZ0FFRUJjallDQkF3QkMwR2NDQ2dDQUNBRVJnUkFRWndJSUFNMkFnQkJrQWhCa0Fnb0FnQWdCMm9pQURZQ0FDQURJQUJCQVhJMkFnUWdBQ0FEYWlBQU5nSUFEQUVMSUFRb0FnUWlBRUVEY1VFQlJnUkFJQUJCZUhFaENTQUVLQUlNSVFJQ1FDQUFRZjhCVFFSQUlBUW9BZ2dpQVNBQ1JnUkFRWWdJUVlnSUtBSUFRWDRnQUVFRGRuZHhOZ0lBREFJTElBRWdBallDRENBQ0lBRTJBZ2dNQVFzZ0JDZ0NHQ0VHQWtBZ0FpQUVSd1JBSUFRb0FnZ2lBQ0FDTmdJTUlBSWdBRFlDQ0F3QkN3SkFJQVFvQWhRaUFBUi9JQVJCRkdvRklBUW9BaEFpQUVVTkFTQUVRUkJxQ3lFQkEwQWdBU0VGSUFBaUFrRVVhaUVCSUFBb0FoUWlBQTBBSUFKQkVHb2hBU0FDS0FJUUlnQU5BQXNnQlVFQU5nSUFEQUVMUVFBaEFnc2dCa1VOQUFKQUlBUW9BaHdpQUVFQ2RFRzRDbW9pQVNnQ0FDQUVSZ1JBSUFFZ0FqWUNBQ0FDRFFGQmpBaEJqQWdvQWdCQmZpQUFkM0UyQWdBTUFnc0NRQ0FFSUFZb0FoQkdCRUFnQmlBQ05nSVFEQUVMSUFZZ0FqWUNGQXNnQWtVTkFRc2dBaUFHTmdJWUlBUW9BaEFpQUFSQUlBSWdBRFlDRUNBQUlBSTJBaGdMSUFRb0FoUWlBRVVOQUNBQ0lBQTJBaFFnQUNBQ05nSVlDeUFISUFscUlRY2dCQ0FKYWlJRUtBSUVJUUFMSUFRZ0FFRitjVFlDQkNBRElBZEJBWEkyQWdRZ0F5QUhhaUFITmdJQUlBZEIvd0ZOQkVBZ0IwRjRjVUd3Q0dvaEFBSi9RWWdJS0FJQUlnRkJBU0FIUVFOMmRDSUNjVVVFUUVHSUNDQUJJQUp5TmdJQUlBQU1BUXNnQUNnQ0NBc2hBU0FBSUFNMkFnZ2dBU0FETmdJTUlBTWdBRFlDRENBRElBRTJBZ2dNQVF0Qkh5RUNJQWRCLy8vL0IwMEVRQ0FIUVNZZ0IwRUlkbWNpQUd0MlFRRnhJQUJCQVhSclFUNXFJUUlMSUFNZ0FqWUNIQ0FEUWdBM0FoQWdBa0VDZEVHNENtb2hBQUpBQWtCQmpBZ29BZ0FpQVVFQklBSjBJZ1Z4UlFSQVFZd0lJQUVnQlhJMkFnQWdBQ0FETmdJQURBRUxJQWRCR1NBQ1FRRjJhMEVBSUFKQkgwY2JkQ0VDSUFBb0FnQWhBUU5BSUFFaUFDZ0NCRUY0Y1NBSFJnMENJQUpCSFhZaEFTQUNRUUYwSVFJZ0FDQUJRUVJ4YWlJRktBSVFJZ0VOQUFzZ0JTQUROZ0lRQ3lBRElBQTJBaGdnQXlBRE5nSU1JQU1nQXpZQ0NBd0JDeUFBS0FJSUlnRWdBellDRENBQUlBTTJBZ2dnQTBFQU5nSVlJQU1nQURZQ0RDQURJQUUyQWdnTElBaEJDR29oQUF3Q0N3SkFJQWhGRFFBQ1FDQUZLQUljSWdGQkFuUkJ1QXBxSWdJb0FnQWdCVVlFUUNBQ0lBQTJBZ0FnQUEwQlFZd0lJQWRCZmlBQmQzRWlCellDQUF3Q0N3SkFJQVVnQ0NnQ0VFWUVRQ0FJSUFBMkFoQU1BUXNnQ0NBQU5nSVVDeUFBUlEwQkN5QUFJQWcyQWhnZ0JTZ0NFQ0lCQkVBZ0FDQUJOZ0lRSUFFZ0FEWUNHQXNnQlNnQ0ZDSUJSUTBBSUFBZ0FUWUNGQ0FCSUFBMkFoZ0xBa0FnQTBFUFRRUkFJQVVnQXlBR2FpSUFRUU55TmdJRUlBQWdCV29pQUNBQUtBSUVRUUZ5TmdJRURBRUxJQVVnQmtFRGNqWUNCQ0FGSUFacUlnUWdBMEVCY2pZQ0JDQURJQVJxSUFNMkFnQWdBMEgvQVUwRVFDQURRWGh4UWJBSWFpRUFBbjlCaUFnb0FnQWlBVUVCSUFOQkEzWjBJZ0p4UlFSQVFZZ0lJQUVnQW5JMkFnQWdBQXdCQ3lBQUtBSUlDeUVCSUFBZ0JEWUNDQ0FCSUFRMkFnd2dCQ0FBTmdJTUlBUWdBVFlDQ0F3QkMwRWZJUUFnQTBILy8vOEhUUVJBSUFOQkppQURRUWgyWnlJQWEzWkJBWEVnQUVFQmRHdEJQbW9oQUFzZ0JDQUFOZ0ljSUFSQ0FEY0NFQ0FBUVFKMFFiZ0thaUVCQWtBQ1FDQUhRUUVnQUhRaUFuRkZCRUJCakFnZ0FpQUhjallDQUNBQklBUTJBZ0FnQkNBQk5nSVlEQUVMSUFOQkdTQUFRUUYyYTBFQUlBQkJIMGNiZENFQUlBRW9BZ0FoQVFOQUlBRWlBaWdDQkVGNGNTQURSZzBDSUFCQkhYWWhBU0FBUVFGMElRQWdBaUFCUVFSeGFpSUhLQUlRSWdFTkFBc2dCeUFFTmdJUUlBUWdBallDR0FzZ0JDQUVOZ0lNSUFRZ0JEWUNDQXdCQ3lBQ0tBSUlJZ0FnQkRZQ0RDQUNJQVEyQWdnZ0JFRUFOZ0lZSUFRZ0FqWUNEQ0FFSUFBMkFnZ0xJQVZCQ0dvaEFBd0JDd0pBSUFsRkRRQUNRQ0FDS0FJY0lnRkJBblJCdUFwcUlnVW9BZ0FnQWtZRVFDQUZJQUEyQWdBZ0FBMEJRWXdJSUF0QmZpQUJkM0UyQWdBTUFnc0NRQ0FDSUFrb0FoQkdCRUFnQ1NBQU5nSVFEQUVMSUFrZ0FEWUNGQXNnQUVVTkFRc2dBQ0FKTmdJWUlBSW9BaEFpQVFSQUlBQWdBVFlDRUNBQklBQTJBaGdMSUFJb0FoUWlBVVVOQUNBQUlBRTJBaFFnQVNBQU5nSVlDd0pBSUFOQkQwMEVRQ0FDSUFNZ0Jtb2lBRUVEY2pZQ0JDQUFJQUpxSWdBZ0FDZ0NCRUVCY2pZQ0JBd0JDeUFDSUFaQkEzSTJBZ1FnQWlBR2FpSUZJQU5CQVhJMkFnUWdBeUFGYWlBRE5nSUFJQWdFUUNBSVFYaHhRYkFJYWlFQVFad0lLQUlBSVFFQ2YwRUJJQWhCQTNaMElnY2dCSEZGQkVCQmlBZ2dCQ0FIY2pZQ0FDQUFEQUVMSUFBb0FnZ0xJUVFnQUNBQk5nSUlJQVFnQVRZQ0RDQUJJQUEyQWd3Z0FTQUVOZ0lJQzBHY0NDQUZOZ0lBUVpBSUlBTTJBZ0FMSUFKQkNHb2hBQXNnQ2tFUWFpUUFJQUFMb1FzQ0MzOEpmU01BUWFBQmF5SUxKQUFnQzBFd2FrRUFRU1Q4Q3dBRFFDQUJJQTVIQkVBZ0FpQU9RUU5zSWd4QkFtcEJBblFpRDJvcUFnQWhGeUFDSUF4QkFXcEJBblFpRUdvcUFnQWhHQ0FJSUF4QkFuUWlFV29nQWlBUmFpb0NBQ0laT0FJQUlBZ2dFR29nR0RnQ0FDQUlJQTlxSUJjNEFnQWdCeUFPUVFWMGFpSU5RUUEyQWd3Z0RTQVhPQUlJSUEwZ0dEZ0NCQ0FOSUJrNEFnQUNRQ0FBUlFSQUlBWWdEbW90QUFCRkRRRUxJQTFCZ0lDQUNEWUNEQXNnRFNBRklBNUJBblFpREVFQmNpSVNhaTBBQUVFSWRDQUZJQXhxTFFBQWNpQUZJQXhCQW5JaUUyb3RBQUJCRUhSeUlBVWdERUVEY2lJTWFpMEFBRUVZZEhJMkFod2dDeUFESUJKQkFuUWlFbW9xQWdBaUZ6Z0NrQUVnQ3lBRElCTkJBblFpRTJvcUFnQWlHRGdDbEFFZ0N5QURJQXhCQW5RaUZHb3FBZ0FpR1RnQ21BRWdDeUFESUE1QkJIUWlGV29xQWdDTUlobzRBcHdCSUF0QjRBQnFJZ3dnQ3lvQ21BRWlGa01BQUFEQWxDQVdsQ0FMS2dLVUFTSVdRd0FBQU1DVUlCYVVRd0FBZ0QrU2tqZ0NBQ0FNSUFzcUFwQUJJaFlnRnBJZ0N5b0NsQUdVSUFzcUFwZ0JJaFlnRnBJZ0N5b0NuQUdVa3pnQ0JDQU1JQXNxQXBBQkloWWdGcElnQ3lvQ21BR1VJQXNxQXBRQkloWWdGcElnQ3lvQ25BR1VramdDQ0NBTUlBc3FBcEFCSWhZZ0ZwSWdDeW9DbEFHVUlBc3FBcGdCSWhZZ0ZwSWdDeW9DbkFHVWtqZ0NEQ0FNSUFzcUFwZ0JJaFpEQUFBQXdKUWdGcFFnQ3lvQ2tBRWlGa01BQUFEQWxDQVdsRU1BQUlBL2twSTRBaEFnRENBTEtnS1VBU0lXSUJhU0lBc3FBcGdCbENBTEtnS1FBU0lXSUJhU0lBc3FBcHdCbEpNNEFoUWdEQ0FMS2dLUUFTSVdJQmFTSUFzcUFwZ0JsQ0FMS2dLVUFTSVdJQmFTSUFzcUFwd0JsSk00QWhnZ0RDQUxLZ0tVQVNJV0lCYVNJQXNxQXBnQmxDQUxLZ0tRQVNJV0lCYVNJQXNxQXB3QmxKSTRBaHdnRENBTEtnS1VBU0lXUXdBQUFNQ1VJQmFVSUFzcUFwQUJJaFpEQUFBQXdKUWdGcFJEQUFDQVA1S1NPQUlnSUFrZ0ZXb2dGemdDQUNBSklCSnFJQmc0QWdBZ0NTQVRhaUFaT0FJQUlBa2dGR29nR2pnQ0FDQUxJQVFnRVdvcUFnQWlGemdDTUNBTElBUWdFR29xQWdBaUdEZ0NRQ0FMSUFRZ0Qyb3FBZ0FpR1RnQ1VDQUtJQkZxSUJjNEFnQWdDaUFRYWlBWU9BSUFJQW9nRDJvZ0dUZ0NBQ0FMSUF3cUFoZ2dDeW9DT0pRZ0RDb0NBQ0FMS2dJd2xDQU1LZ0lNSUFzcUFqU1VrcEk0QWdBZ0N5QU1LZ0ljSUFzcUFqaVVJQXdxQWdRZ0N5b0NNSlFnRENvQ0VDQUxLZ0kwbEpLU09BSUVJQXNnRENvQ0lDQUxLZ0k0bENBTUtnSUlJQXNxQWpDVUlBd3FBaFFnQ3lvQ05KU1NramdDQ0NBTElBd3FBaGdnQ3lvQ1JKUWdEQ29DQUNBTEtnSThsQ0FNS2dJTUlBc3FBa0NVa3BJNEFnd2dDeUFNS2dJY0lBc3FBa1NVSUF3cUFnUWdDeW9DUEpRZ0RDb0NFQ0FMS2dKQWxKS1NPQUlRSUFzZ0RDb0NJQ0FMS2dKRWxDQU1LZ0lJSUFzcUFqeVVJQXdxQWhRZ0N5b0NRSlNTa2pnQ0ZDQUxJQXdxQWhnZ0N5b0NVSlFnRENvQ0FDQUxLZ0pJbENBTUtnSU1JQXNxQWt5VWtwSTRBaGdnQ3lBTUtnSWNJQXNxQWxDVUlBd3FBZ1FnQ3lvQ1NKUWdEQ29DRUNBTEtnSk1sSktTT0FJY0lBc2dEQ29DSUNBTEtnSlFsQ0FNS2dJSUlBc3FBa2lVSUF3cUFoUWdDeW9DVEpTU2tqZ0NJQ0FMS2dJZ0lSY2dDeW9DQ0NFWUlBc3FBaFFoR1NBTklBc3FBaGdpR2lBYWxDQUxLZ0lBSWhZZ0ZwUWdDeW9DRENJYklCdVVrcEpEQUFDQVFKUWdHaUFMS2dJY0loeVVJQllnQ3lvQ0JDSWRsQ0FiSUFzcUFoQWlIcFNTa2tNQUFJQkFsQkFDTmdJUUlBMGdHaUFYbENBV0lCaVVJQnNnR1pTU2trTUFBSUJBbENBY0lCeVVJQjBnSFpRZ0hpQWVsSktTUXdBQWdFQ1VFQUkyQWhRZ0RTQWNJQmVVSUIwZ0dKUWdIaUFabEpLU1F3QUFnRUNVSUJjZ0Y1UWdHQ0FZbENBWklCbVVrcEpEQUFDQVFKUVFBallDR0NBT1FRRnFJUTRNQVFzTElBdEJvQUZxSkFBTEFnQUxDd2tCQUVHQkNBc0NCZ0U9Iik7CiAgfQogIGZ1bmN0aW9uIFcoZykgewogICAgaWYgKEFycmF5QnVmZmVyLmlzVmlldyhnKSkKICAgICAgcmV0dXJuIGc7CiAgICBpZiAoZyA9PSBtICYmIEYpCiAgICAgIHJldHVybiBuZXcgVWludDhBcnJheShGKTsKICAgIGlmICh5KQogICAgICByZXR1cm4geShnKTsKICAgIHRocm93ICdzeW5jIGZldGNoaW5nIG9mIHRoZSB3YXNtIGZhaWxlZDogeW91IGNhbiBwcmVsb2FkIGl0IHRvIE1vZHVsZVsid2FzbUJpbmFyeSJdIG1hbnVhbGx5LCBvciBlbWNjLnB5IHdpbGwgZG8gdGhhdCBmb3IgeW91IHdoZW4gZ2VuZXJhdGluZyBIVE1MIChidXQgbm90IEpTKSc7CiAgfQogIGZ1bmN0aW9uIF8oZywgQikgewogICAgdmFyIEUsIFEgPSBXKGcpOwogICAgRSA9IG5ldyBXZWJBc3NlbWJseS5Nb2R1bGUoUSk7CiAgICB2YXIgbyA9IG5ldyBXZWJBc3NlbWJseS5JbnN0YW5jZShFLCBCKTsKICAgIHJldHVybiBbbywgRV07CiAgfQogIGZ1bmN0aW9uIFYoKSB7CiAgICByZXR1cm4geyBhOiBFQSB9OwogIH0KICBmdW5jdGlvbiB6KCkgewogICAgZnVuY3Rpb24gZyhRLCBvKSB7CiAgICAgIHJldHVybiBmID0gUS5leHBvcnRzLCBEID0gZi5iLCBVKCksIFFBKGYpLCBQKCksIGY7CiAgICB9CiAgICB2KCk7CiAgICB2YXIgQiA9IFYoKTsKICAgIGlmIChBLmluc3RhbnRpYXRlV2FzbSkKICAgICAgcmV0dXJuIG5ldyBQcm9taXNlKChRLCBvKSA9PiB7CiAgICAgICAgQS5pbnN0YW50aWF0ZVdhc20oQiwgKHIsIGMpID0+IHsKICAgICAgICAgIFEoZyhyKSk7CiAgICAgICAgfSk7CiAgICAgIH0pOwogICAgbSA/Pz0gWCgpOwogICAgdmFyIEUgPSBfKG0sIEIpOwogICAgcmV0dXJuIGcoRVswXSk7CiAgfQogIGZvciAodmFyIHggPSAoZykgPT4gewogICAgZm9yICg7IGcubGVuZ3RoID4gMDsgKQogICAgICBnLnNoaWZ0KCkoQSk7CiAgfSwgaiA9IFtdLCBPID0gKGcpID0+IGoucHVzaChnKSwgVCA9IFtdLCAkID0gKGcpID0+IFQucHVzaChnKSwgQUEgPSAoZykgPT4gewogICAgZm9yICh2YXIgQiwgRSwgUSA9IDAsIG8gPSAwLCByID0gZy5sZW5ndGgsIGMgPSBuZXcgVWludDhBcnJheSgociAqIDMgPj4gMikgLSAoZ1tyIC0gMl0gPT0gIj0iKSAtIChnW3IgLSAxXSA9PSAiPSIpKTsgUSA8IHI7IFEgKz0gNCwgbyArPSAzKQogICAgICBCID0gbltnLmNoYXJDb2RlQXQoUSArIDEpXSwgRSA9IG5bZy5jaGFyQ29kZUF0KFEgKyAyKV0sIGNbb10gPSBuW2cuY2hhckNvZGVBdChRKV0gPDwgMiB8IEIgPj4gNCwgY1tvICsgMV0gPSBCIDw8IDQgfCBFID4+IDIsIGNbbyArIDJdID0gRSA8PCA2IHwgbltnLmNoYXJDb2RlQXQoUSArIDMpXTsKICAgIHJldHVybiBjOwogIH0sIGdBID0gKCkgPT4gMjE0NzQ4MzY0OCwgSUEgPSAoZywgQikgPT4gTWF0aC5jZWlsKGcgLyBCKSAqIEIsIENBID0gKGcpID0+IHsKICAgIHZhciBCID0gRC5idWZmZXIsIEUgPSAoZyAtIEIuYnl0ZUxlbmd0aCArIDY1NTM1KSAvIDY1NTM2IHwgMDsKICAgIHRyeSB7CiAgICAgIHJldHVybiBELmdyb3coRSksIFUoKSwgMTsKICAgIH0gY2F0Y2ggewogICAgfQogIH0sIEJBID0gKGcpID0+IHsKICAgIHZhciBCID0gTi5sZW5ndGg7CiAgICBnID4+Pj0gMDsKICAgIHZhciBFID0gZ0EoKTsKICAgIGlmIChnID4gRSkKICAgICAgcmV0dXJuICExOwogICAgZm9yICh2YXIgUSA9IDE7IFEgPD0gNDsgUSAqPSAyKSB7CiAgICAgIHZhciBvID0gQiAqICgxICsgMC4yIC8gUSk7CiAgICAgIG8gPSBNYXRoLm1pbihvLCBnICsgMTAwNjYzMjk2KTsKICAgICAgdmFyIHIgPSBNYXRoLm1pbihFLCBJQShNYXRoLm1heChnLCBvKSwgNjU1MzYpKSwgYyA9IENBKHIpOwogICAgICBpZiAoYykKICAgICAgICByZXR1cm4gITA7CiAgICB9CiAgICByZXR1cm4gITE7CiAgfSwgbiA9IG5ldyBVaW50OEFycmF5KDEyMyksIGEgPSAyNTsgYSA+PSAwOyAtLWEpCiAgICBuWzQ4ICsgYV0gPSA1MiArIGEsIG5bNjUgKyBhXSA9IGEsIG5bOTcgKyBhXSA9IDI2ICsgYTsKICBuWzQzXSA9IDYyLCBuWzQ3XSA9IDYzLCBBLm5vRXhpdFJ1bnRpbWUgJiYgQS5ub0V4aXRSdW50aW1lLCBBLnByaW50ICYmIEEucHJpbnQsIEEucHJpbnRFcnIgJiYgQS5wcmludEVyciwgQS53YXNtQmluYXJ5ICYmIChGID0gQS53YXNtQmluYXJ5KSwgQS5hcmd1bWVudHMgJiYgQS5hcmd1bWVudHMsIEEudGhpc1Byb2dyYW0gJiYgQS50aGlzUHJvZ3JhbTsKICBmdW5jdGlvbiBRQShnKSB7CiAgICBBLl9wYWNrID0gZy5kLCBBLl9tYWxsb2MgPSBnLmUsIEEuX2ZyZWUgPSBnLmY7CiAgfQogIHZhciBFQSA9IHsgYTogQkEgfSwgZiA9IHooKTsKICBmdW5jdGlvbiBxKCkgewogICAgaWYgKHMgPiAwKSB7CiAgICAgIHcgPSBxOwogICAgICByZXR1cm47CiAgICB9CiAgICBpZiAoaSgpLCBzID4gMCkgewogICAgICB3ID0gcTsKICAgICAgcmV0dXJuOwogICAgfQogICAgZnVuY3Rpb24gZygpIHsKICAgICAgQS5jYWxsZWRSdW4gPSAhMCwgSCgpLCBBLm9uUnVudGltZUluaXRpYWxpemVkPy4oKSwgYigpOwogICAgfQogICAgQS5zZXRTdGF0dXMgPyAoQS5zZXRTdGF0dXMoIlJ1bm5pbmcuLi4iKSwgc2V0VGltZW91dCgoKSA9PiB7CiAgICAgIHNldFRpbWVvdXQoKCkgPT4gQS5zZXRTdGF0dXMoIiIpLCAxKSwgZygpOwogICAgfSwgMSkpIDogZygpOwogIH0KICBmdW5jdGlvbiBpQSgpIHsKICAgIGlmIChBLnByZUluaXQpCiAgICAgIGZvciAodHlwZW9mIEEucHJlSW5pdCA9PSAiZnVuY3Rpb24iICYmIChBLnByZUluaXQgPSBbQS5wcmVJbml0XSk7IEEucHJlSW5pdC5sZW5ndGggPiAwOyApCiAgICAgICAgQS5wcmVJbml0LnNoaWZ0KCkoKTsKICB9CiAgcmV0dXJuIGlBKCksIHEoKSwgZSA9IEEsIGU7Cn07CmxldCBJOwphc3luYyBmdW5jdGlvbiB0QSgpIHsKICBpZiAoSSA9IGF3YWl0IG9BKCksICFJIHx8ICFJLkhFQVBGMzIgfHwgIUkuX3BhY2spCiAgICB0aHJvdyBuZXcgRXJyb3IoIldBU00gbW9kdWxlIGZhaWxlZCB0byBpbml0aWFsaXplIHByb3Blcmx5Iik7Cn0KbGV0IHQgPSAwOwpjb25zdCBsID0gbmV3IEFycmF5KCk7CmxldCBLID0gITEsIHAgPSAhMSwgWSwgUiwgRywgdSwgZCwgTSwgUywgTCwgSjsKY29uc3QgZUEgPSBhc3luYyAoQykgPT4gewogIGZvciAoOyBwOyApCiAgICBhd2FpdCBuZXcgUHJvbWlzZSgoSCkgPT4gc2V0VGltZW91dChILCAwKSk7CiAgSSB8fCAocCA9ICEwLCBhd2FpdCB0QSgpLCBwID0gITEpOwogIGNvbnN0IGUgPSBNYXRoLnBvdygyLCBNYXRoLmNlaWwoTWF0aC5sb2cyKEMudmVydGV4Q291bnQpKSk7CiAgZSA+IHQgJiYgKHQgPiAwICYmIChJLl9mcmVlKFkpLCBJLl9mcmVlKFIpLCBJLl9mcmVlKEcpLCBJLl9mcmVlKHUpLCBJLl9mcmVlKGQpLCBJLl9mcmVlKE0pLCBJLl9mcmVlKFMpLCBJLl9mcmVlKEwpLCBJLl9mcmVlKEopKSwgdCA9IGUsIFkgPSBJLl9tYWxsb2MoMyAqIHQgKiA0KSwgUiA9IEkuX21hbGxvYyg0ICogdCAqIDQpLCBHID0gSS5fbWFsbG9jKDMgKiB0ICogNCksIHUgPSBJLl9tYWxsb2MoNCAqIHQpLCBkID0gSS5fbWFsbG9jKHQpLCBNID0gSS5fbWFsbG9jKDggKiB0ICogNCksIFMgPSBJLl9tYWxsb2MoMyAqIHQgKiA0KSwgTCA9IEkuX21hbGxvYyg0ICogdCAqIDQpLCBKID0gSS5fbWFsbG9jKDMgKiB0ICogNCkpLCBJLkhFQVBGMzIuc2V0KEMucG9zaXRpb25zLCBZIC8gNCksIEkuSEVBUEYzMi5zZXQoQy5yb3RhdGlvbnMsIFIgLyA0KSwgSS5IRUFQRjMyLnNldChDLnNjYWxlcywgRyAvIDQpLCBJLkhFQVBVOC5zZXQoQy5jb2xvcnMsIHUpLCBJLkhFQVBVOC5zZXQoQy5zZWxlY3Rpb24sIGQpLCBJLl9wYWNrKAogICAgQy5zZWxlY3RlZCwKICAgIEMudmVydGV4Q291bnQsCiAgICBZLAogICAgUiwKICAgIEcsCiAgICB1LAogICAgZCwKICAgIE0sCiAgICBTLAogICAgTCwKICAgIEoKICApOwogIGNvbnN0IEEgPSBuZXcgVWludDMyQXJyYXkoSS5IRUFQVTMyLmJ1ZmZlciwgTSwgQy52ZXJ0ZXhDb3VudCAqIDgpLCBoID0gbmV3IFVpbnQzMkFycmF5KEEuc2xpY2UoKS5idWZmZXIpLCBrID0gbmV3IEZsb2F0MzJBcnJheShJLkhFQVBGMzIuYnVmZmVyLCBTLCBDLnZlcnRleENvdW50ICogMyksIHkgPSBuZXcgRmxvYXQzMkFycmF5KGsuc2xpY2UoKS5idWZmZXIpLCBGID0gbmV3IEZsb2F0MzJBcnJheShJLkhFQVBGMzIuYnVmZmVyLCBMLCBDLnZlcnRleENvdW50ICogNCksIEQgPSBuZXcgRmxvYXQzMkFycmF5KEYuc2xpY2UoKS5idWZmZXIpLCBOID0gbmV3IEZsb2F0MzJBcnJheShJLkhFQVBGMzIuYnVmZmVyLCBKLCBDLnZlcnRleENvdW50ICogMyksIFUgPSBuZXcgRmxvYXQzMkFycmF5KE4uc2xpY2UoKS5idWZmZXIpLCBpID0gewogICAgZGF0YTogaCwKICAgIHdvcmxkUG9zaXRpb25zOiB5LAogICAgd29ybGRSb3RhdGlvbnM6IEQsCiAgICB3b3JsZFNjYWxlczogVSwKICAgIG9mZnNldDogQy5vZmZzZXQsCiAgICB2ZXJ0ZXhDb3VudDogQy52ZXJ0ZXhDb3VudCwKICAgIHBvc2l0aW9uczogQy5wb3NpdGlvbnMuYnVmZmVyLAogICAgcm90YXRpb25zOiBDLnJvdGF0aW9ucy5idWZmZXIsCiAgICBzY2FsZXM6IEMuc2NhbGVzLmJ1ZmZlciwKICAgIGNvbG9yczogQy5jb2xvcnMuYnVmZmVyLAogICAgc2VsZWN0aW9uOiBDLnNlbGVjdGlvbi5idWZmZXIKICB9OwogIHNlbGYucG9zdE1lc3NhZ2UoeyByZXNwb25zZTogaSB9LCBbCiAgICBpLmRhdGEuYnVmZmVyLAogICAgaS53b3JsZFBvc2l0aW9ucy5idWZmZXIsCiAgICBpLndvcmxkUm90YXRpb25zLmJ1ZmZlciwKICAgIGkud29ybGRTY2FsZXMuYnVmZmVyLAogICAgaS5wb3NpdGlvbnMsCiAgICBpLnJvdGF0aW9ucywKICAgIGkuc2NhbGVzLAogICAgaS5jb2xvcnMsCiAgICBpLnNlbGVjdGlvbgogIF0pLCBLID0gITE7Cn0sIFogPSAoKSA9PiB7CiAgaWYgKGwubGVuZ3RoICE9PSAwICYmICFLKSB7CiAgICBLID0gITA7CiAgICBjb25zdCBDID0gbC5zaGlmdCgpOwogICAgZUEoQyksIHNldFRpbWVvdXQoKCkgPT4gewogICAgICBLID0gITEsIFooKTsKICAgIH0sIDApOwogIH0KfTsKc2VsZi5vbm1lc3NhZ2UgPSAoQykgPT4gewogIGlmIChDLmRhdGEuc3BsYXQpIHsKICAgIGNvbnN0IGUgPSBDLmRhdGEuc3BsYXQ7CiAgICBmb3IgKGNvbnN0IFtBLCBoXSBvZiBsLmVudHJpZXMoKSkKICAgICAgaWYgKGgub2Zmc2V0ID09PSBlLm9mZnNldCkgewogICAgICAgIGxbQV0gPSBlOwogICAgICAgIHJldHVybjsKICAgICAgfQogICAgbC5wdXNoKGUpLCBaKCk7CiAgfQp9OwovLyMgc291cmNlTWFwcGluZ1VSTD1EYXRhV29ya2VyLUJ6RWRfWmo2LmpzLm1hcAo="; + var ut = (E) => Uint8Array.from(atob(E), (t) => t.charCodeAt(0)); + var at = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", ut(gt)], { type: "text/javascript;charset=utf-8" }); + function Jt(E) { + let t; + try { + if (t = at && (self.URL || self.webkitURL).createObjectURL(at), !t) throw ""; + const n = new Worker(t, { + type: "module", + name: E?.name + }); + return n.addEventListener("error", () => { + (self.URL || self.webkitURL).revokeObjectURL(t); + }), n; + } catch { + return new Worker( + "data:text/javascript;base64," + gt, + { + type: "module", + name: E?.name + } + ); + } + } + var mt = function(E = {}) { + var t, n = E, i = import_meta.url, e = "", A; + { + try { + e = new URL(".", i).href; + } catch { + } + A = (h) => { + var m = new XMLHttpRequest(); + return m.open("GET", h, false), m.responseType = "arraybuffer", m.send(null), new Uint8Array(m.response); + }; + } + console.log.bind(console), console.error.bind(console); + var o, s, r; + function Q() { + var h = s.buffer; + n.HEAPU8 = r = new Uint8Array(h), n.HEAPU32 = new Uint32Array(h), n.HEAPF32 = new Float32Array(h), new BigInt64Array(h), new BigUint64Array(h); + } + function I() { + if (n.preRun) + for (typeof n.preRun == "function" && (n.preRun = [n.preRun]); n.preRun.length; ) + L(n.preRun.shift()); + Z(H); + } + function d() { + j.c(); + } + function a() { + if (n.postRun) + for (typeof n.postRun == "function" && (n.postRun = [n.postRun]); n.postRun.length; ) + f(n.postRun.shift()); + Z(k); + } + var U = 0, F = null; + function g(h) { + U++, n.monitorRunDependencies?.(U); + } + function B(h) { + if (U--, n.monitorRunDependencies?.(U), U == 0 && F) { + var m = F; + F = null, m(); + } + } + var C; + function c() { + return M("AGFzbQEAAAABJgZgAX8Bf2ACfX0Bf2ABfQF/YAF/AGALf39/f39/f39/f38AYAAAAgcBAWEBYQAAAwgHAAECAwAEBQUHAQGCAoCAAgYIAX8BQYCMBAsHFQUBYgIAAWMABwFkAAYBZQAFAWYABAwBAQqqQAdPAQJ/QYAIKAIAIgEgAEEHakF4cSICaiEAAkAgAkEAIAAgAU0bRQRAIAA/AEEQdE0NASAAEAANAQtBhAhBMDYCAEF/DwtBgAggADYCACABCw4AIAAQAyABEANBEHRyC3IBBH8gALwiBEH///8DcSEBAkAgBEEXdkH/AXEiAkUNACACQfAATQRAIAFBgICABHJB8QAgAmt2IQEMAQsgAkGNAUsEQEGA+AEhA0EAIQEMAQsgAkEKdEGAgAdrIQMLIAMgBEEQdkGAgAJxciABQQ12cgvcCwEIfwJAIABFDQAgAEEIayIDIABBBGsoAgAiAkF4cSIAaiEFAkAgAkEBcQ0AIAJBAnFFDQEgAyADKAIAIgRrIgNBmAgoAgBJDQEgACAEaiEAAkACQAJAQZwIKAIAIANHBEAgAygCDCEBIARB/wFNBEAgASADKAIIIgJHDQJBiAhBiAgoAgBBfiAEQQN2d3E2AgAMBQsgAygCGCEHIAEgA0cEQCADKAIIIgIgATYCDCABIAI2AggMBAsgAygCFCICBH8gA0EUagUgAygCECICRQ0DIANBEGoLIQQDQCAEIQYgAiIBQRRqIQQgASgCFCICDQAgAUEQaiEEIAEoAhAiAg0ACyAGQQA2AgAMAwsgBSgCBCICQQNxQQNHDQNBkAggADYCACAFIAJBfnE2AgQgAyAAQQFyNgIEIAUgADYCAA8LIAIgATYCDCABIAI2AggMAgtBACEBCyAHRQ0AAkAgAygCHCIEQQJ0QbgKaiICKAIAIANGBEAgAiABNgIAIAENAUGMCEGMCCgCAEF+IAR3cTYCAAwCCwJAIAMgBygCEEYEQCAHIAE2AhAMAQsgByABNgIUCyABRQ0BCyABIAc2AhggAygCECICBEAgASACNgIQIAIgATYCGAsgAygCFCICRQ0AIAEgAjYCFCACIAE2AhgLIAMgBU8NACAFKAIEIgRBAXFFDQACQAJAAkACQCAEQQJxRQRAQaAIKAIAIAVGBEBBoAggAzYCAEGUCEGUCCgCACAAaiIANgIAIAMgAEEBcjYCBCADQZwIKAIARw0GQZAIQQA2AgBBnAhBADYCAA8LQZwIKAIAIgcgBUYEQEGcCCADNgIAQZAIQZAIKAIAIABqIgA2AgAgAyAAQQFyNgIEIAAgA2ogADYCAA8LIARBeHEgAGohACAFKAIMIQEgBEH/AU0EQCAFKAIIIgIgAUYEQEGICEGICCgCAEF+IARBA3Z3cTYCAAwFCyACIAE2AgwgASACNgIIDAQLIAUoAhghCCABIAVHBEAgBSgCCCICIAE2AgwgASACNgIIDAMLIAUoAhQiAgR/IAVBFGoFIAUoAhAiAkUNAiAFQRBqCyEEA0AgBCEGIAIiAUEUaiEEIAEoAhQiAg0AIAFBEGohBCABKAIQIgINAAsgBkEANgIADAILIAUgBEF+cTYCBCADIABBAXI2AgQgACADaiAANgIADAMLQQAhAQsgCEUNAAJAIAUoAhwiBEECdEG4CmoiAigCACAFRgRAIAIgATYCACABDQFBjAhBjAgoAgBBfiAEd3E2AgAMAgsCQCAFIAgoAhBGBEAgCCABNgIQDAELIAggATYCFAsgAUUNAQsgASAINgIYIAUoAhAiAgRAIAEgAjYCECACIAE2AhgLIAUoAhQiAkUNACABIAI2AhQgAiABNgIYCyADIABBAXI2AgQgACADaiAANgIAIAMgB0cNAEGQCCAANgIADwsgAEH/AU0EQCAAQXhxQbAIaiECAn9BiAgoAgAiBEEBIABBA3Z0IgBxRQRAQYgIIAAgBHI2AgAgAgwBCyACKAIICyEAIAIgAzYCCCAAIAM2AgwgAyACNgIMIAMgADYCCA8LQR8hASAAQf///wdNBEAgAEEmIABBCHZnIgJrdkEBcSACQQF0a0E+aiEBCyADIAE2AhwgA0IANwIQIAFBAnRBuApqIQQCfwJAAn9BjAgoAgAiBkEBIAF0IgJxRQRAQYwIIAIgBnI2AgAgBCADNgIAQRghAUEIDAELIABBGSABQQF2a0EAIAFBH0cbdCEBIAQoAgAhBANAIAQiAigCBEF4cSAARg0CIAFBHXYhBCABQQF0IQEgAiAEQQRxaiIGKAIQIgQNAAsgBiADNgIQQRghASACIQRBCAshACADIgIMAQsgAigCCCIEIAM2AgwgAiADNgIIQRghAEEIIQFBAAshBiABIANqIAQ2AgAgAyACNgIMIAAgA2ogBjYCAEGoCEGoCCgCAEEBayIAQX8gABs2AgALC9EnAQt/IwBBEGsiCiQAAkACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEGICCgCACIEQRAgAEELakH4A3EgAEELSRsiBkEDdiIAdiIBQQNxBEACQCABQX9zQQFxIABqIgJBA3QiAUGwCGoiACABQbgIaigCACIBKAIIIgVGBEBBiAggBEF+IAJ3cTYCAAwBCyAFIAA2AgwgACAFNgIICyABQQhqIQAgASACQQN0IgJBA3I2AgQgASACaiIBIAEoAgRBAXI2AgQMCwsgBkGQCCgCACIITQ0BIAEEQAJAQQIgAHQiAkEAIAJrciABIAB0cWgiAUEDdCIAQbAIaiICIABBuAhqKAIAIgAoAggiBUYEQEGICCAEQX4gAXdxIgQ2AgAMAQsgBSACNgIMIAIgBTYCCAsgACAGQQNyNgIEIAAgBmoiByABQQN0IgEgBmsiBUEBcjYCBCAAIAFqIAU2AgAgCARAIAhBeHFBsAhqIQFBnAgoAgAhAgJ/IARBASAIQQN2dCIDcUUEQEGICCADIARyNgIAIAEMAQsgASgCCAshAyABIAI2AgggAyACNgIMIAIgATYCDCACIAM2AggLIABBCGohAEGcCCAHNgIAQZAIIAU2AgAMCwtBjAgoAgAiC0UNASALaEECdEG4CmooAgAiAigCBEF4cSAGayEDIAIhAQNAAkAgASgCECIARQRAIAEoAhQiAEUNAQsgACgCBEF4cSAGayIBIAMgASADSSIBGyEDIAAgAiABGyECIAAhAQwBCwsgAigCGCEJIAIgAigCDCIARwRAIAIoAggiASAANgIMIAAgATYCCAwKCyACKAIUIgEEfyACQRRqBSACKAIQIgFFDQMgAkEQagshBQNAIAUhByABIgBBFGohBSAAKAIUIgENACAAQRBqIQUgACgCECIBDQALIAdBADYCAAwJC0F/IQYgAEG/f0sNACAAQQtqIgFBeHEhBkGMCCgCACIHRQ0AQR8hCEEAIAZrIQMgAEH0//8HTQRAIAZBJiABQQh2ZyIAa3ZBAXEgAEEBdGtBPmohCAsCQAJAAkAgCEECdEG4CmooAgAiAUUEQEEAIQAMAQtBACEAIAZBGSAIQQF2a0EAIAhBH0cbdCECA0ACQCABKAIEQXhxIAZrIgQgA08NACABIQUgBCIDDQBBACEDIAEhAAwDCyAAIAEoAhQiBCAEIAEgAkEddkEEcWooAhAiAUYbIAAgBBshACACQQF0IQIgAQ0ACwsgACAFckUEQEEAIQVBAiAIdCIAQQAgAGtyIAdxIgBFDQMgAGhBAnRBuApqKAIAIQALIABFDQELA0AgACgCBEF4cSAGayICIANJIQEgAiADIAEbIQMgACAFIAEbIQUgACgCECIBBH8gAQUgACgCFAsiAA0ACwsgBUUNACADQZAIKAIAIAZrTw0AIAUoAhghCCAFIAUoAgwiAEcEQCAFKAIIIgEgADYCDCAAIAE2AggMCAsgBSgCFCIBBH8gBUEUagUgBSgCECIBRQ0DIAVBEGoLIQIDQCACIQQgASIAQRRqIQIgACgCFCIBDQAgAEEQaiECIAAoAhAiAQ0ACyAEQQA2AgAMBwsgBkGQCCgCACIFTQRAQZwIKAIAIQACQCAFIAZrIgFBEE8EQCAAIAZqIgIgAUEBcjYCBCAAIAVqIAE2AgAgACAGQQNyNgIEDAELIAAgBUEDcjYCBCAAIAVqIgEgASgCBEEBcjYCBEEAIQJBACEBC0GQCCABNgIAQZwIIAI2AgAgAEEIaiEADAkLIAZBlAgoAgAiAkkEQEGUCCACIAZrIgE2AgBBoAhBoAgoAgAiACAGaiICNgIAIAIgAUEBcjYCBCAAIAZBA3I2AgQgAEEIaiEADAkLQQAhACAGQS9qIgMCf0HgCygCAARAQegLKAIADAELQewLQn83AgBB5AtCgKCAgICABDcCAEHgCyAKQQxqQXBxQdiq1aoFczYCAEH0C0EANgIAQcQLQQA2AgBBgCALIgFqIgRBACABayIHcSIBIAZNDQhBwAsoAgAiBQRAQbgLKAIAIgggAWoiCSAITSAFIAlJcg0JCwJAQcQLLQAAQQRxRQRAAkACQAJAAkBBoAgoAgAiBQRAQcgLIQADQCAAKAIAIgggBU0EQCAFIAggACgCBGpJDQMLIAAoAggiAA0ACwtBABABIgJBf0YNAyABIQRB5AsoAgAiAEEBayIFIAJxBEAgASACayACIAVqQQAgAGtxaiEECyAEIAZNDQNBwAsoAgAiAARAQbgLKAIAIgUgBGoiByAFTSAAIAdJcg0ECyAEEAEiACACRw0BDAULIAQgAmsgB3EiBBABIgIgACgCACAAKAIEakYNASACIQALIABBf0YNASAGQTBqIARNBEAgACECDAQLQegLKAIAIgIgAyAEa2pBACACa3EiAhABQX9GDQEgAiAEaiEEIAAhAgwDCyACQX9HDQILQcQLQcQLKAIAQQRyNgIACyABEAEiAkF/RkEAEAEiAEF/RnIgACACTXINBSAAIAJrIgQgBkEoak0NBQtBuAtBuAsoAgAgBGoiADYCAEG8CygCACAASQRAQbwLIAA2AgALAkBBoAgoAgAiAwRAQcgLIQADQCACIAAoAgAiASAAKAIEIgVqRg0CIAAoAggiAA0ACwwEC0GYCCgCACIAQQAgACACTRtFBEBBmAggAjYCAAtBACEAQcwLIAQ2AgBByAsgAjYCAEGoCEF/NgIAQawIQeALKAIANgIAQdQLQQA2AgADQCAAQQN0IgFBuAhqIAFBsAhqIgU2AgAgAUG8CGogBTYCACAAQQFqIgBBIEcNAAtBlAggBEEoayIAQXggAmtBB3EiAWsiBTYCAEGgCCABIAJqIgE2AgAgASAFQQFyNgIEIAAgAmpBKDYCBEGkCEHwCygCADYCAAwECyACIANNIAEgA0tyDQIgACgCDEEIcQ0CIAAgBCAFajYCBEGgCCADQXggA2tBB3EiAGoiATYCAEGUCEGUCCgCACAEaiICIABrIgA2AgAgASAAQQFyNgIEIAIgA2pBKDYCBEGkCEHwCygCADYCAAwDC0EAIQAMBgtBACEADAQLQZgIKAIAIAJLBEBBmAggAjYCAAsgAiAEaiEFQcgLIQACQANAIAUgACgCACIBRwRAIAAoAggiAA0BDAILCyAALQAMQQhxRQ0DC0HICyEAA0ACQCAAKAIAIgEgA00EQCADIAEgACgCBGoiBUkNAQsgACgCCCEADAELC0GUCCAEQShrIgBBeCACa0EHcSIBayIHNgIAQaAIIAEgAmoiATYCACABIAdBAXI2AgQgACACakEoNgIEQaQIQfALKAIANgIAIAMgBUEnIAVrQQdxakEvayIAIAAgA0EQakkbIgFBGzYCBCABQdALKQIANwIQIAFByAspAgA3AghB0AsgAUEIajYCAEHMCyAENgIAQcgLIAI2AgBB1AtBADYCACABQRhqIQADQCAAQQc2AgQgAEEIaiAAQQRqIQAgBUkNAAsgASADRg0AIAEgASgCBEF+cTYCBCADIAEgA2siAkEBcjYCBCABIAI2AgACfyACQf8BTQRAIAJBeHFBsAhqIQACf0GICCgCACIBQQEgAkEDdnQiAnFFBEBBiAggASACcjYCACAADAELIAAoAggLIQEgACADNgIIIAEgAzYCDEEMIQJBCAwBC0EfIQAgAkH///8HTQRAIAJBJiACQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAAsgAyAANgIcIANCADcCECAAQQJ0QbgKaiEBAkACQEGMCCgCACIFQQEgAHQiBHFFBEBBjAggBCAFcjYCACABIAM2AgAMAQsgAkEZIABBAXZrQQAgAEEfRxt0IQAgASgCACEFA0AgBSIBKAIEQXhxIAJGDQIgAEEddiEFIABBAXQhACABIAVBBHFqIgQoAhAiBQ0ACyAEIAM2AhALIAMgATYCGEEIIQIgAyIBIQBBDAwBCyABKAIIIgAgAzYCDCABIAM2AgggAyAANgIIQQAhAEEYIQJBDAsgA2ogATYCACACIANqIAA2AgALQZQIKAIAIgAgBk0NAEGUCCAAIAZrIgE2AgBBoAhBoAgoAgAiACAGaiICNgIAIAIgAUEBcjYCBCAAIAZBA3I2AgQgAEEIaiEADAQLQYQIQTA2AgBBACEADAMLIAAgAjYCACAAIAAoAgQgBGo2AgQgAkF4IAJrQQdxaiIIIAZBA3I2AgQgAUF4IAFrQQdxaiIEIAYgCGoiA2shBwJAQaAIKAIAIARGBEBBoAggAzYCAEGUCEGUCCgCACAHaiIANgIAIAMgAEEBcjYCBAwBC0GcCCgCACAERgRAQZwIIAM2AgBBkAhBkAgoAgAgB2oiADYCACADIABBAXI2AgQgACADaiAANgIADAELIAQoAgQiAEEDcUEBRgRAIABBeHEhCSAEKAIMIQICQCAAQf8BTQRAIAQoAggiASACRgRAQYgIQYgIKAIAQX4gAEEDdndxNgIADAILIAEgAjYCDCACIAE2AggMAQsgBCgCGCEGAkAgAiAERwRAIAQoAggiACACNgIMIAIgADYCCAwBCwJAIAQoAhQiAAR/IARBFGoFIAQoAhAiAEUNASAEQRBqCyEBA0AgASEFIAAiAkEUaiEBIAAoAhQiAA0AIAJBEGohASACKAIQIgANAAsgBUEANgIADAELQQAhAgsgBkUNAAJAIAQoAhwiAEECdEG4CmoiASgCACAERgRAIAEgAjYCACACDQFBjAhBjAgoAgBBfiAAd3E2AgAMAgsCQCAEIAYoAhBGBEAgBiACNgIQDAELIAYgAjYCFAsgAkUNAQsgAiAGNgIYIAQoAhAiAARAIAIgADYCECAAIAI2AhgLIAQoAhQiAEUNACACIAA2AhQgACACNgIYCyAHIAlqIQcgBCAJaiIEKAIEIQALIAQgAEF+cTYCBCADIAdBAXI2AgQgAyAHaiAHNgIAIAdB/wFNBEAgB0F4cUGwCGohAAJ/QYgIKAIAIgFBASAHQQN2dCICcUUEQEGICCABIAJyNgIAIAAMAQsgACgCCAshASAAIAM2AgggASADNgIMIAMgADYCDCADIAE2AggMAQtBHyECIAdB////B00EQCAHQSYgB0EIdmciAGt2QQFxIABBAXRrQT5qIQILIAMgAjYCHCADQgA3AhAgAkECdEG4CmohAAJAAkBBjAgoAgAiAUEBIAJ0IgVxRQRAQYwIIAEgBXI2AgAgACADNgIADAELIAdBGSACQQF2a0EAIAJBH0cbdCECIAAoAgAhAQNAIAEiACgCBEF4cSAHRg0CIAJBHXYhASACQQF0IQIgACABQQRxaiIFKAIQIgENAAsgBSADNgIQCyADIAA2AhggAyADNgIMIAMgAzYCCAwBCyAAKAIIIgEgAzYCDCAAIAM2AgggA0EANgIYIAMgADYCDCADIAE2AggLIAhBCGohAAwCCwJAIAhFDQACQCAFKAIcIgFBAnRBuApqIgIoAgAgBUYEQCACIAA2AgAgAA0BQYwIIAdBfiABd3EiBzYCAAwCCwJAIAUgCCgCEEYEQCAIIAA2AhAMAQsgCCAANgIUCyAARQ0BCyAAIAg2AhggBSgCECIBBEAgACABNgIQIAEgADYCGAsgBSgCFCIBRQ0AIAAgATYCFCABIAA2AhgLAkAgA0EPTQRAIAUgAyAGaiIAQQNyNgIEIAAgBWoiACAAKAIEQQFyNgIEDAELIAUgBkEDcjYCBCAFIAZqIgQgA0EBcjYCBCADIARqIAM2AgAgA0H/AU0EQCADQXhxQbAIaiEAAn9BiAgoAgAiAUEBIANBA3Z0IgJxRQRAQYgIIAEgAnI2AgAgAAwBCyAAKAIICyEBIAAgBDYCCCABIAQ2AgwgBCAANgIMIAQgATYCCAwBC0EfIQAgA0H///8HTQRAIANBJiADQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAAsgBCAANgIcIARCADcCECAAQQJ0QbgKaiEBAkACQCAHQQEgAHQiAnFFBEBBjAggAiAHcjYCACABIAQ2AgAgBCABNgIYDAELIANBGSAAQQF2a0EAIABBH0cbdCEAIAEoAgAhAQNAIAEiAigCBEF4cSADRg0CIABBHXYhASAAQQF0IQAgAiABQQRxaiIHKAIQIgENAAsgByAENgIQIAQgAjYCGAsgBCAENgIMIAQgBDYCCAwBCyACKAIIIgAgBDYCDCACIAQ2AgggBEEANgIYIAQgAjYCDCAEIAA2AggLIAVBCGohAAwBCwJAIAlFDQACQCACKAIcIgFBAnRBuApqIgUoAgAgAkYEQCAFIAA2AgAgAA0BQYwIIAtBfiABd3E2AgAMAgsCQCACIAkoAhBGBEAgCSAANgIQDAELIAkgADYCFAsgAEUNAQsgACAJNgIYIAIoAhAiAQRAIAAgATYCECABIAA2AhgLIAIoAhQiAUUNACAAIAE2AhQgASAANgIYCwJAIANBD00EQCACIAMgBmoiAEEDcjYCBCAAIAJqIgAgACgCBEEBcjYCBAwBCyACIAZBA3I2AgQgAiAGaiIFIANBAXI2AgQgAyAFaiADNgIAIAgEQCAIQXhxQbAIaiEAQZwIKAIAIQECf0EBIAhBA3Z0IgcgBHFFBEBBiAggBCAHcjYCACAADAELIAAoAggLIQQgACABNgIIIAQgATYCDCABIAA2AgwgASAENgIIC0GcCCAFNgIAQZAIIAM2AgALIAJBCGohAAsgCkEQaiQAIAALoQsCC38JfSMAQaABayILJAAgC0EwakEAQST8CwADQCABIA5HBEAgAiAOQQNsIgxBAmpBAnQiD2oqAgAhFyACIAxBAWpBAnQiEGoqAgAhGCAIIAxBAnQiEWogAiARaioCACIZOAIAIAggEGogGDgCACAIIA9qIBc4AgAgByAOQQV0aiINQQA2AgwgDSAXOAIIIA0gGDgCBCANIBk4AgACQCAARQRAIAYgDmotAABFDQELIA1BgICACDYCDAsgDSAFIA5BAnQiDEEBciISai0AAEEIdCAFIAxqLQAAciAFIAxBAnIiE2otAABBEHRyIAUgDEEDciIMai0AAEEYdHI2AhwgCyADIBJBAnQiEmoqAgAiFzgCkAEgCyADIBNBAnQiE2oqAgAiGDgClAEgCyADIAxBAnQiFGoqAgAiGTgCmAEgCyADIA5BBHQiFWoqAgCMIho4ApwBIAtB4ABqIgwgCyoCmAEiFkMAAADAlCAWlCALKgKUASIWQwAAAMCUIBaUQwAAgD+SkjgCACAMIAsqApABIhYgFpIgCyoClAGUIAsqApgBIhYgFpIgCyoCnAGUkzgCBCAMIAsqApABIhYgFpIgCyoCmAGUIAsqApQBIhYgFpIgCyoCnAGUkjgCCCAMIAsqApABIhYgFpIgCyoClAGUIAsqApgBIhYgFpIgCyoCnAGUkjgCDCAMIAsqApgBIhZDAAAAwJQgFpQgCyoCkAEiFkMAAADAlCAWlEMAAIA/kpI4AhAgDCALKgKUASIWIBaSIAsqApgBlCALKgKQASIWIBaSIAsqApwBlJM4AhQgDCALKgKQASIWIBaSIAsqApgBlCALKgKUASIWIBaSIAsqApwBlJM4AhggDCALKgKUASIWIBaSIAsqApgBlCALKgKQASIWIBaSIAsqApwBlJI4AhwgDCALKgKUASIWQwAAAMCUIBaUIAsqApABIhZDAAAAwJQgFpRDAACAP5KSOAIgIAkgFWogFzgCACAJIBJqIBg4AgAgCSATaiAZOAIAIAkgFGogGjgCACALIAQgEWoqAgAiFzgCMCALIAQgEGoqAgAiGDgCQCALIAQgD2oqAgAiGTgCUCAKIBFqIBc4AgAgCiAQaiAYOAIAIAogD2ogGTgCACALIAwqAhggCyoCOJQgDCoCACALKgIwlCAMKgIMIAsqAjSUkpI4AgAgCyAMKgIcIAsqAjiUIAwqAgQgCyoCMJQgDCoCECALKgI0lJKSOAIEIAsgDCoCICALKgI4lCAMKgIIIAsqAjCUIAwqAhQgCyoCNJSSkjgCCCALIAwqAhggCyoCRJQgDCoCACALKgI8lCAMKgIMIAsqAkCUkpI4AgwgCyAMKgIcIAsqAkSUIAwqAgQgCyoCPJQgDCoCECALKgJAlJKSOAIQIAsgDCoCICALKgJElCAMKgIIIAsqAjyUIAwqAhQgCyoCQJSSkjgCFCALIAwqAhggCyoCUJQgDCoCACALKgJIlCAMKgIMIAsqAkyUkpI4AhggCyAMKgIcIAsqAlCUIAwqAgQgCyoCSJQgDCoCECALKgJMlJKSOAIcIAsgDCoCICALKgJQlCAMKgIIIAsqAkiUIAwqAhQgCyoCTJSSkjgCICALKgIgIRcgCyoCCCEYIAsqAhQhGSANIAsqAhgiGiAalCALKgIAIhYgFpQgCyoCDCIbIBuUkpJDAACAQJQgGiALKgIcIhyUIBYgCyoCBCIdlCAbIAsqAhAiHpSSkkMAAIBAlBACNgIQIA0gGiAXlCAWIBiUIBsgGZSSkkMAAIBAlCAcIByUIB0gHZQgHiAelJKSQwAAgECUEAI2AhQgDSAcIBeUIB0gGJQgHiAZlJKSQwAAgECUIBcgF5QgGCAYlCAZIBmUkpJDAACAQJQQAjYCGCAOQQFqIQ4MAQsLIAtBoAFqJAALAgALCwkBAEGBCAsCBgE="); + } + function p(h) { + if (ArrayBuffer.isView(h)) + return h; + if (h == C && o) + return new Uint8Array(o); + if (A) + return A(h); + throw 'sync fetching of the wasm failed: you can preload it to Module["wasmBinary"] manually, or emcc.py will do that for you when generating HTML (but not JS)'; + } + function u(h, m) { + var x, N = p(h); + x = new WebAssembly.Module(N); + var v = new WebAssembly.Instance(x, m); + return [v, x]; + } + function S() { + return { a: b }; + } + function W() { + function h(N, v) { + return j = N.exports, s = j.b, Q(), D(j), B(), j; + } + g(); + var m = S(); + if (n.instantiateWasm) + return new Promise((N, v) => { + n.instantiateWasm(m, (O, $) => { + N(h(O)); + }); + }); + C ?? (C = c()); + var x = u(C, m); + return h(x[0]); + } + for (var Z = (h) => { + for (; h.length > 0; ) + h.shift()(n); + }, k = [], f = (h) => k.push(h), H = [], L = (h) => H.push(h), M = (h) => { + for (var m, x, N = 0, v = 0, O = h.length, $ = new Uint8Array((O * 3 >> 2) - (h[O - 2] == "=") - (h[O - 1] == "=")); N < O; N += 4, v += 3) + m = l[h.charCodeAt(N + 1)], x = l[h.charCodeAt(N + 2)], $[v] = l[h.charCodeAt(N)] << 2 | m >> 4, $[v + 1] = m << 4 | x >> 2, $[v + 2] = x << 6 | l[h.charCodeAt(N + 3)]; + return $; + }, V = () => 2147483648, w = (h, m) => Math.ceil(h / m) * m, P = (h) => { + var m = s.buffer, x = (h - m.byteLength + 65535) / 65536 | 0; + try { + return s.grow(x), Q(), 1; + } catch { + } + }, T = (h) => { + var m = r.length; + h >>>= 0; + var x = V(); + if (h > x) + return false; + for (var N = 1; N <= 4; N *= 2) { + var v = m * (1 + 0.2 / N); + v = Math.min(v, h + 100663296); + var O = Math.min(x, w(Math.max(h, v), 65536)), $ = P(O); + if ($) + return true; + } + return false; + }, l = new Uint8Array(123), J = 25; J >= 0; --J) + l[48 + J] = 52 + J, l[65 + J] = J, l[97 + J] = 26 + J; + l[43] = 62, l[47] = 63, n.noExitRuntime && n.noExitRuntime, n.print && n.print, n.printErr && n.printErr, n.wasmBinary && (o = n.wasmBinary), n.arguments && n.arguments, n.thisProgram && n.thisProgram; + function D(h) { + n._pack = h.d, n._malloc = h.e, n._free = h.f; + } + var b = { a: T }, j = W(); + function q() { + if (U > 0) { + F = q; + return; + } + if (I(), U > 0) { + F = q; + return; + } + function h() { + n.calledRun = true, d(), n.onRuntimeInitialized?.(), a(); + } + n.setStatus ? (n.setStatus("Running..."), setTimeout(() => { + setTimeout(() => n.setStatus(""), 1), h(); + }, 1)) : h(); + } + function G() { + if (n.preInit) + for (typeof n.preInit == "function" && (n.preInit = [n.preInit]); n.preInit.length > 0; ) + n.preInit.shift()(); + } + return G(), q(), t = n, t; + }; + var ft = () => new Jt(); + var Ut = class { + constructor(t) { + this.dataChanged = false, this.transformsChanged = false, this.colorTransformsChanged = false, this._updating = /* @__PURE__ */ new Set(), this._dirty = /* @__PURE__ */ new Set(); + let n = 0, i = 0; + this._splatIndices = /* @__PURE__ */ new Map(), this._offsets = /* @__PURE__ */ new Map(); + const e = /* @__PURE__ */ new Map(); + for (const a of t.objects) + a instanceof X && (this._splatIndices.set(a, i), this._offsets.set(a, n), e.set(n, a), n += a.data.vertexCount, i++); + this._vertexCount = n, this._width = 2048, this._height = Math.ceil(2 * this.vertexCount / this.width), this._data = new Uint32Array(this.width * this.height * 4), this._transformsWidth = 5, this._transformsHeight = e.size, this._transforms = new Float32Array(this._transformsWidth * this._transformsHeight * 4), this._transformIndicesWidth = 1024, this._transformIndicesHeight = Math.ceil(this.vertexCount / this._transformIndicesWidth), this._transformIndices = new Uint32Array(this._transformIndicesWidth * this._transformIndicesHeight), this._colorTransformsWidth = 4, this._colorTransformsHeight = 64, this._colorTransforms = new Float32Array(this._colorTransformsWidth * this._colorTransformsHeight * 4), this._colorTransforms.fill(0), this._colorTransforms[0] = 1, this._colorTransforms[5] = 1, this._colorTransforms[10] = 1, this._colorTransforms[15] = 1, this._colorTransformIndicesWidth = 1024, this._colorTransformIndicesHeight = Math.ceil(this.vertexCount / this._colorTransformIndicesWidth), this._colorTransformIndices = new Uint32Array( + this._colorTransformIndicesWidth * this._colorTransformIndicesHeight + ), this.colorTransformIndices.fill(0), this._positions = new Float32Array(this.vertexCount * 3), this._rotations = new Float32Array(this.vertexCount * 4), this._scales = new Float32Array(this.vertexCount * 3), this._worker = ft(); + const A = (a) => { + const U = this._splatIndices.get(a); + this._transforms.set(a.transform.buffer, U * 20), this._transforms[U * 20 + 16] = a.selected ? 1 : 0, a.positionChanged = false, a.rotationChanged = false, a.scaleChanged = false, a.selectedChanged = false, this.transformsChanged = true; + }, o = () => { + let a = false; + for (const g of this._splatIndices.keys()) + if (g.colorTransformChanged) { + a = true; + break; + } + if (!a) + return; + const U = [new K()]; + this._colorTransformIndices.fill(0); + let F = 1; + for (const g of this._splatIndices.keys()) { + const B = this._offsets.get(g); + for (const C of g.colorTransforms) + U.includes(C) || (U.push(C), F++); + for (const C of g.colorTransformsMap.keys()) { + const c = g.colorTransformsMap.get(C); + this._colorTransformIndices[C + B] = c + F - 1; + } + g.colorTransformChanged = false; + } + for (let g = 0; g < U.length; g++) { + const B = U[g]; + this._colorTransforms.set(B.buffer, g * 16); + } + this.colorTransformsChanged = true; + }; + this._worker.onmessage = (a) => { + if (a.data.response) { + const U = a.data.response, F = e.get(U.offset); + A(F), o(); + const g = this._splatIndices.get(F); + for (let B = 0; B < F.data.vertexCount; B++) + this._transformIndices[U.offset + B] = g; + this._data.set(U.data, U.offset * 8), F.data.reattach( + U.positions, + U.rotations, + U.scales, + U.colors, + U.selection + ), this._positions.set(U.worldPositions, U.offset * 3), this._rotations.set(U.worldRotations, U.offset * 4), this._scales.set(U.worldScales, U.offset * 3), this._updating.delete(F), F.selectedChanged = false, this.dataChanged = true; + } + }; + let s; + async function r() { + s = await mt(); + } + r(); + async function Q() { + for (; !s; ) + await new Promise((a) => setTimeout(a, 0)); + } + const I = (a) => { + if (!s) { + Q().then(() => { + I(a); + }); + return; + } + A(a); + const U = s._malloc(3 * a.data.vertexCount * 4), F = s._malloc(4 * a.data.vertexCount * 4), g = s._malloc(3 * a.data.vertexCount * 4), B = s._malloc(4 * a.data.vertexCount), C = s._malloc(a.data.vertexCount), c = s._malloc(8 * a.data.vertexCount * 4), p = s._malloc(3 * a.data.vertexCount * 4), u = s._malloc(4 * a.data.vertexCount * 4), S = s._malloc(3 * a.data.vertexCount * 4); + s.HEAPF32.set(a.data.positions, U / 4), s.HEAPF32.set(a.data.rotations, F / 4), s.HEAPF32.set(a.data.scales, g / 4), s.HEAPU8.set(a.data.colors, B), s.HEAPU8.set(a.data.selection, C), s._pack( + a.selected, + a.data.vertexCount, + U, + F, + g, + B, + C, + c, + p, + u, + S + ); + const W = new Uint32Array(s.HEAPU32.buffer, c, a.data.vertexCount * 8), Z = new Float32Array( + s.HEAPF32.buffer, + p, + a.data.vertexCount * 3 + ), k = new Float32Array( + s.HEAPF32.buffer, + u, + a.data.vertexCount * 4 + ), f = new Float32Array(s.HEAPF32.buffer, S, a.data.vertexCount * 3), H = this._splatIndices.get(a), L = this._offsets.get(a); + for (let M = 0; M < a.data.vertexCount; M++) + this._transformIndices[L + M] = H; + this._data.set(W, L * 8), this._positions.set(Z, L * 3), this._rotations.set(k, L * 4), this._scales.set(f, L * 3), s._free(U), s._free(F), s._free(g), s._free(B), s._free(C), s._free(c), s._free(p), s._free(u), s._free(S), this.dataChanged = true, this.colorTransformsChanged = true; + }, d = (a) => { + if ((a.positionChanged || a.rotationChanged || a.scaleChanged || a.selectedChanged) && A(a), a.colorTransformChanged && o(), !a.data.changed || a.data.detached) return; + const U = { + position: new Float32Array(a.position.flat()), + rotation: new Float32Array(a.rotation.flat()), + scale: new Float32Array(a.scale.flat()), + selected: a.selected, + vertexCount: a.data.vertexCount, + positions: a.data.positions, + rotations: a.data.rotations, + scales: a.data.scales, + colors: a.data.colors, + selection: a.data.selection, + offset: this._offsets.get(a) + }; + this._worker.postMessage( + { + splat: U + }, + [ + U.position.buffer, + U.rotation.buffer, + U.scale.buffer, + U.positions.buffer, + U.rotations.buffer, + U.scales.buffer, + U.colors.buffer, + U.selection.buffer + ] + ), this._updating.add(a), a.data.detached = true; + }; + this.getSplat = (a) => { + let U = null; + for (const [F, g] of this._offsets) + if (a >= g) + U = F; + else + break; + return U; + }, this.getLocalIndex = (a, U) => { + const F = this._offsets.get(a); + return U - F; + }, this.markDirty = (a) => { + this._dirty.add(a); + }, this.rebuild = () => { + for (const a of this._dirty) + d(a); + this._dirty.clear(); + }, this.dispose = () => { + this._worker.terminate(); + }; + for (const a of this._splatIndices.keys()) + I(a); + o(); + } + get offsets() { + return this._offsets; + } + get data() { + return this._data; + } + get width() { + return this._width; + } + get height() { + return this._height; + } + get transforms() { + return this._transforms; + } + get transformsWidth() { + return this._transformsWidth; + } + get transformsHeight() { + return this._transformsHeight; + } + get transformIndices() { + return this._transformIndices; + } + get transformIndicesWidth() { + return this._transformIndicesWidth; + } + get transformIndicesHeight() { + return this._transformIndicesHeight; + } + get colorTransforms() { + return this._colorTransforms; + } + get colorTransformsWidth() { + return this._colorTransformsWidth; + } + get colorTransformsHeight() { + return this._colorTransformsHeight; + } + get colorTransformIndices() { + return this._colorTransformIndices; + } + get colorTransformIndicesWidth() { + return this._colorTransformIndicesWidth; + } + get colorTransformIndicesHeight() { + return this._colorTransformIndicesHeight; + } + get positions() { + return this._positions; + } + get rotations() { + return this._rotations; + } + get scales() { + return this._scales; + } + get vertexCount() { + return this._vertexCount; + } + get needsRebuild() { + return this._dirty.size > 0; + } + get updating() { + return this._updating.size > 0; + } + }; + var dt = class { + constructor(t = 0, n = 0, i = 0, e = 255) { + this.r = t, this.g = n, this.b = i, this.a = e; + } + flat() { + return [this.r, this.g, this.b, this.a]; + } + flatNorm() { + return [this.r / 255, this.g / 255, this.b / 255, this.a / 255]; + } + toHexString() { + return "#" + this.flat().map((t) => t.toString(16).padStart(2, "0")).join(""); + } + toString() { + return `[${this.flat().join(", ")}]`; + } + }; + var Vt = () => new St(); + var Zt = ( + /* glsl */ + `#version 300 es +precision highp float; +precision highp int; + +uniform highp usampler2D u_texture; +uniform highp sampler2D u_transforms; +uniform highp usampler2D u_transformIndices; +uniform highp sampler2D u_colorTransforms; +uniform highp usampler2D u_colorTransformIndices; +uniform mat4 projection, view; +uniform vec2 focal; +uniform vec2 viewport; + +uniform bool useDepthFade; +uniform float depthFade; + +in vec2 position; +in int index; + +out vec4 vColor; +out vec2 vPosition; +out float vSize; +out float vSelected; + +void main () { + uvec4 cen = texelFetch(u_texture, ivec2((uint(index) & 0x3ffu) << 1, uint(index) >> 10), 0); + float selected = float((cen.w >> 24) & 0xffu); + + uint transformIndex = texelFetch(u_transformIndices, ivec2(uint(index) & 0x3ffu, uint(index) >> 10), 0).x; + mat4 transform = mat4( + texelFetch(u_transforms, ivec2(0, transformIndex), 0), + texelFetch(u_transforms, ivec2(1, transformIndex), 0), + texelFetch(u_transforms, ivec2(2, transformIndex), 0), + texelFetch(u_transforms, ivec2(3, transformIndex), 0) + ); + + if (selected < 0.5) { + selected = texelFetch(u_transforms, ivec2(4, transformIndex), 0).x; + } + + mat4 viewTransform = view * transform; + + vec4 cam = viewTransform * vec4(uintBitsToFloat(cen.xyz), 1); + vec4 pos2d = projection * cam; + + float clip = 1.2 * pos2d.w; + if (pos2d.z < -pos2d.w || pos2d.z > pos2d.w || pos2d.x < -clip || pos2d.x > clip || pos2d.y < -clip || pos2d.y > clip) { + gl_Position = vec4(0.0, 0.0, 2.0, 1.0); + return; + } + + uvec4 cov = texelFetch(u_texture, ivec2(((uint(index) & 0x3ffu) << 1) | 1u, uint(index) >> 10), 0); + vec2 u1 = unpackHalf2x16(cov.x), u2 = unpackHalf2x16(cov.y), u3 = unpackHalf2x16(cov.z); + mat3 Vrk = mat3(u1.x, u1.y, u2.x, u1.y, u2.y, u3.x, u2.x, u3.x, u3.y); + + mat3 J = mat3( + focal.x / cam.z, 0., -(focal.x * cam.x) / (cam.z * cam.z), + 0., -focal.y / cam.z, (focal.y * cam.y) / (cam.z * cam.z), + 0., 0., 0. + ); + + mat3 T = transpose(mat3(viewTransform)) * J; + mat3 cov2d = transpose(T) * Vrk * T; + + //ref: https://github.com/graphdeco-inria/diff-gaussian-rasterization/blob/main/cuda_rasterizer/forward.cu#L110-L111 + cov2d[0][0] += 0.3; + cov2d[1][1] += 0.3; + + float mid = (cov2d[0][0] + cov2d[1][1]) / 2.0; + float radius = length(vec2((cov2d[0][0] - cov2d[1][1]) / 2.0, cov2d[0][1])); + float lambda1 = mid + radius, lambda2 = mid - radius; + + if (lambda2 < 0.0) return; + vec2 diagonalVector = normalize(vec2(cov2d[0][1], lambda1 - cov2d[0][0])); + vec2 majorAxis = min(sqrt(2.0 * lambda1), 1024.0) * diagonalVector; + vec2 minorAxis = min(sqrt(2.0 * lambda2), 1024.0) * vec2(diagonalVector.y, -diagonalVector.x); + + uint colorTransformIndex = texelFetch(u_colorTransformIndices, ivec2(uint(index) & 0x3ffu, uint(index) >> 10), 0).x; + mat4 colorTransform = mat4( + texelFetch(u_colorTransforms, ivec2(0, colorTransformIndex), 0), + texelFetch(u_colorTransforms, ivec2(1, colorTransformIndex), 0), + texelFetch(u_colorTransforms, ivec2(2, colorTransformIndex), 0), + texelFetch(u_colorTransforms, ivec2(3, colorTransformIndex), 0) + ); + + vec4 color = vec4((cov.w) & 0xffu, (cov.w >> 8) & 0xffu, (cov.w >> 16) & 0xffu, (cov.w >> 24) & 0xffu) / 255.0; + vColor = colorTransform * color; + + vPosition = position; + vSize = length(majorAxis); + vSelected = selected; + + float scalingFactor = 1.0; + + if (useDepthFade) { + float depthNorm = (pos2d.z / pos2d.w + 1.0) / 2.0; + float near = 0.1; float far = 100.0; + float normalizedDepth = (2.0 * near) / (far + near - depthNorm * (far - near)); + float start = max(normalizedDepth - 0.1, 0.0); + float end = min(normalizedDepth + 0.1, 1.0); + scalingFactor = clamp((depthFade - start) / (end - start), 0.0, 1.0); + } + + vec2 vCenter = vec2(pos2d) / pos2d.w; + gl_Position = vec4( + vCenter + + position.x * majorAxis * scalingFactor / viewport + + position.y * minorAxis * scalingFactor / viewport, 0.0, 1.0); +} +` + ); + var pt = ( + /* glsl */ + `#version 300 es +precision highp float; + +uniform float outlineThickness; +uniform vec4 outlineColor; + +in vec4 vColor; +in vec2 vPosition; +in float vSize; +in float vSelected; + +out vec4 fragColor; + +void main () { + float A = -dot(vPosition, vPosition); + + if (A < -4.0) discard; + + if (vSelected < 0.5) { + float B = exp(A) * vColor.a; + fragColor = vec4(B * vColor.rgb, B); + return; + } + + float outlineThreshold = -4.0 + (outlineThickness / vSize); + + if (A < outlineThreshold) { + fragColor = outlineColor; + } + else { + float B = exp(A) * vColor.a; + fragColor = vec4(B * vColor.rgb, B); + } +} +` + ); + var Ct = class extends lt { + constructor(t, n) { + super(t, n), this._outlineThickness = 10, this._outlineColor = new dt(255, 165, 0, 255), this._renderData = null, this._depthIndex = new Uint32Array(), this._splatTexture = null, this._worker = null; + const i = t.canvas, e = t.gl; + let A, o, s, r, Q, I, d, a, U, F, g, B, C, c, p, u, S, W, Z; + this._resize = () => { + this._camera && (this._camera.data.setSize(i.width, i.height), this._camera.update(), A = e.getUniformLocation(this.program, "projection"), e.uniformMatrix4fv(A, false, this._camera.data.projectionMatrix.buffer), o = e.getUniformLocation(this.program, "viewport"), e.uniform2fv(o, new Float32Array([i.width, i.height]))); + }; + const k = () => { + this._worker = Vt(), this._worker.onmessage = (V) => { + if (V.data.depthIndex) { + const { depthIndex: w } = V.data; + this._depthIndex = w, e.bindBuffer(e.ARRAY_BUFFER, Z), e.bufferData(e.ARRAY_BUFFER, w, e.STATIC_DRAW); + } + }; + }; + this._initialize = () => { + if (!this._scene || !this._camera) { + console.error("Cannot render without scene and camera"); + return; + } + this._resize(), this._scene.addEventListener("objectAdded", f), this._scene.addEventListener("objectRemoved", H); + for (const V of this._scene.objects) + V instanceof X && V.addEventListener("objectChanged", L); + this._renderData = new Ut(this._scene), s = e.getUniformLocation(this.program, "focal"), e.uniform2fv(s, new Float32Array([this._camera.data.fx, this._camera.data.fy])), r = e.getUniformLocation(this.program, "view"), e.uniformMatrix4fv(r, false, this._camera.data.viewMatrix.buffer), F = e.getUniformLocation(this.program, "outlineThickness"), e.uniform1f(F, this.outlineThickness), g = e.getUniformLocation(this.program, "outlineColor"), e.uniform4fv(g, new Float32Array(this.outlineColor.flatNorm())), this._splatTexture = e.createTexture(), Q = e.getUniformLocation(this.program, "u_texture"), e.uniform1i(Q, 0), c = e.createTexture(), I = e.getUniformLocation(this.program, "u_transforms"), e.uniform1i(I, 1), p = e.createTexture(), d = e.getUniformLocation(this.program, "u_transformIndices"), e.uniform1i(d, 2), u = e.createTexture(), a = e.getUniformLocation(this.program, "u_colorTransforms"), e.uniform1i(a, 3), S = e.createTexture(), U = e.getUniformLocation( + this.program, + "u_colorTransformIndices" + ), e.uniform1i(U, 4), W = e.createBuffer(), e.bindBuffer(e.ARRAY_BUFFER, W), e.bufferData(e.ARRAY_BUFFER, new Float32Array([-2, -2, 2, -2, 2, 2, -2, 2]), e.STATIC_DRAW), B = e.getAttribLocation(this.program, "position"), e.enableVertexAttribArray(B), e.vertexAttribPointer(B, 2, e.FLOAT, false, 0, 0), Z = e.createBuffer(), C = e.getAttribLocation(this.program, "index"), e.enableVertexAttribArray(C), e.bindBuffer(e.ARRAY_BUFFER, Z), k(); + }; + const f = (V) => { + const w = V; + w.object instanceof X && w.object.addEventListener("objectChanged", L), M(); + }, H = (V) => { + const w = V; + w.object instanceof X && w.object.removeEventListener("objectChanged", L), M(); + }, L = (V) => { + const w = V; + w.object instanceof X && this._renderData && this._renderData.markDirty(w.object); + }, M = () => { + this._renderData?.dispose(), this._renderData = new Ut(this._scene), this._worker?.terminate(), k(); + }; + this._render = () => { + if (!this._scene || !this._camera || !this.renderData) { + console.error("Cannot render without scene and camera"); + return; + } + if (this.renderData.needsRebuild && this.renderData.rebuild(), this.renderData.dataChanged || this.renderData.transformsChanged || this.renderData.colorTransformsChanged) { + this.renderData.dataChanged && (e.activeTexture(e.TEXTURE0), e.bindTexture(e.TEXTURE_2D, this.splatTexture), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_WRAP_S, e.CLAMP_TO_EDGE), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_WRAP_T, e.CLAMP_TO_EDGE), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_MIN_FILTER, e.NEAREST), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_MAG_FILTER, e.NEAREST), e.texImage2D( + e.TEXTURE_2D, + 0, + e.RGBA32UI, + this.renderData.width, + this.renderData.height, + 0, + e.RGBA_INTEGER, + e.UNSIGNED_INT, + this.renderData.data + )), this.renderData.transformsChanged && (e.activeTexture(e.TEXTURE1), e.bindTexture(e.TEXTURE_2D, c), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_WRAP_S, e.CLAMP_TO_EDGE), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_WRAP_T, e.CLAMP_TO_EDGE), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_MIN_FILTER, e.NEAREST), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_MAG_FILTER, e.NEAREST), e.texImage2D( + e.TEXTURE_2D, + 0, + e.RGBA32F, + this.renderData.transformsWidth, + this.renderData.transformsHeight, + 0, + e.RGBA, + e.FLOAT, + this.renderData.transforms + ), e.activeTexture(e.TEXTURE2), e.bindTexture(e.TEXTURE_2D, p), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_WRAP_S, e.CLAMP_TO_EDGE), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_WRAP_T, e.CLAMP_TO_EDGE), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_MIN_FILTER, e.NEAREST), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_MAG_FILTER, e.NEAREST), e.texImage2D( + e.TEXTURE_2D, + 0, + e.R32UI, + this.renderData.transformIndicesWidth, + this.renderData.transformIndicesHeight, + 0, + e.RED_INTEGER, + e.UNSIGNED_INT, + this.renderData.transformIndices + )), this.renderData.colorTransformsChanged && (e.activeTexture(e.TEXTURE3), e.bindTexture(e.TEXTURE_2D, u), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_WRAP_S, e.CLAMP_TO_EDGE), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_WRAP_T, e.CLAMP_TO_EDGE), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_MIN_FILTER, e.NEAREST), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_MAG_FILTER, e.NEAREST), e.texImage2D( + e.TEXTURE_2D, + 0, + e.RGBA32F, + this.renderData.colorTransformsWidth, + this.renderData.colorTransformsHeight, + 0, + e.RGBA, + e.FLOAT, + this.renderData.colorTransforms + ), e.activeTexture(e.TEXTURE4), e.bindTexture(e.TEXTURE_2D, S), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_WRAP_S, e.CLAMP_TO_EDGE), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_WRAP_T, e.CLAMP_TO_EDGE), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_MIN_FILTER, e.NEAREST), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_MAG_FILTER, e.NEAREST), e.texImage2D( + e.TEXTURE_2D, + 0, + e.R32UI, + this.renderData.colorTransformIndicesWidth, + this.renderData.colorTransformIndicesHeight, + 0, + e.RED_INTEGER, + e.UNSIGNED_INT, + this.renderData.colorTransformIndices + )); + const V = new Float32Array(this.renderData.positions.slice().buffer), w = new Float32Array(this.renderData.transforms.slice().buffer), P = new Uint32Array(this.renderData.transformIndices.slice().buffer); + this._worker?.postMessage( + { + sortData: { + positions: V, + transforms: w, + transformIndices: P, + vertexCount: this.renderData.vertexCount + } + }, + [V.buffer, w.buffer, P.buffer] + ), this.renderData.dataChanged = false, this.renderData.transformsChanged = false, this.renderData.colorTransformsChanged = false; + } + this._camera.update(), this._worker?.postMessage({ viewProj: this._camera.data.viewProj.buffer }), e.viewport(0, 0, i.width, i.height), e.clearColor(0, 0, 0, 0), e.clear(e.COLOR_BUFFER_BIT), e.disable(e.DEPTH_TEST), e.enable(e.BLEND), e.blendFuncSeparate(e.ONE_MINUS_DST_ALPHA, e.ONE, e.ONE_MINUS_DST_ALPHA, e.ONE), e.blendEquationSeparate(e.FUNC_ADD, e.FUNC_ADD), e.uniformMatrix4fv(A, false, this._camera.data.projectionMatrix.buffer), e.uniformMatrix4fv(r, false, this._camera.data.viewMatrix.buffer), e.bindBuffer(e.ARRAY_BUFFER, W), e.vertexAttribPointer(B, 2, e.FLOAT, false, 0, 0), e.bindBuffer(e.ARRAY_BUFFER, Z), e.bufferData(e.ARRAY_BUFFER, this.depthIndex, e.STATIC_DRAW), e.vertexAttribIPointer(C, 1, e.INT, 0, 0), e.vertexAttribDivisor(C, 1), e.drawArraysInstanced(e.TRIANGLE_FAN, 0, 4, this.depthIndex.length); + }, this._dispose = () => { + if (!this._scene || !this._camera || !this.renderData) { + console.error("Cannot dispose without scene and camera"); + return; + } + this._scene.removeEventListener("objectAdded", f), this._scene.removeEventListener("objectRemoved", H); + for (const V of this._scene.objects) + V instanceof X && V.removeEventListener("objectChanged", L); + this._worker?.terminate(), this.renderData.dispose(), e.deleteTexture(this.splatTexture), e.deleteTexture(c), e.deleteTexture(p), e.deleteBuffer(Z), e.deleteBuffer(W); + }, this._setOutlineThickness = (V) => { + this._outlineThickness = V, this._initialized && e.uniform1f(F, V); + }, this._setOutlineColor = (V) => { + this._outlineColor = V, this._initialized && e.uniform4fv(g, new Float32Array(V.flatNorm())); + }; + } + get renderData() { + return this._renderData; + } + get depthIndex() { + return this._depthIndex; + } + get splatTexture() { + return this._splatTexture; + } + get outlineThickness() { + return this._outlineThickness; + } + set outlineThickness(t) { + this._setOutlineThickness(t); + } + get outlineColor() { + return this._outlineColor; + } + set outlineColor(t) { + this._setOutlineColor(t); + } + get worker() { + return this._worker; + } + _getVertexSource() { + return Zt; + } + _getFragmentSource() { + return pt; + } + }; + var Nt = class { + constructor(t = 1) { + let n = 0, i = false, e, A, o, s; + this.initialize = (r) => { + if (!(r instanceof Ct)) + throw new Error("FadeInPass requires a RenderProgram"); + n = r.started ? 1 : 0, i = true, e = r, A = r.renderer.gl, o = A.getUniformLocation(e.program, "useDepthFade"), A.uniform1i(o, 1), s = A.getUniformLocation(e.program, "depthFade"), A.uniform1f(s, n); + }, this.render = () => { + !i || e.renderData?.updating || (A.useProgram(e.program), n = Math.min(n + t * 0.01, 1), n >= 1 && (i = false, A.uniform1i(o, 0)), A.uniform1f(s, n)); + }; + } + dispose() { + } + }; + var Mt = class { + constructor(t = null, n = null) { + this._backgroundColor = new dt(); + const i = t || document.createElement("canvas"); + t || (i.style.display = "block", i.style.boxSizing = "border-box", i.style.width = "100%", i.style.height = "100%", i.style.margin = "0", i.style.padding = "0", document.body.appendChild(i)), i.style.background = this._backgroundColor.toHexString(), this._canvas = i, this._gl = i.getContext("webgl2", { antialias: false, preserveDrawingBuffer: true }); + const e = n || []; + n || e.push(new Nt()), this._renderProgram = new Ct(this, e); + const A = [this._renderProgram]; + this.resize = () => { + const o = i.clientWidth, s = i.clientHeight; + (i.width !== o || i.height !== s) && this.setSize(o, s); + }, this.setSize = (o, s) => { + i.width = o, i.height = s, this._gl.viewport(0, 0, i.width, i.height); + for (const r of A) + r.resize(); + }, this.render = (o, s) => { + for (const r of A) + r.render(o, s); + }, this.dispose = () => { + for (const o of A) + o.dispose(); + }, this.addProgram = (o) => { + A.push(o); + }, this.removeProgram = (o) => { + const s = A.indexOf(o); + if (s < 0) + throw new Error("Program not found"); + A.splice(s, 1); + }, this.resize(); + } + get canvas() { + return this._canvas; + } + get gl() { + return this._gl; + } + get renderProgram() { + return this._renderProgram; + } + get backgroundColor() { + return this._backgroundColor; + } + set backgroundColor(t) { + this._backgroundColor = t, this._canvas.style.background = t.toHexString(); + } + }; + var Lt = class { + constructor(t, n, i = 0.5, e = 0.5, A = 5, o = true, s = new R()) { + this.minAngle = -90, this.maxAngle = 90, this.minZoom = 0.1, this.maxZoom = 30, this.orbitSpeed = 1, this.panSpeed = 1, this.zoomSpeed = 1, this.dampening = 0.12, this.setCameraTarget = () => { + }; + let r = s.clone(), Q = r.clone(), I = i, d = e, a = A, U = false, F = false, g = 0, B = 0, C = 0; + const c = {}; + let p = false; + const u = () => { + if (p) return; + const l = t.rotation.toEuler(); + I = -l.y, d = -l.x; + const J = t.position.x - a * Math.sin(I) * Math.cos(d), D = t.position.y + a * Math.sin(d), b = t.position.z + a * Math.cos(I) * Math.cos(d); + Q = new R(J, D, b); + }; + t.addEventListener("objectChanged", u), this.setCameraTarget = (l) => { + const J = l.x - t.position.x, D = l.y - t.position.y, b = l.z - t.position.z; + a = Math.sqrt(J * J + D * D + b * b), d = Math.atan2(D, Math.sqrt(J * J + b * b)), I = -Math.atan2(J, b), Q = new R(l.x, l.y, l.z), i = I, e = d, A = a, r = Q.clone(); + }; + const S = () => 0.1 + 0.9 * (a - this.minZoom) / (this.maxZoom - this.minZoom), W = (l) => { + c[l.code] = true, l.code === "ArrowUp" && (c.KeyW = true), l.code === "ArrowDown" && (c.KeyS = true), l.code === "ArrowLeft" && (c.KeyA = true), l.code === "ArrowRight" && (c.KeyD = true); + }, Z = (l) => { + c[l.code] = false, l.code === "ArrowUp" && (c.KeyW = false), l.code === "ArrowDown" && (c.KeyS = false), l.code === "ArrowLeft" && (c.KeyA = false), l.code === "ArrowRight" && (c.KeyD = false); + }, k = (l) => { + T(l), U = true, F = l.button === 2, B = l.clientX, C = l.clientY, window.addEventListener("mouseup", f); + }, f = (l) => { + T(l), U = false, F = false, window.removeEventListener("mouseup", f); + }, H = (l) => { + if (T(l), !U || !t) return; + const J = l.clientX - B, D = l.clientY - C; + if (F) { + const b = S(), j = -J * this.panSpeed * 0.01 * b, q = -D * this.panSpeed * 0.01 * b, G = _.RotationFromQuaternion(t.rotation).buffer, h = new R(G[0], G[3], G[6]), m = new R(G[1], G[4], G[7]); + Q = Q.add(h.multiply(j)), Q = Q.add(m.multiply(q)); + } else + I -= J * this.orbitSpeed * 3e-3, d += D * this.orbitSpeed * 3e-3, d = Math.min( + Math.max(d, this.minAngle * Math.PI / 180), + this.maxAngle * Math.PI / 180 + ); + B = l.clientX, C = l.clientY; + }, L = (l) => { + T(l); + const J = S(); + a += l.deltaY * this.zoomSpeed * 0.025 * J, a = Math.min(Math.max(a, this.minZoom), this.maxZoom); + }, M = (l) => { + if (T(l), l.touches.length === 1) + U = true, F = false, B = l.touches[0].clientX, C = l.touches[0].clientY, g = 0; + else if (l.touches.length === 2) { + U = true, F = true, B = (l.touches[0].clientX + l.touches[1].clientX) / 2, C = (l.touches[0].clientY + l.touches[1].clientY) / 2; + const J = l.touches[0].clientX - l.touches[1].clientX, D = l.touches[0].clientY - l.touches[1].clientY; + g = Math.sqrt(J * J + D * D); + } + }, V = (l) => { + T(l), U = false, F = false; + }, w = (l) => { + if (T(l), !(!U || !t)) + if (F) { + const J = S(), D = l.touches[0].clientX - l.touches[1].clientX, b = l.touches[0].clientY - l.touches[1].clientY, j = Math.sqrt(D * D + b * b), q = g - j; + a += q * this.zoomSpeed * 0.1 * J, a = Math.min(Math.max(a, this.minZoom), this.maxZoom), g = j; + const G = (l.touches[0].clientX + l.touches[1].clientX) / 2, h = (l.touches[0].clientY + l.touches[1].clientY) / 2, m = G - B, x = h - C, N = _.RotationFromQuaternion(t.rotation).buffer, v = new R(N[0], N[3], N[6]), O = new R(N[1], N[4], N[7]); + Q = Q.add(v.multiply(-m * this.panSpeed * 0.025 * J)), Q = Q.add(O.multiply(-x * this.panSpeed * 0.025 * J)), B = G, C = h; + } else { + const J = l.touches[0].clientX - B, D = l.touches[0].clientY - C; + I -= J * this.orbitSpeed * 3e-3, d += D * this.orbitSpeed * 3e-3, d = Math.min( + Math.max(d, this.minAngle * Math.PI / 180), + this.maxAngle * Math.PI / 180 + ), B = l.touches[0].clientX, C = l.touches[0].clientY; + } + }, P = (l, J, D) => (1 - D) * l + D * J; + this.update = () => { + p = true, i = P(i, I, this.dampening), e = P(e, d, this.dampening), A = P(A, a, this.dampening), r = r.lerp(Q, this.dampening); + const l = r.x + A * Math.sin(i) * Math.cos(e), J = r.y - A * Math.sin(e), D = r.z - A * Math.cos(i) * Math.cos(e); + t.position = new R(l, J, D); + const b = r.subtract(t.position).normalize(), j = Math.asin(-b.y), q = Math.atan2(b.x, b.z); + t.rotation = y.FromEuler(new R(j, q, 0)); + const G = 0.025, h = 0.01, m = _.RotationFromQuaternion(t.rotation).buffer, x = new R(-m[2], -m[5], -m[8]), N = new R(m[0], m[3], m[6]); + c.KeyS && (Q = Q.add(x.multiply(G))), c.KeyW && (Q = Q.subtract(x.multiply(G))), c.KeyA && (Q = Q.subtract(N.multiply(G))), c.KeyD && (Q = Q.add(N.multiply(G))), c.KeyE && (I += h), c.KeyQ && (I -= h), c.KeyR && (d += h), c.KeyF && (d -= h), p = false; + }; + const T = (l) => { + l.preventDefault(), l.stopPropagation(); + }; + this.dispose = () => { + n.removeEventListener("dragenter", T), n.removeEventListener("dragover", T), n.removeEventListener("dragleave", T), n.removeEventListener("contextmenu", T), n.removeEventListener("mousedown", k), n.removeEventListener("mousemove", H), n.removeEventListener("wheel", L), n.removeEventListener("touchstart", M), n.removeEventListener("touchend", V), n.removeEventListener("touchmove", w), o && (window.removeEventListener("keydown", W), window.removeEventListener("keyup", Z)); + }, o && (window.addEventListener("keydown", W), window.addEventListener("keyup", Z)), n.addEventListener("dragenter", T), n.addEventListener("dragover", T), n.addEventListener("dragleave", T), n.addEventListener("contextmenu", T), n.addEventListener("mousedown", k), n.addEventListener("mousemove", H), n.addEventListener("wheel", L), n.addEventListener("touchstart", M), n.addEventListener("touchend", V), n.addEventListener("touchmove", w), this.update(); + } + }; + var Gt = class { + constructor(t, n) { + this.moveSpeed = 1.5, this.lookSpeed = 0.7, this.dampening = 0.5; + const i = {}; + let e = t.rotation.toEuler().x, A = t.rotation.toEuler().y, o = t.position, s = false; + const r = () => { + n.requestPointerLock(); + }, Q = () => { + s = document.pointerLockElement === n, s ? n.addEventListener("mousemove", I) : n.removeEventListener("mousemove", I); + }, I = (F) => { + const g = F.movementX, B = F.movementY; + A += g * this.lookSpeed * 1e-3, e -= B * this.lookSpeed * 1e-3, e = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, e)); + }, d = (F) => { + i[F.code] = true, F.code === "ArrowUp" && (i.KeyW = true), F.code === "ArrowDown" && (i.KeyS = true), F.code === "ArrowLeft" && (i.KeyA = true), F.code === "ArrowRight" && (i.KeyD = true); + }, a = (F) => { + i[F.code] = false, F.code === "ArrowUp" && (i.KeyW = false), F.code === "ArrowDown" && (i.KeyS = false), F.code === "ArrowLeft" && (i.KeyA = false), F.code === "ArrowRight" && (i.KeyD = false), F.code === "Escape" && document.exitPointerLock(); + }; + this.update = () => { + const F = _.RotationFromQuaternion(t.rotation).buffer, g = new R(-F[2], -F[5], -F[8]), B = new R(F[0], F[3], F[6]); + let C = new R(0, 0, 0); + i.KeyS && (C = C.add(g)), i.KeyW && (C = C.subtract(g)), i.KeyA && (C = C.subtract(B)), i.KeyD && (C = C.add(B)), C = new R(C.x, 0, C.z), C.magnitude() > 0 && (C = C.normalize()), o = o.add(C.multiply(this.moveSpeed * 0.01)), t.position = t.position.add(o.subtract(t.position).multiply(this.dampening)), t.rotation = y.FromEuler(new R(e, A, 0)); + }; + const U = (F) => { + F.preventDefault(), F.stopPropagation(); + }; + this.dispose = () => { + n.removeEventListener("dragenter", U), n.removeEventListener("dragover", U), n.removeEventListener("dragleave", U), n.removeEventListener("contextmenu", U), n.removeEventListener("mousedown", r), document.removeEventListener("pointerlockchange", Q), window.removeEventListener("keydown", d), window.removeEventListener("keyup", a); + }, window.addEventListener("keydown", d), window.addEventListener("keyup", a), n.addEventListener("dragenter", U), n.addEventListener("dragover", U), n.addEventListener("dragleave", U), n.addEventListener("contextmenu", U), n.addEventListener("mousedown", r), document.addEventListener("pointerlockchange", Q), this.update(); + } + }; + var vt = class { + constructor(t, n) { + this.normal = t, this.point = n; + } + intersect(t, n) { + const i = this.normal.dot(n); + if (Math.abs(i) < 1e-4) + return null; + const e = this.normal.dot(this.point.subtract(t)) / i; + return e < 0 ? null : t.add(n.multiply(e)); + } + }; + var _t = class { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + initialize(t) { + } + render() { + } + dispose() { + } + }; + var Wt = ( + /* glsl */ + `#version 300 es +precision highp float; +precision highp int; + +uniform highp usampler2D u_texture; +uniform mat4 projection, view; +uniform vec2 focal; +uniform vec2 viewport; +uniform float time; + +in vec2 position; +in int index; + +out vec4 vColor; +out vec2 vPosition; + +void main () { + gl_Position = vec4(0.0, 0.0, 2.0, 1.0); + + uvec4 motion1 = texelFetch(u_texture, ivec2(((uint(index) & 0x3ffu) << 2) | 3u, uint(index) >> 10), 0); + vec2 trbf = unpackHalf2x16(motion1.w); + float dt = time - trbf.x; + + float topacity = exp(-1.0 * pow(dt / trbf.y, 2.0)); + if(topacity < 0.02) return; + + uvec4 motion0 = texelFetch(u_texture, ivec2(((uint(index) & 0x3ffu) << 2) | 2u, uint(index) >> 10), 0); + uvec4 static0 = texelFetch(u_texture, ivec2(((uint(index) & 0x3ffu) << 2), uint(index) >> 10), 0); + + vec2 m0 = unpackHalf2x16(motion0.x), m1 = unpackHalf2x16(motion0.y), m2 = unpackHalf2x16(motion0.z), + m3 = unpackHalf2x16(motion0.w), m4 = unpackHalf2x16(motion1.x); + + vec4 trot = vec4(unpackHalf2x16(motion1.y).xy, unpackHalf2x16(motion1.z).xy) * dt; + vec3 tpos = (vec3(m0.xy, m1.x) * dt + vec3(m1.y, m2.xy) * dt*dt + vec3(m3.xy, m4.x) * dt*dt*dt); + + vec4 cam = view * vec4(uintBitsToFloat(static0.xyz) + tpos, 1); + vec4 pos = projection * cam; + + float clip = 1.2 * pos.w; + if (pos.z < -clip || pos.x < -clip || pos.x > clip || pos.y < -clip || pos.y > clip) return; + uvec4 static1 = texelFetch(u_texture, ivec2(((uint(index) & 0x3ffu) << 2) | 1u, uint(index) >> 10), 0); + + vec4 rot = vec4(unpackHalf2x16(static0.w).xy, unpackHalf2x16(static1.x).xy) + trot; + vec3 scale = vec3(unpackHalf2x16(static1.y).xy, unpackHalf2x16(static1.z).x); + rot /= sqrt(dot(rot, rot)); + + mat3 S = mat3(scale.x, 0.0, 0.0, 0.0, scale.y, 0.0, 0.0, 0.0, scale.z); + mat3 R = mat3( + 1.0 - 2.0 * (rot.z * rot.z + rot.w * rot.w), 2.0 * (rot.y * rot.z - rot.x * rot.w), 2.0 * (rot.y * rot.w + rot.x * rot.z), + 2.0 * (rot.y * rot.z + rot.x * rot.w), 1.0 - 2.0 * (rot.y * rot.y + rot.w * rot.w), 2.0 * (rot.z * rot.w - rot.x * rot.y), + 2.0 * (rot.y * rot.w - rot.x * rot.z), 2.0 * (rot.z * rot.w + rot.x * rot.y), 1.0 - 2.0 * (rot.y * rot.y + rot.z * rot.z)); + mat3 M = S * R; + mat3 Vrk = 4.0 * transpose(M) * M; + mat3 J = mat3( + focal.x / cam.z, 0., -(focal.x * cam.x) / (cam.z * cam.z), + 0., -focal.y / cam.z, (focal.y * cam.y) / (cam.z * cam.z), + 0., 0., 0. + ); + + mat3 T = transpose(mat3(view)) * J; + mat3 cov2d = transpose(T) * Vrk * T; + + float mid = (cov2d[0][0] + cov2d[1][1]) / 2.0; + float radius = length(vec2((cov2d[0][0] - cov2d[1][1]) / 2.0, cov2d[0][1])); + float lambda1 = mid + radius, lambda2 = mid - radius; + + if(lambda2 < 0.0) return; + vec2 diagonalVector = normalize(vec2(cov2d[0][1], lambda1 - cov2d[0][0])); + vec2 majorAxis = min(sqrt(2.0 * lambda1), 1024.0) * diagonalVector; + vec2 minorAxis = min(sqrt(2.0 * lambda2), 1024.0) * vec2(diagonalVector.y, -diagonalVector.x); + + uint rgba = static1.w; + vColor = + clamp(pos.z/pos.w+1.0, 0.0, 1.0) * + vec4(1.0, 1.0, 1.0, topacity) * + vec4( + (rgba) & 0xffu, + (rgba >> 8) & 0xffu, + (rgba >> 16) & 0xffu, + (rgba >> 24) & 0xffu) / 255.0; + + vec2 vCenter = vec2(pos) / pos.w; + gl_Position = vec4( + vCenter + + position.x * majorAxis / viewport + + position.y * minorAxis / viewport, 0.0, 1.0); + + vPosition = position; +} +` + ); + var Dt = ( + /* glsl */ + `#version 300 es +precision highp float; + +in vec4 vColor; +in vec2 vPosition; + +out vec4 fragColor; + +void main () { + float A = -dot(vPosition, vPosition); + if (A < -4.0) discard; + float B = exp(A) * vColor.a; + fragColor = vec4(B * vColor.rgb, B); +} +` + ); + var Yt = class extends lt { + constructor(t, n = []) { + super(t, n), this._renderData = null, this._depthIndex = new Uint32Array(), this._splatTexture = null; + const i = t.canvas, e = t.gl; + let A, o, s, r, Q, I, d, a, U, F, g; + this._resize = () => { + this._camera && (this._camera.data.setSize(i.width, i.height), this._camera.update(), o = e.getUniformLocation(this.program, "projection"), e.uniformMatrix4fv(o, false, this._camera.data.projectionMatrix.buffer), s = e.getUniformLocation(this.program, "viewport"), e.uniform2fv(s, new Float32Array([i.width, i.height]))); + }; + const B = () => { + if (t.renderProgram.worker === null) { + console.error("Render program is not initialized. Cannot render without worker"); + return; + } + A = t.renderProgram.worker, A.onmessage = (u) => { + if (u.data.depthIndex) { + const { depthIndex: S } = u.data; + this._depthIndex = S, e.bindBuffer(e.ARRAY_BUFFER, g), e.bufferData(e.ARRAY_BUFFER, S, e.STATIC_DRAW); + } + }; + }; + this._initialize = () => { + if (!this._scene || !this._camera) { + console.error("Cannot render without scene and camera"); + return; + } + this._resize(), this._scene.addEventListener("objectAdded", C), this._scene.addEventListener("objectRemoved", c); + for (const Z of this._scene.objects) + Z instanceof tt && (this._renderData === null ? (this._renderData = Z.data, Z.addEventListener("objectChanged", p)) : console.warn("Multiple Splatv objects are not currently supported")); + if (this._renderData === null) { + console.error("Cannot render without Splatv object"); + return; + } + r = e.getUniformLocation(this.program, "focal"), e.uniform2fv(r, new Float32Array([this._camera.data.fx, this._camera.data.fy])), Q = e.getUniformLocation(this.program, "view"), e.uniformMatrix4fv(Q, false, this._camera.data.viewMatrix.buffer), this._splatTexture = e.createTexture(), I = e.getUniformLocation(this.program, "u_texture"), e.uniform1i(I, 0), d = e.getUniformLocation(this.program, "time"), e.uniform1f(d, Math.sin(Date.now() / 1e3) / 2 + 1 / 2), F = e.createBuffer(), e.bindBuffer(e.ARRAY_BUFFER, F), e.bufferData(e.ARRAY_BUFFER, new Float32Array([-2, -2, 2, -2, 2, 2, -2, 2]), e.STATIC_DRAW), a = e.getAttribLocation(this.program, "position"), e.enableVertexAttribArray(a), e.vertexAttribPointer(a, 2, e.FLOAT, false, 0, 0), g = e.createBuffer(), U = e.getAttribLocation(this.program, "index"), e.enableVertexAttribArray(U), e.bindBuffer(e.ARRAY_BUFFER, g), B(), e.activeTexture(e.TEXTURE0), e.bindTexture(e.TEXTURE_2D, this._splatTexture), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_WRAP_S, e.CLAMP_TO_EDGE), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_WRAP_T, e.CLAMP_TO_EDGE), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_MIN_FILTER, e.NEAREST), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_MAG_FILTER, e.NEAREST), e.texImage2D( + e.TEXTURE_2D, + 0, + e.RGBA32UI, + this._renderData.width, + this._renderData.height, + 0, + e.RGBA_INTEGER, + e.UNSIGNED_INT, + this._renderData.data + ); + const u = this._renderData.positions, S = new Float32Array(new K().buffer), W = new Uint32Array(this._renderData.vertexCount); + W.fill(0), A.postMessage( + { + sortData: { + positions: u, + transforms: S, + transformIndices: W, + vertexCount: this._renderData.vertexCount + } + }, + [u.buffer, S.buffer, W.buffer] + ); + }; + const C = (u) => { + const S = u; + S.object instanceof tt && (this._renderData === null ? (this._renderData = S.object.data, S.object.addEventListener("objectChanged", p)) : console.warn("Splatv not supported by default RenderProgram. Use VideoRenderProgram instead.")), this.dispose(); + }, c = (u) => { + const S = u; + S.object instanceof tt && this._renderData === S.object.data && (this._renderData = null, S.object.removeEventListener("objectChanged", p)), this.dispose(); + }, p = (u) => { + const S = u; + S.object instanceof tt && this._renderData === S.object.data && this.dispose(); + }; + this._render = () => { + if (!this._scene || !this._camera) { + console.error("Cannot render without scene and camera"); + return; + } + if (!this._renderData) { + console.warn("Cannot render without Splatv object"); + return; + } + this._camera.update(), A.postMessage({ viewProj: this._camera.data.viewProj.buffer }), e.viewport(0, 0, i.width, i.height), e.clearColor(0, 0, 0, 0), e.clear(e.COLOR_BUFFER_BIT), e.disable(e.DEPTH_TEST), e.enable(e.BLEND), e.blendFuncSeparate(e.ONE_MINUS_DST_ALPHA, e.ONE, e.ONE_MINUS_DST_ALPHA, e.ONE), e.blendEquationSeparate(e.FUNC_ADD, e.FUNC_ADD), e.uniformMatrix4fv(o, false, this._camera.data.projectionMatrix.buffer), e.uniformMatrix4fv(Q, false, this._camera.data.viewMatrix.buffer), e.uniform1f(d, Math.sin(Date.now() / 1e3) / 2 + 1 / 2), e.bindBuffer(e.ARRAY_BUFFER, F), e.vertexAttribPointer(a, 2, e.FLOAT, false, 0, 0), e.bindBuffer(e.ARRAY_BUFFER, g), e.bufferData(e.ARRAY_BUFFER, this._depthIndex, e.STATIC_DRAW), e.vertexAttribIPointer(U, 1, e.INT, 0, 0), e.vertexAttribDivisor(U, 1), e.drawArraysInstanced(e.TRIANGLE_FAN, 0, 4, this._renderData.vertexCount); + }, this._dispose = () => { + if (!this._scene || !this._camera) { + console.error("Cannot dispose without scene and camera"); + return; + } + this._scene.removeEventListener("objectAdded", C), this._scene.removeEventListener("objectRemoved", c); + for (const u of this._scene.objects) + u instanceof tt && this._renderData === u.data && (this._renderData = null, u.removeEventListener("objectChanged", p)); + A?.terminate(), e.deleteTexture(this._splatTexture), e.deleteBuffer(g), e.deleteBuffer(F); + }; + } + get renderData() { + return this._renderData; + } + _getVertexSource() { + return Wt; + } + _getFragmentSource() { + return Dt; + } + }; + var it = class _it { + constructor(t, n, i) { + this.bounds = t, this.boxes = n, this.left = null, this.right = null, this.pointIndices = [], i.length > 1 ? this.split(t, n, i) : i.length > 0 && (this.pointIndices = i); + } + split(t, n, i) { + const e = t.size().maxComponent(); + i.sort((r, Q) => n[r].center().getComponent(e) - n[Q].center().getComponent(e)); + const A = Math.floor(i.length / 2), o = i.slice(0, A), s = i.slice(A); + this.left = new _it(t, n, o), this.right = new _it(t, n, s); + } + queryRange(t) { + return this.bounds.intersects(t) ? this.left !== null && this.right !== null ? this.left.queryRange(t).concat(this.right.queryRange(t)) : this.pointIndices.filter((n) => t.intersects(this.boxes[n])) : []; + } + }; + var yt = class { + constructor(t, n) { + const i = n.map((e, A) => A); + this.root = new it(t, n, i); + } + queryRange(t) { + return this.root.queryRange(t); + } + }; + var Kt = class { + constructor(t, n = 100, i = 1) { + let e = 0, A = null, o = []; + const s = () => { + if (t.renderData === null) { + console.error("IntersectionTester cannot be called before renderProgram has been initialized"); + return; + } + o = []; + const r = t.renderData, Q = new Array(r.offsets.size); + let I = 0; + const d = new nt( + new R(1 / 0, 1 / 0, 1 / 0), + new R(-1 / 0, -1 / 0, -1 / 0) + ); + for (const a of r.offsets.keys()) { + const U = a.bounds; + Q[I++] = U, d.expand(U.min), d.expand(U.max), o.push(a); + } + d.permute(), A = new yt(d, Q), e = r.vertexCount; + }; + this.testPoint = (r, Q) => { + if (t.renderData === null || t.camera === null) + return console.error("IntersectionTester cannot be called before renderProgram has been initialized"), null; + if (s(), A === null) + return console.error("Failed to build octree for IntersectionTester"), null; + const I = t.renderData, d = t.camera; + e !== I.vertexCount && console.warn("IntersectionTester has not been rebuilt since the last render"); + const a = d.screenPointToRay(r, Q); + for (let U = 0; U < n; U += i) { + const F = d.position.add(a.multiply(U)), g = new R( + F.x - i / 2, + F.y - i / 2, + F.z - i / 2 + ), B = new R( + F.x + i / 2, + F.y + i / 2, + F.z + i / 2 + ), C = new nt(g, B), c = A.queryRange(C); + if (c.length > 0) + return o[c[0]]; + } + return null; + }; + } + }; + return __toCommonJS(gsplat_entry_exports); +})(); diff --git a/web_src/load_mesh_batch_path.js b/javascript/js/load_mesh_batch_path.js similarity index 100% rename from web_src/load_mesh_batch_path.js rename to javascript/js/load_mesh_batch_path.js diff --git a/web_src/load_mesh_upload.js b/javascript/js/load_mesh_upload.js similarity index 100% rename from web_src/load_mesh_upload.js rename to javascript/js/load_mesh_upload.js diff --git a/javascript/js/mesh_preview.js b/javascript/js/mesh_preview.js new file mode 100644 index 00000000..12859e66 --- /dev/null +++ b/javascript/js/mesh_preview.js @@ -0,0 +1,130 @@ +/** + * ComfyUI GeomPack - 3D Mesh Preview Widget + * Minimal implementation based on ComfyUI-3D-Pack pattern + */ + +import { app } from "../../../scripts/app.js"; + +// Auto-detect extension folder name (handles ComfyUI-GeometryPack or comfyui-geometrypack) +const EXTENSION_FOLDER = (() => { + const url = import.meta.url; + const match = url.match(/\/extensions\/([^/]+)\//); + return match ? match[1] : "ComfyUI-GeometryPack"; +})(); + +console.log("[GeomPack] Loading mesh preview extension..."); + +app.registerExtension({ + name: "geompack.meshpreview", + + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name === "GeomPackPreviewMesh") { + console.log("[GeomPack] Registering Preview Mesh node"); + + const onNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function() { + const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined; + + console.log("[GeomPack DEBUG] this.widgets before:", this.widgets); + console.log("[GeomPack DEBUG] nodeData:", nodeData); + console.log("[GeomPack] Node created, adding widget"); + + // Create iframe for 3D viewer + const iframe = document.createElement("iframe"); + iframe.style.width = "100%"; + iframe.style.height = "100%"; + iframe.style.border = "none"; + iframe.style.backgroundColor = "#2a2a2a"; + iframe.style.aspectRatio = "1"; + + // Point to our HTML viewer (with cache buster) + iframe.src = `/extensions/${EXTENSION_FOLDER}/viewer.html?v=` + Date.now(); + + // Add widget with required options + console.log("[GeomPack DEBUG] About to call addDOMWidget"); + console.log("[GeomPack DEBUG] typeof this.addDOMWidget:", typeof this.addDOMWidget); + + const widget = this.addDOMWidget("preview", "MESH_PREVIEW", iframe, { + getValue() { return ""; }, + setValue(v) { } + }); + + console.log("[GeomPack DEBUG] Widget created:", widget); + console.log("[GeomPack DEBUG] Widget properties:", Object.keys(widget || {})); + console.log("[GeomPack DEBUG] Widget.id:", widget?.id); + console.log("[GeomPack DEBUG] this.widgets after addDOMWidget:", this.widgets); + + // Set widget size - computeSize returns [width, height] + widget.computeSize = function(width) { + console.log("[GeomPack DEBUG] computeSize called with width:", width); + const size = [width || 512, width || 512]; + console.log("[GeomPack DEBUG] computeSize returning:", size); + return size; + }; + + // Also try setting element size directly + widget.element = iframe; + + console.log("[GeomPack DEBUG] Widget computeSize set"); + console.log("[GeomPack DEBUG] Iframe dimensions:", iframe.style.width, iframe.style.height); + + // Store iframe reference + this.meshViewerIframe = iframe; + + // Set initial node size to be square + this.setSize([512, 512]); + console.log("[GeomPack DEBUG] Node size set to [512, 512]"); + + // Handle execution + const onExecuted = this.onExecuted; + this.onExecuted = function(message) { + console.log("[GeomPack] onExecuted called with message:", message); + onExecuted?.apply(this, arguments); + + // The message IS the UI data (not message.ui) + if (message?.mesh_file && message.mesh_file[0]) { + const filename = message.mesh_file[0]; + console.log(`[GeomPack] Loading mesh: ${filename}`); + + // ComfyUI serves files via /view API — parse type/subfolder/filename + // Handles both absolute (/home/.../output/sub/file) and relative (output/sub/file) paths + let filepath; + const normalized = filename.replace(/\\/g, '/'); + const pathMatch = normalized.match(/(?:^|\/)(output|input|temp)\/(.+)$/); + if (pathMatch) { + const [, type, relPath] = pathMatch; + const parts = relPath.split('/'); + const fname = parts.pop(); + const subfolder = parts.join('/'); + filepath = `/view?filename=${encodeURIComponent(fname)}&type=${type}&subfolder=${encodeURIComponent(subfolder)}`; + } else { + // Fallback: use just the basename + const basename = normalized.split('/').pop(); + filepath = `/view?filename=${encodeURIComponent(basename)}&type=output&subfolder=`; + } + + // Send message to iframe (with delay to ensure iframe is loaded) + setTimeout(() => { + if (iframe.contentWindow) { + console.log(`[GeomPack] Sending postMessage to iframe: ${filepath}`); + iframe.contentWindow.postMessage({ + type: "LOAD_MESH", + filepath: filepath, + timestamp: Date.now() + }, "*"); + } else { + console.error("[GeomPack] Iframe contentWindow not available"); + } + }, 100); + } else { + console.log("[GeomPack] No mesh_file in message data. Keys:", Object.keys(message || {})); + } + }; + + return r; + }; + } + } +}); + +console.log("[GeomPack] Mesh preview extension registered"); diff --git a/javascript/js/mesh_preview_dual.js b/javascript/js/mesh_preview_dual.js new file mode 100644 index 00000000..cf68189d --- /dev/null +++ b/javascript/js/mesh_preview_dual.js @@ -0,0 +1,191 @@ +/** + * ComfyUI GeomPack - Dual Mesh Preview Widget + * Unified viewer for side-by-side and overlay dual mesh visualization + * with full field visualization support + */ + +import { app } from "../../../scripts/app.js"; +import { EXTENSION_FOLDER, getViewerUrl } from "./utils/extensionFolder.js"; +import { createContainer, createIframe, createInfoPanel } from "./utils/uiComponents.js"; +import { buildDualMeshInfoHTML, formatExtents } from "./utils/formatting.js"; +import { createViewerManager, createErrorHandler, buildViewUrl, createLoadDualMeshMessage } from "./utils/postMessage.js"; + +app.registerExtension({ + name: "geompack.meshpreview.dual", + + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name === "GeomPackPreviewMeshDual") { + const onNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function() { + const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined; + + // Viewer state persisted via DOM widget serialization + const viewerState = { show_edges: false, camera_state: "", selected_field: "", selected_channel: "magnitude", selected_colormap: "erdc_rainbow_bright" }; + + // Create container for viewer + info panel + const container = createContainer(); + + // Create iframe for VTK.js viewer + const iframe = createIframe(getViewerUrl("viewer_dual"), { minHeight: "550px" }); + + // Create mesh info panel + const infoPanel = createInfoPanel("Mesh info will appear here after execution"); + + // Add iframe and info panel to container + container.appendChild(iframe); + container.appendChild(infoPanel); + + // Add widget + const widget = this.addDOMWidget("preview_dual", "MESH_PREVIEW_DUAL", container, { + getValue() { return JSON.stringify(viewerState); }, + setValue(v) { + try { Object.assign(viewerState, JSON.parse(v)); } catch(e) {} + } + }); + widget.computeSize = () => [768, 680]; + + // Store references + this.meshViewerIframeDual = iframe; + this.meshInfoPanelDual = infoPanel; + + this.setSize(this.computeSize()); + + // Bidirectional sync: viewer → node widgets (viewerState + real widgets like opacity) + const node = this; + window.addEventListener('message', (event) => { + // Without this check, every open viewer instance's listener + // fires for every iframe's messages, not just its own. + if (event.source !== iframe.contentWindow) return; + if (event.data.type === 'WIDGET_UPDATE') { + const { widget: name, value } = event.data; + if (name in viewerState) viewerState[name] = value; + const w = node.widgets?.find(w => w.name === name); + if (w) w.value = value; + } + }); + + // Create viewer manager + const viewerManager = createViewerManager(iframe, "[GeomPack Dual]"); + + // Listen for error messages + window.addEventListener('message', createErrorHandler(infoPanel, "[GeomPack Dual]")); + + // Set initial node size + this.setSize([768, 680]); + + // Handle execution + const onExecuted = this.onExecuted; + this.onExecuted = function(message) { + onExecuted?.apply(this, arguments); + + if (!message?.layout) { + return; + } + + const layout = message.layout[0]; + const mode = message.mode?.[0] || "fields"; + + // Determine viewer type and name + let viewerType, viewerName; + if (layout === 'slider') { + viewerType = "slider"; + viewerName = "viewer_dual_slider"; + } else if (mode === "texture") { + viewerType = "texture"; + viewerName = "viewer_dual_textured"; + } else { + viewerType = "fields"; + viewerName = "viewer_dual"; + } + + let postMessageData; + + if (layout === 'side_by_side' || layout === 'slider') { + // Side-by-side mode + if (!message?.mesh_1_file || !message?.mesh_2_file) { + return; + } + + // Build info HTML using utility + const infoHTML = buildDualMeshInfoHTML({ + mode: mode, + layout: layout, + mesh1: { + vertices: message.vertex_count_1?.[0] || 'N/A', + faces: message.face_count_1?.[0] || 'N/A', + extents: message.extents_1?.[0] || [], + isWatertight: message.is_watertight_1?.[0], + hasTexture: message.has_texture_1?.[0] + }, + mesh2: { + vertices: message.vertex_count_2?.[0] || 'N/A', + faces: message.face_count_2?.[0] || 'N/A', + extents: message.extents_2?.[0] || [], + isWatertight: message.is_watertight_2?.[0], + hasTexture: message.has_texture_2?.[0] + }, + commonFields: message.common_fields?.[0] || [] + }); + + infoPanel.innerHTML = infoHTML; + + postMessageData = createLoadDualMeshMessage({ + layout: layout, + mesh1Filepath: buildViewUrl(message.mesh_1_file[0]), + mesh2Filepath: buildViewUrl(message.mesh_2_file[0]), + opacity1: message.opacity_1?.[0] || 1.0, + opacity2: message.opacity_2?.[0] || 1.0, + showEdges: viewerState.show_edges, + cameraState: viewerState.camera_state, + selectedField: viewerState.selected_field, + selectedChannel: viewerState.selected_channel, + selectedColormap: viewerState.selected_colormap, + }); + + } else { + // Overlay mode + if (!message?.mesh_file) { + return; + } + + // Build info HTML using utility + const infoHTML = buildDualMeshInfoHTML({ + mode: mode, + layout: "overlay", + mesh1: { + vertices: message.vertex_count_1?.[0] || 'N/A', + faces: message.face_count_1?.[0] || 'N/A', + hasTexture: message.has_texture_1?.[0] + }, + mesh2: { + vertices: message.vertex_count_2?.[0] || 'N/A', + faces: message.face_count_2?.[0] || 'N/A', + hasTexture: message.has_texture_2?.[0] + }, + commonFields: message.common_fields?.[0] || [] + }); + + infoPanel.innerHTML = infoHTML; + + postMessageData = createLoadDualMeshMessage({ + layout: layout, + meshFilepath: buildViewUrl(message.mesh_file[0]), + opacity1: message.opacity_1?.[0] || 1.0, + opacity2: message.opacity_2?.[0] || 1.0, + showEdges: viewerState.show_edges, + cameraState: viewerState.camera_state, + selectedField: viewerState.selected_field, + selectedChannel: viewerState.selected_channel, + selectedColormap: viewerState.selected_colormap, + }); + } + + // Switch viewer if needed and send message + viewerManager.switchViewer(viewerType, getViewerUrl(viewerName), postMessageData); + }; + + return r; + }; + } + } +}); diff --git a/javascript/js/mesh_preview_fbx.js b/javascript/js/mesh_preview_fbx.js new file mode 100644 index 00000000..b900468c --- /dev/null +++ b/javascript/js/mesh_preview_fbx.js @@ -0,0 +1,325 @@ +/** + * ComfyUI FBX Rigged Mesh Preview Widget + * + * Generic widget for FBX preview nodes. Loads viewer from file (not inline). + * Used by UniRig, SAM3DBody, and other extensions that preview FBX files. + * + * This file auto-registers for all known FBX preview node types when loaded. + * Extensions copy this file from the comfy-3d-viewers package at startup. + */ + +import { app } from "../../../../scripts/app.js"; + +// Auto-register for all known FBX preview node types +const FBX_PREVIEW_NODES = [ + { + nodeName: "UniRigPreviewRiggedMesh", + extensionName: "unirig.fbxpreview", + logPrefix: "[UniRig]", + fbxExportApiPath: "/unirig/export_posed_fbx" + }, + { + nodeName: "SAM3DBodyPreviewRiggedMesh", + extensionName: "sam3dbody.meshpreview", + logPrefix: "[SAM3DBody]" + // Note: SAM3DBody doesn't have FBX export API + }, + { + nodeName: "MocapPreviewRiggedMesh", + extensionName: "motioncapture.meshpreview", + logPrefix: "[MotionCapture]" + }, + { + nodeName: "FBXPreview", + extensionName: "motioncapture.fbxpreview.legacy", + logPrefix: "[MotionCapture]" + } +]; + +/** + * Detect the extension folder name from the current script URL + */ +function detectExtensionFolder() { + try { + // Try to detect from import.meta.url if available + if (typeof import.meta !== 'undefined' && import.meta.url) { + const match = import.meta.url.match(/\/extensions\/([^\/]+)\//); + if (match) { + return match[1]; + } + } + + // Fallback: look at currently loading script + const scripts = document.getElementsByTagName('script'); + for (let i = scripts.length - 1; i >= 0; i--) { + const src = scripts[i].src; + if (src) { + const match = src.match(/\/extensions\/([^\/]+)\//); + if (match) { + return match[1]; + } + } + } + } catch (e) { + console.warn('[FBX Preview] Could not detect extension folder:', e); + } + return null; +} + +/** + * Get the viewer URL for the FBX viewer HTML file + * @param {string} extensionFolder - The extension folder name + * @returns {string} The URL to the viewer HTML + */ +function getViewerUrl(extensionFolder, viewerFile = "viewer_fbx.html") { + // Add cache-busting timestamp + return `/extensions/${extensionFolder}/${viewerFile}?v=` + Date.now(); +} + +/** + * Create and register an FBX preview extension + * @param {Object} config - Configuration object + * @param {string} config.extensionName - Unique extension name (e.g., "unirig.fbxpreview") + * @param {string} config.nodeName - Node type name to hook (e.g., "UniRigPreviewRiggedMesh") + * @param {string} config.logPrefix - Log prefix for console messages (e.g., "[UniRig]") + * @param {string} [config.extensionFolder] - Override extension folder detection + * @param {string} [config.fbxExportApiPath] - API path for FBX export (e.g., "/unirig/export_posed_fbx") + */ +export function createFBXPreviewExtension(config) { + const { + extensionName, + nodeName, + logPrefix, + extensionFolder: configExtensionFolder, + fbxExportApiPath + } = config; + + console.log(`${logPrefix} Loading FBX mesh preview extension...`); + + // Detect extension folder if not provided + const extensionFolder = configExtensionFolder || detectExtensionFolder(); + if (!extensionFolder) { + console.error(`${logPrefix} Could not detect extension folder`); + return; + } + console.log(`${logPrefix} Detected extension folder: ${extensionFolder}`); + + app.registerExtension({ + name: extensionName, + + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name === nodeName) { + console.log(`${logPrefix} Registering Preview Rigged Mesh node`); + + const onNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function() { + const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined; + + console.log(`${logPrefix} Node created, adding FBX viewer widget`); + + // Create iframe for FBX viewer + const iframe = document.createElement("iframe"); + iframe.style.width = "100%"; + iframe.style.flex = "1 1 0"; + iframe.style.minHeight = "0"; + iframe.style.border = "none"; + iframe.style.backgroundColor = "#2a2a2a"; + + // Load viewer from file URL (not inline) + const viewerUrl = getViewerUrl(extensionFolder); + iframe.src = viewerUrl; + console.log(`${logPrefix} Setting iframe src to: ${viewerUrl}`); + + // Add load event listener + iframe.onload = () => { + console.log(`${logPrefix} Iframe loaded successfully`); + }; + iframe.onerror = (e) => { + console.error(`${logPrefix} Iframe failed to load:`, e); + }; + + // Add widget + const widget = this.addDOMWidget("preview", "FBX_PREVIEW", iframe, { + getValue() { return ""; }, + setValue(v) { } + }); + + console.log(`${logPrefix} Widget created:`, widget); + + // Set widget size - allow flexible height + widget.computeSize = function(width) { + const w = width || 512; + const h = w * 1.5; // Taller than wide to accommodate controls + return [w, h]; + }; + + widget.element = iframe; + + // Store iframe reference + this.fbxViewerIframe = iframe; + this.fbxViewerReady = false; + + // Listen for ready message from iframe + const onMessage = (event) => { + if (event.data && event.data.type === 'VIEWER_READY') { + console.log(`${logPrefix} Viewer iframe is ready!`); + this.fbxViewerReady = true; + } + }; + window.addEventListener('message', onMessage.bind(this)); + + const notifyIframeResize = () => { + if (iframe.contentWindow) { + const rect = iframe.getBoundingClientRect(); + iframe.contentWindow.postMessage({ + type: 'RESIZE', + width: rect.width, + height: rect.height + }, '*'); + } + }; + + this.onResize = function(size) { + const isVueNodes = iframe.closest('[data-node-id]') !== null || + document.querySelector('.vue-graph-canvas') !== null; + + if (!isVueNodes && size && size[1]) { + const nodeHeight = size[1]; + const headerHeight = 70; + const availableHeight = Math.max(200, nodeHeight - headerHeight); + iframe.style.height = availableHeight + 'px'; + } + + requestAnimationFrame(() => { + notifyIframeResize(); + }); + }; + + let resizeTimeout = null; + let lastSize = { width: 0, height: 0 }; + const resizeObserver = new ResizeObserver((entries) => { + const entry = entries[0]; + const newWidth = entry.contentRect.width; + const newHeight = entry.contentRect.height; + + if (Math.abs(newWidth - lastSize.width) < 1 && Math.abs(newHeight - lastSize.height) < 1) { + return; + } + lastSize = { width: newWidth, height: newHeight }; + + if (resizeTimeout) { + clearTimeout(resizeTimeout); + } + resizeTimeout = setTimeout(() => { + notifyIframeResize(); + }, 50); + }); + resizeObserver.observe(iframe); + + const originalOnRemoved = this.onRemoved; + this.onRemoved = function() { + resizeObserver.disconnect(); + if (resizeTimeout) { + clearTimeout(resizeTimeout); + } + window.removeEventListener('message', onMessage); + if (originalOnRemoved) { + originalOnRemoved.apply(this, arguments); + } + }; + + // Set initial node size (taller to accommodate controls) + this.setSize([512, 768]); + + // Handle execution + const onExecuted = this.onExecuted; + this.onExecuted = function(message) { + console.log(`${logPrefix} onExecuted called with message:`, message); + onExecuted?.apply(this, arguments); + + // The message contains the FBX file path + if (message?.fbx_file && message.fbx_file[0]) { + const filename = message.fbx_file[0]; + console.log(`${logPrefix} Loading FBX: ${filename}`); + + // Try different path formats based on filename + let filepath; + let folderType = 'output'; // default + + // Detect folder type from path + if (filename.includes('/input/') || filename.includes('\\input\\')) { + folderType = 'input'; + } + + // Extract basename if full path provided + const basename = filename.includes('/') || filename.includes('\\') + ? filename.split(/[/\\]/).pop() + : filename; + + filepath = `${window.location.origin}/view?filename=${encodeURIComponent(basename)}&type=${folderType}&subfolder=`; + + // Send message to iframe + const sendMessage = () => { + if (iframe.contentWindow) { + console.log(`${logPrefix} Sending postMessage to iframe: ${filepath}`); + const messageData = { + type: "LOAD_FBX", + filepath: filepath, + timestamp: Date.now() + }; + // Include custom FBX export API path if configured + if (fbxExportApiPath) { + messageData.fbxExportApiPath = fbxExportApiPath; + } + iframe.contentWindow.postMessage(messageData, "*"); + } else { + console.error(`${logPrefix} Iframe contentWindow not available`); + } + }; + + // Wait for iframe to be ready, or use timeout as fallback + if (this.fbxViewerReady) { + sendMessage(); + } else { + const checkReady = setInterval(() => { + if (this.fbxViewerReady) { + clearInterval(checkReady); + sendMessage(); + } + }, 50); + + // Fallback timeout after 2 seconds + setTimeout(() => { + clearInterval(checkReady); + if (!this.fbxViewerReady) { + console.warn(`${logPrefix} Iframe not ready after 2s, sending anyway`); + sendMessage(); + } + }, 2000); + } + } else { + console.log(`${logPrefix} No fbx_file in message data. Keys:`, Object.keys(message || {})); + } + }; + + return r; + }; + } + } + }); + + console.log(`${logPrefix} FBX mesh preview extension registered`); +} + +// Export detectExtensionFolder for use by other modules +export { detectExtensionFolder, getViewerUrl }; + +// Self-executing: register all known FBX preview node types +console.log("[FBX Preview] Auto-registering for all known FBX preview node types..."); +FBX_PREVIEW_NODES.forEach(config => { + try { + createFBXPreviewExtension(config); + } catch (e) { + // Extension already registered by another custom node copy - skip + } +}); diff --git a/javascript/js/mesh_preview_multi.js b/javascript/js/mesh_preview_multi.js new file mode 100644 index 00000000..ed58973e --- /dev/null +++ b/javascript/js/mesh_preview_multi.js @@ -0,0 +1,200 @@ +/** + * ComfyUI GeomPack - Multi Mesh Preview Widget + * Grid viewer for 1-4 meshes with synchronized cameras + */ + +import { app } from "../../../scripts/app.js"; + +// Auto-detect extension folder name +const EXTENSION_FOLDER = (() => { + const url = import.meta.url; + const match = url.match(/\/extensions\/([^/]+)\//); + return match ? match[1] : "ComfyUI-GeometryPack"; +})(); + +console.log('[GeomPack Multi JS] Loading mesh_preview_multi.js extension'); + +app.registerExtension({ + name: "geompack.meshpreview.multi", + + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name === "GeomPackPreviewMeshMulti") { + const onNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function() { + const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined; + + // Viewer state persisted via DOM widget serialization + const viewerState = { layout: "wipe", show_edges: false, camera_state: "", selected_field: "", selected_channel: "magnitude", selected_colormap: "erdc_rainbow_bright" }; + const viewerUrl = () => (viewerState.layout === "overlay" ? "viewer_multi.html" : "viewer_multi_slider.html"); + + console.log('[GeomPack Multi JS] Creating PreviewMeshMulti node widget'); + + // Create container for viewer + info panel + const container = document.createElement("div"); + container.style.width = "100%"; + container.style.height = "100%"; + container.style.display = "flex"; + container.style.flexDirection = "column"; + container.style.backgroundColor = "#2a2a2a"; + + // Create iframe for VTK.js viewer + const iframe = document.createElement("iframe"); + iframe.style.width = "100%"; + iframe.style.flex = "1"; + iframe.style.minHeight = "450px"; + iframe.style.border = "none"; + iframe.style.backgroundColor = "#2a2a2a"; + iframe.src = `/extensions/${EXTENSION_FOLDER}/${viewerUrl()}?v=` + Date.now(); + + // Layout toggle bar (Wipe = N-1 draggable dividers, fixed order; Overlay = stacked) + const bar = document.createElement("div"); + bar.style.cssText = "background:#1a1a1a;border-bottom:1px solid #444;padding:4px 8px;display:flex;gap:8px;align-items:center;font:11px monospace;color:#ccc;flex-shrink:0;"; + const layoutSel = document.createElement("select"); + layoutSel.style.cssText = "background:#333;color:#ccc;border:1px solid #555;border-radius:3px;font:11px monospace;padding:2px 6px;"; + layoutSel.innerHTML = ''; + bar.appendChild(Object.assign(document.createElement("span"), { textContent: "Layout:" })); + bar.appendChild(layoutSel); + + // Create mesh info panel + const infoPanel = document.createElement("div"); + infoPanel.style.backgroundColor = "#1a1a1a"; + infoPanel.style.borderTop = "1px solid #444"; + infoPanel.style.padding = "6px 12px"; + infoPanel.style.fontSize = "10px"; + infoPanel.style.fontFamily = "monospace"; + infoPanel.style.color = "#ccc"; + infoPanel.style.lineHeight = "1.3"; + infoPanel.style.flexShrink = "0"; + infoPanel.style.overflow = "hidden"; + infoPanel.innerHTML = 'Mesh info will appear here after execution'; + + container.appendChild(bar); + container.appendChild(iframe); + container.appendChild(infoPanel); + + // Add widget + const widget = this.addDOMWidget("preview_multi", "MESH_PREVIEW_MULTI", container, { + getValue() { return JSON.stringify(viewerState); }, + setValue(v) { + try { Object.assign(viewerState, JSON.parse(v)); } catch(e) {} + } + }); + + widget.computeSize = () => [768, 580]; + + // Store references + this.meshViewerIframeMulti = iframe; + this.meshInfoPanelMulti = infoPanel; + + this.setSize(this.computeSize()); + + // Bidirectional sync: viewer → node widgets (viewerState + real widgets) + const node = this; + window.addEventListener('message', (event) => { + // Without this check, every open viewer instance's listener + // fires for every iframe's messages, not just its own. + if (event.source !== iframe.contentWindow) return; + if (event.data.type === 'WIDGET_UPDATE') { + const { widget: name, value } = event.data; + if (name in viewerState) viewerState[name] = value; + const w = node.widgets?.find(w => w.name === name); + if (w) w.value = value; + } + }); + + // Track iframe load state + last loaded meshes (so a layout switch re-sends) + let iframeLoaded = false; + let lastLoad = null; // { numMeshes, filepaths } + const buildAndSend = () => { + if (!lastLoad || !iframe.contentWindow) return; + let msg; + if (viewerState.layout === "overlay") { + msg = { type: 'LOAD_MULTI_MESH', numMeshes: lastLoad.numMeshes, meshFiles: lastLoad.filepaths, + timestamp: Date.now(), showEdges: viewerState.show_edges, cameraState: viewerState.camera_state, + selectedField: viewerState.selected_field, selectedChannel: viewerState.selected_channel, + selectedColormap: viewerState.selected_colormap }; + } else { + msg = { type: 'LOAD_MULTI_SLIDER', mesh_files: lastLoad.filepaths, timestamp: Date.now(), + show_edges: viewerState.show_edges, camera_state: viewerState.camera_state }; + } + iframe.contentWindow.postMessage(msg, "*"); + }; + iframe.addEventListener('load', () => { iframeLoaded = true; buildAndSend(); }); + + // Layout switch: swap the viewer iframe; buildAndSend fires on its load + layoutSel.value = viewerState.layout; + layoutSel.addEventListener('change', () => { + viewerState.layout = layoutSel.value; + iframeLoaded = false; + iframe.src = `/extensions/${EXTENSION_FOLDER}/${viewerUrl()}?v=` + Date.now(); + }); + + // Set initial node size + this.setSize([768, 580]); + + // Handle execution + const onExecuted = this.onExecuted; + this.onExecuted = function(message) { + onExecuted?.apply(this, arguments); + + if (!message?.num_meshes) { + return; + } + + const numMeshes = message.num_meshes[0]; + const meshFiles = message.mesh_files[0]; + const vertexCounts = message.vertex_counts[0]; + const faceCounts = message.face_counts[0]; + const gridCols = message.grid_cols[0]; + const gridRows = message.grid_rows[0]; + + console.log(`[GeomPack Multi] onExecuted: ${numMeshes} meshes, grid ${gridCols}x${gridRows}`); + + // Per-mesh info, one column per mesh (matches the single Preview Mesh panel) + const wt = message.is_watertight_list?.[0] || []; + const avg = message.avg_edge_lengths?.[0] || []; + const bnds = message.bounds_list?.[0] || []; + const exts = message.extents_list?.[0] || []; + const fields = message.field_names_list?.[0] || null; + const num = (v) => (v == null ? '—' : Number(v).toLocaleString()); + const sig = (v) => (v == null ? '—' : Number(v).toLocaleString(undefined, { maximumSignificantDigits: 4 })); + const ext = (e) => (e ? e.map((x) => Number(x).toFixed(2)).join(' × ') : '—'); + const bnd = (b) => (b + ? `[${b[0].map((x) => Number(x).toFixed(1)).join(', ')}]
→ [${b[1].map((x) => Number(x).toFixed(1)).join(', ')}]
` + : '—'); + + let infoHTML = `
`; + infoHTML += ``; + for (let i = 0; i < numMeshes; i++) { + infoHTML += `Mesh ${i + 1}`; + } + const row = (label, valFn) => { + infoHTML += `${label}`; + for (let i = 0; i < numMeshes; i++) infoHTML += `${valFn(i)}`; + }; + row('Vertices:', (i) => num(vertexCounts[i])); + row('Faces:', (i) => num(faceCounts[i])); + row('Watertight:', (i) => { const w = wt[i]; return `${w ? 'Yes' : 'No'}`; }); + row('Avg edge:', (i) => sig(avg[i])); + row('Extents:', (i) => ext(exts[i])); + row('Bounds:', (i) => bnd(bnds[i])); + if (fields) { + row('Fields:', (i) => { + const f = fields[i] || []; + return f.length ? `${f.join(', ')}` : '—'; + }); + } + infoHTML += '
'; + infoPanel.innerHTML = infoHTML; + + // Prepare file paths + store for (re)send (also used when layout is switched) + const filepaths = meshFiles.map(f => `/view?filename=${encodeURIComponent(f)}&type=output&subfolder=`); + lastLoad = { numMeshes, filepaths }; + buildAndSend(); + }; + + return r; + }; + } + } +}); diff --git a/javascript/js/mesh_preview_uv.js b/javascript/js/mesh_preview_uv.js new file mode 100644 index 00000000..ca773c09 --- /dev/null +++ b/javascript/js/mesh_preview_uv.js @@ -0,0 +1,119 @@ +/** + * ComfyUI GeomPack - UV Mesh Preview Widget + * Synchronized 3D mesh and 2D UV layout viewer with interactive picking + */ + +import { app } from "../../../scripts/app.js"; + +// Auto-detect extension folder name (handles ComfyUI-GeometryPack or comfyui-geometrypack) +const EXTENSION_FOLDER = (() => { + const url = import.meta.url; + const match = url.match(/\/extensions\/([^/]+)\//); + return match ? match[1] : "ComfyUI-GeometryPack"; +})(); + +console.log("[GeomPack] Loading UV mesh preview extension..."); + +app.registerExtension({ + name: "geompack.meshpreviewuv", + + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name === "GeomPackPreviewMeshUV") { + console.log("[GeomPack] Registering Preview Mesh UV node"); + + const onNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function() { + const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined; + + console.log("[GeomPack UV] Node created, adding widget"); + + // Create iframe for UV viewer + const iframe = document.createElement("iframe"); + iframe.style.width = "100%"; + iframe.style.height = "100%"; + iframe.style.border = "none"; + iframe.style.backgroundColor = "#2a2a2a"; + iframe.style.aspectRatio = "2"; // Wide aspect for split view + + // Point to our UV viewer HTML + iframe.src = `/extensions/${EXTENSION_FOLDER}/viewer_uv.html?v=` + Date.now(); + + // Add widget + const widget = this.addDOMWidget("uv_preview", "MESH_UV_PREVIEW", iframe, { + getValue() { return ""; }, + setValue(v) { } + }); + + // Set widget size - wider for split view + widget.computeSize = function(width) { + const w = width || 600; + const h = w / 2; // 2:1 aspect ratio + return [w, h]; + }; + + widget.element = iframe; + + // Store iframe reference + this.uvViewerIframe = iframe; + + // Set initial node size (wide for split view) + this.setSize([600, 350]); + + // Handle execution + const onExecuted = this.onExecuted; + this.onExecuted = function(message) { + console.log("[GeomPack UV] onExecuted called with message:", message); + onExecuted?.apply(this, arguments); + + if (message?.mesh_file && message.mesh_file[0]) { + const meshFilename = message.mesh_file[0]; + const uvDataFilename = message.uv_data_file ? message.uv_data_file[0] : null; + const showChecker = message.show_checker ? message.show_checker[0] : false; + const showWireframe = message.show_wireframe ? message.show_wireframe[0] : true; + + console.log(`[GeomPack UV] Loading mesh: ${meshFilename}`); + console.log(`[GeomPack UV] UV data: ${uvDataFilename}`); + console.log(`[GeomPack UV] Checker: ${showChecker}, Wireframe: ${showWireframe}`); + + // Build file URLs + const meshPath = `/view?filename=${encodeURIComponent(meshFilename)}&type=output&subfolder=`; + const uvDataPath = uvDataFilename ? + `/view?filename=${encodeURIComponent(uvDataFilename)}&type=output&subfolder=` : null; + + // Send message to iframe + setTimeout(() => { + if (iframe.contentWindow) { + console.log(`[GeomPack UV] Sending postMessage to iframe`); + iframe.contentWindow.postMessage({ + type: "LOAD_MESH_UV", + meshPath: meshPath, + uvDataPath: uvDataPath, + checker: showChecker, + wireframe: showWireframe, + timestamp: Date.now() + }, "*"); + } else { + console.error("[GeomPack UV] Iframe contentWindow not available"); + } + }, 100); + + // Update node title with UV info + if (message.has_uvs && message.has_uvs[0]) { + const coverage = message.uv_coverage ? message.uv_coverage[0].toFixed(3) : "?"; + const inUnit = message.uv_in_unit_square ? message.uv_in_unit_square[0] : false; + console.log(`[GeomPack UV] UV Coverage: ${coverage}, In Unit Square: ${inUnit}`); + } else { + console.warn("[GeomPack UV] No UV data found on mesh"); + } + } else { + console.log("[GeomPack UV] No mesh_file in message data. Keys:", Object.keys(message || {})); + } + }; + + return r; + }; + } + } +}); + +console.log("[GeomPack] UV mesh preview extension registered"); diff --git a/javascript/js/mesh_preview_vtk.js b/javascript/js/mesh_preview_vtk.js new file mode 100644 index 00000000..f56caf4c --- /dev/null +++ b/javascript/js/mesh_preview_vtk.js @@ -0,0 +1,160 @@ +/** + * ComfyUI GeomPack - VTK.js Mesh Preview Widget + * Scientific visualization with VTK.js + */ + +import { app } from "../../../scripts/app.js"; +import { EXTENSION_FOLDER, getViewerUrl } from "./utils/extensionFolder.js"; +import { createContainer, createIframe, createInfoPanel, showPanelError } from "./utils/uiComponents.js"; +import { buildMeshInfoHTML } from "./utils/formatting.js"; +import { createScreenshotHandler } from "./utils/screenshot.js"; +import { createViewerManager, createErrorHandler, buildViewUrl } from "./utils/postMessage.js"; + +app.registerExtension({ + name: "geompack.meshpreview.vtk", + + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name === "GeomPackPreviewMeshVTK") { + + const onNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function() { + const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined; + + // Viewer state persisted via DOM widget serialization + const viewerState = { show_edges: false, camera_state: "", selected_field: "", selected_channel: "magnitude", selected_colormap: "erdc_rainbow_bright" }; + + // Create container for viewer + info panel + const container = createContainer(); + + // Create iframe for VTK.js viewer + const iframe = createIframe(getViewerUrl("viewer_vtk")); + + // Create mesh info panel + const infoPanel = createInfoPanel("Mesh info will appear here after execution"); + + // Add iframe and info panel to container + container.appendChild(iframe); + container.appendChild(infoPanel); + + // Add widget + const widget = this.addDOMWidget("preview_vtk", "MESH_PREVIEW_VTK", container, { + getValue() { return JSON.stringify(viewerState); }, + setValue(v) { + try { Object.assign(viewerState, JSON.parse(v)); } catch(e) {} + }, + // Low constant minimum: the DOM widget fills the node's height and + // the node resizes freely down to ~120px. A CONSTANT can't feed back + // the way a node.size-derived computeSize did (which grew forever), + // so do NOT re-add a computeSize override here. + getMinHeight: () => 120, + }); + + // Store references + this.meshViewerIframeVTK = iframe; + this.meshInfoPanelVTK = infoPanel; + + this.setSize([512, 640]); + + // Bidirectional sync: viewer → node widgets (viewerState + real widgets) + const node = this; + window.addEventListener('message', (event) => { + // Without this check, every open viewer instance's listener + // fires for every iframe's messages, not just its own. + if (event.source !== iframe.contentWindow) return; + if (event.data.type === 'WIDGET_UPDATE') { + const { widget: name, value } = event.data; + if (name in viewerState) viewerState[name] = value; + const w = node.widgets?.find(w => w.name === name); + if (w) w.value = value; + } else if (event.data.type === 'TOGGLE_INFO') { + // viewer's minimise arrow also hides/shows this node's info panel + infoPanel.style.display = event.data.collapsed ? 'none' : ''; + } + }); + + // Create viewer manager for handling viewer switching + const viewerManager = createViewerManager(iframe, "[GeomPack VTK]"); + + // Listen for screenshot and error messages + window.addEventListener('message', createScreenshotHandler('vtk-screenshot')); + window.addEventListener('message', createErrorHandler(infoPanel, "[GeomPack VTK]")); + + // Set initial node size + this.setSize([512, 640]); + + // Handle execution + const onExecuted = this.onExecuted; + this.onExecuted = function(message) { + onExecuted?.apply(this, arguments); + + if (message?.mesh_file && message.mesh_file[0]) { + const filename = message.mesh_file[0]; + const viewerType = message.viewer_type?.[0] || "fields"; + const mode = message.mode?.[0] || "fields"; + + // Determine which viewer HTML to use + let viewerName; + if (viewerType === "pbr") { + viewerName = "viewer_pbr"; + } else if (viewerType === "texture") { + viewerName = "viewer_vtk_textured"; + } else { + viewerName = "viewer_vtk"; + } + + // Build info HTML using utility + const infoHTML = buildMeshInfoHTML({ + mode: mode, + vertices: message.vertex_count?.[0] || 'N/A', + faces: message.face_count?.[0] || 'N/A', + boundsMin: message.bounds_min?.[0] || [], + boundsMax: message.bounds_max?.[0] || [], + extents: message.extents?.[0] || [], + avgEdge: message.avg_edge_length?.[0], + isWatertight: message.is_watertight?.[0], + fieldNames: message.field_names?.[0] || [], + fieldRanges: message.field_ranges?.[0] || [], + hasTexture: message.has_texture?.[0], + hasVertexColors: message.has_vertex_colors?.[0], + visualKind: message.visual_kind?.[0] + }); + + infoPanel.innerHTML = infoHTML; + + // Click a field's min/max value to fly the camera to that element. + const minPos = message.field_min_pos?.[0] || []; + const maxPos = message.field_max_pos?.[0] || []; + infoPanel.querySelectorAll('.field-extreme').forEach((el) => { + el.addEventListener('click', () => { + const i = parseInt(el.dataset.fidx, 10); + const pos = (el.dataset.which === 'min' ? minPos : maxPos)[i]; + if (pos && pos.length === 3) { + viewerManager.sendMessage({ type: 'FOCUS_ON_POINT', point: pos, timestamp: Date.now() }); + } + }); + }); + + // Build file path and message + const filepath = buildViewUrl(filename); + const messageData = { + type: "LOAD_MESH", + filepath: filepath, + timestamp: Date.now(), + showEdges: viewerState.show_edges, + cameraState: viewerState.camera_state, + selectedField: viewerState.selected_field, + selectedChannel: viewerState.selected_channel, + selectedColormap: viewerState.selected_colormap, + }; + + // Switch viewer if needed and send message + viewerManager.switchViewer(viewerType, getViewerUrl(viewerName), messageData); + } + }; + + return r; + }; + } + } +}); + diff --git a/javascript/js/mesh_preview_vtk_batch.js b/javascript/js/mesh_preview_vtk_batch.js new file mode 100644 index 00000000..c42f0b63 --- /dev/null +++ b/javascript/js/mesh_preview_vtk_batch.js @@ -0,0 +1,463 @@ +/** + * ComfyUI GeomPack - VTK.js Batch Mesh Preview Widget + * Scientific visualization with VTK.js and batch navigation + */ + +import { app } from "../../../scripts/app.js"; + +// Auto-detect extension folder name (handles ComfyUI-GeometryPack or comfyui-geometrypack) +const EXTENSION_FOLDER = (() => { + const url = import.meta.url; + const match = url.match(/\/extensions\/([^/]+)\//); + return match ? match[1] : "ComfyUI-GeometryPack"; +})(); + +app.registerExtension({ + name: "geompack.meshpreview.vtk.batch", + + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name === "GeomPackPreviewMeshVTKBatch") { + + const onNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function() { + const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined; + + // Viewer state persisted via DOM widget serialization + const viewerState = { show_edges: false, camera_state: "", selected_field: "", selected_channel: "magnitude", selected_colormap: "erdc_rainbow_bright" }; + + // Create container for viewer + navigation + info panel + const container = document.createElement("div"); + container.style.width = "100%"; + container.style.height = "100%"; + container.style.display = "flex"; + container.style.flexDirection = "column"; + container.style.backgroundColor = "#2a2a2a"; + container.style.overflow = "hidden"; + + // Create iframe for VTK.js viewer + const iframe = document.createElement("iframe"); + iframe.style.width = "100%"; + iframe.style.flex = "1 1 0"; + iframe.style.minHeight = "0"; + iframe.style.border = "none"; + iframe.style.backgroundColor = "#2a2a2a"; + + // Point to VTK.js HTML viewer (with cache buster) + // Note: viewer will be dynamically switched based on mode in onExecuted + // Use unified v2 viewer with modular architecture + iframe.src = `/extensions/${EXTENSION_FOLDER}/viewer_vtk.html?v=` + Date.now(); + + // Track current viewer type to avoid unnecessary reloads + let currentViewerType = "fields"; + + // Create navigation bar for batch controls + const navBar = document.createElement("div"); + navBar.style.backgroundColor = "#1a1a1a"; + navBar.style.borderTop = "1px solid #444"; + navBar.style.padding = "8px 12px"; + navBar.style.display = "flex"; + navBar.style.alignItems = "center"; + navBar.style.justifyContent = "center"; + navBar.style.gap = "12px"; + navBar.style.fontSize = "12px"; + navBar.style.color = "#ccc"; + navBar.style.flexShrink = "0"; + + // Previous button + const prevButton = document.createElement("button"); + prevButton.textContent = "< Previous"; + prevButton.style.padding = "4px 12px"; + prevButton.style.cursor = "pointer"; + prevButton.style.backgroundColor = "#333"; + prevButton.style.color = "#ccc"; + prevButton.style.border = "1px solid #555"; + prevButton.style.borderRadius = "3px"; + prevButton.style.fontSize = "11px"; + + // Index display + const indexLabel = document.createElement("span"); + indexLabel.textContent = "1 / 1"; + indexLabel.style.minWidth = "60px"; + indexLabel.style.textAlign = "center"; + indexLabel.style.fontFamily = "monospace"; + indexLabel.style.fontWeight = "bold"; + + // Next button + const nextButton = document.createElement("button"); + nextButton.textContent = "Next >"; + nextButton.style.padding = "4px 12px"; + nextButton.style.cursor = "pointer"; + nextButton.style.backgroundColor = "#333"; + nextButton.style.color = "#ccc"; + nextButton.style.border = "1px solid #555"; + nextButton.style.borderRadius = "3px"; + nextButton.style.fontSize = "11px"; + + // Assemble navigation bar + navBar.appendChild(prevButton); + navBar.appendChild(indexLabel); + navBar.appendChild(nextButton); + + // Create mesh info panel + const infoPanel = document.createElement("div"); + infoPanel.style.backgroundColor = "#1a1a1a"; + infoPanel.style.borderTop = "1px solid #444"; + infoPanel.style.padding = "6px 12px"; + infoPanel.style.fontSize = "10px"; + infoPanel.style.fontFamily = "monospace"; + infoPanel.style.color = "#ccc"; + infoPanel.style.lineHeight = "1.3"; + infoPanel.style.flexShrink = "0"; + infoPanel.style.overflow = "hidden"; + infoPanel.innerHTML = 'Mesh info will appear here after execution'; + + // Add iframe, navigation bar, and info panel to container + container.appendChild(iframe); + container.appendChild(navBar); + container.appendChild(infoPanel); + + // Add widget with required options + + const widget = this.addDOMWidget("preview_vtk_batch", "MESH_PREVIEW_VTK_BATCH", container, { + getValue() { return JSON.stringify(viewerState); }, + setValue(v) { + try { Object.assign(viewerState, JSON.parse(v)); } catch(e) {} + } + }); + + + widget.computeSize = () => [512, 680]; // Increased height for viewer + navigation + info panel + + // Store iframe and info panel references + this.meshViewerIframeVTKBatch = iframe; + this.meshInfoPanelVTKBatch = infoPanel; + this.meshNavBarVTKBatch = navBar; + + // Bidirectional sync: viewer → node widgets (viewerState + real widgets) + const node = this; + window.addEventListener('message', (event) => { + // Without this check, every open GeomPackPreviewMeshVTKBatch + // instance's listener fires for every iframe's messages, not + // just its own -- e.g. toggling "show edges" in one viewer + // updates every other open viewer's state too. + if (event.source !== iframe.contentWindow) return; + if (event.data.type === 'WIDGET_UPDATE') { + const { widget: name, value } = event.data; + if (name in viewerState) viewerState[name] = value; + const w = node.widgets?.find(w => w.name === name); + if (w) w.value = value; + } + }); + + // Track iframe load state + let iframeLoaded = false; + iframe.addEventListener('load', () => { + iframeLoaded = true; + }); + + // Find the index widget (created by ComfyUI from INPUT_TYPES) + const indexWidget = this.widgets.find(w => w.name === "index"); + + // Track batch state + let currentBatchSize = 1; + let currentIndex = 0; + + // Add callback to auto-execute when index changes manually + if (indexWidget) { + const originalCallback = indexWidget.callback; + indexWidget.callback = function(value) { + // Call original callback if it exists + const result = originalCallback?.apply(this, arguments); + + // Update tracked index + currentIndex = value; + + // Trigger re-execution (same as button clicks) + app.queuePrompt(); + + return result; + }; + } + + // Button click handlers + prevButton.addEventListener("click", () => { + if (indexWidget && currentIndex > 0) { + indexWidget.value = currentIndex - 1; + // Trigger node queue/re-execution + app.queuePrompt(); + } + }); + + nextButton.addEventListener("click", () => { + if (indexWidget && currentIndex < currentBatchSize - 1) { + indexWidget.value = currentIndex + 1; + // Trigger node queue/re-execution + app.queuePrompt(); + } + }); + + // Update button states + const updateNavigationButtons = () => { + prevButton.disabled = currentIndex === 0; + nextButton.disabled = currentIndex >= currentBatchSize - 1; + + // Style disabled buttons + if (prevButton.disabled) { + prevButton.style.opacity = "0.4"; + prevButton.style.cursor = "not-allowed"; + } else { + prevButton.style.opacity = "1"; + prevButton.style.cursor = "pointer"; + } + + if (nextButton.disabled) { + nextButton.style.opacity = "0.4"; + nextButton.style.cursor = "not-allowed"; + } else { + nextButton.style.opacity = "1"; + nextButton.style.cursor = "pointer"; + } + }; + + // Listen for messages from iframe + window.addEventListener('message', async (event) => { + if (event.source !== iframe.contentWindow) return; + // Handle screenshot messages + if (event.data.type === 'SCREENSHOT' && event.data.image) { + + try { + // Convert base64 data URL to blob + const base64Data = event.data.image.split(',')[1]; + const byteString = atob(base64Data); + const arrayBuffer = new ArrayBuffer(byteString.length); + const uint8Array = new Uint8Array(arrayBuffer); + + for (let i = 0; i < byteString.length; i++) { + uint8Array[i] = byteString.charCodeAt(i); + } + + const blob = new Blob([uint8Array], { type: 'image/png' }); + + // Generate filename with timestamp + const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); + const filename = `vtk-screenshot-${timestamp}.png`; + + // Create FormData for upload + const formData = new FormData(); + formData.append('image', blob, filename); + formData.append('type', 'output'); // Save to output directory + formData.append('subfolder', ''); // Root of output folder + + // Upload to ComfyUI backend + const response = await fetch('/upload/image', { + method: 'POST', + body: formData + }); + + if (response.ok) { + const result = await response.json(); + } else { + throw new Error(`Upload failed: ${response.status} ${response.statusText}`); + } + + } catch (error) { + console.error('[GeomPack VTK Batch] Error saving screenshot:', error); + } + } + // Handle error messages from iframe + else if (event.data.type === 'MESH_ERROR' && event.data.error) { + console.error('[GeomPack VTK Batch] Error from viewer:', event.data.error); + if (infoPanel) { + infoPanel.innerHTML = `
Error: ${event.data.error}
`; + } + } + }); + + // Set initial node size (increased for info panel + navigation) + this.setSize([512, 680]); + + // Handle execution + const onExecuted = this.onExecuted; + this.onExecuted = function(message) { + onExecuted?.apply(this, arguments); + + // The message IS the UI data (not message.ui) + if (message?.mesh_file && message.mesh_file[0]) { + const filename = message.mesh_file[0]; + const viewerType = message.viewer_type?.[0] || "fields"; + const mode = message.mode?.[0] || "fields"; + + // Get batch metadata + currentBatchSize = message.batch_size?.[0] || 1; + currentIndex = message.current_index?.[0] || 0; + + // Update navigation controls + indexLabel.textContent = `${currentIndex + 1} / ${currentBatchSize}`; + updateNavigationButtons(); + + // Dynamically update index widget max based on actual batch size + if (indexWidget) { + indexWidget.options.max = currentBatchSize - 1; + + // Clamp current value if out of range + if (indexWidget.value >= currentBatchSize) { + indexWidget.value = currentBatchSize - 1; + } + } + + // Determine which viewer HTML to use (unified v2 viewers) + const viewerUrl = viewerType === "texture" + ? `/extensions/${EXTENSION_FOLDER}/viewer_vtk_textured.html` + : `/extensions/${EXTENSION_FOLDER}/viewer_vtk.html`; + + // Update mesh info panel with metadata + const vertices = message.vertex_count?.[0] || 'N/A'; + const faces = message.face_count?.[0] || 'N/A'; + const boundsMin = message.bounds_min?.[0] || []; + const boundsMax = message.bounds_max?.[0] || []; + const extents = message.extents?.[0] || []; + + // Format bounds + let boundsStr = 'N/A'; + if (boundsMin.length === 3 && boundsMax.length === 3) { + boundsStr = `[${boundsMin.map(v => v.toFixed(2)).join(', ')}] to [${boundsMax.map(v => v.toFixed(2)).join(', ')}]`; + } + + // Format extents + let extentsStr = 'N/A'; + if (extents.length === 3) { + extentsStr = `${extents.map(v => v.toFixed(2)).join(' x ')}`; + } + + // Build info HTML + const modeLabel = mode.charAt(0).toUpperCase() + mode.slice(1); + const modeColor = mode === "texture" ? '#c8c' : '#6cc'; + + let infoHTML = ` +
+ Batch: + ${currentIndex + 1} / ${currentBatchSize} + + Mode: + ${modeLabel} + + Vertices: + ${vertices.toLocaleString()} + + Faces: + ${faces.toLocaleString()} + + Bounds: + ${boundsStr} + + Extents: + ${extentsStr} + `; + + // Add watertight status (always shown) + if (message.is_watertight !== undefined) { + const watertight = message.is_watertight[0] ? 'Yes' : 'No'; + const color = message.is_watertight[0] ? '#6c6' : '#c66'; + infoHTML += ` + Watertight: + ${watertight} + `; + } + + // Add mode-specific info + if (viewerType === "texture") { + // Texture mode info + if (message.visual_kind !== undefined) { + const visualKind = message.visual_kind[0] || 'none'; + infoHTML += ` + Visual Kind: + ${visualKind} + `; + } + if (message.has_texture !== undefined) { + const hasTexture = message.has_texture[0] ? 'Yes' : 'No'; + const texColor = message.has_texture[0] ? '#c8c' : '#888'; + infoHTML += ` + Textures: + ${hasTexture} + `; + } + if (message.has_vertex_colors !== undefined) { + const hasColors = message.has_vertex_colors[0] ? 'Yes' : 'No'; + infoHTML += ` + Vertex Colors: + ${hasColors} + `; + } + } else { + // Fields mode info + if (message.field_names && message.field_names[0]?.length > 0) { + const fields = message.field_names[0].join(', '); + infoHTML += ` + Fields: + ${fields} + `; + } else { + infoHTML += ` + Fields: + None + `; + } + } + + infoHTML += '
'; + + infoPanel.innerHTML = infoHTML; + + // ComfyUI serves output files via /view API endpoint + const filepath = `/view?filename=${encodeURIComponent(filename)}&type=output&subfolder=`; + + // Function to send message + const sendMessage = () => { + if (iframe.contentWindow) { + iframe.contentWindow.postMessage({ + type: "LOAD_MESH", + filepath: filepath, + timestamp: Date.now(), + showEdges: viewerState.show_edges, + cameraState: viewerState.camera_state, + selectedField: viewerState.selected_field, + selectedChannel: viewerState.selected_channel, + selectedColormap: viewerState.selected_colormap, + }, "*"); + } else { + console.error("[GeomPack VTK Batch] Iframe contentWindow not available"); + } + }; + + // Reload iframe if viewer type changed + if (viewerType !== currentViewerType) { + currentViewerType = viewerType; + iframeLoaded = false; + + // Set up one-time load listener before changing src + const onViewerLoaded = () => { + iframeLoaded = true; + sendMessage(); + }; + iframe.addEventListener('load', onViewerLoaded, { once: true }); + + // Change iframe src to trigger reload + iframe.src = viewerUrl + "?v=" + Date.now(); + } else { + // No viewer change needed, send message immediately or after short delay + if (iframeLoaded) { + sendMessage(); + } else { + setTimeout(sendMessage, 500); + } + } + } else { + } + }; + + return r; + }; + } + } +}); diff --git a/javascript/js/mesh_preview_vtk_textured.js b/javascript/js/mesh_preview_vtk_textured.js new file mode 100644 index 00000000..f1e53290 --- /dev/null +++ b/javascript/js/mesh_preview_vtk_textured.js @@ -0,0 +1,261 @@ +/** + * ComfyUI GeomPack - VTK.js Textured Mesh Preview Widget + * Supports GLB/GLTF with textures and PBR materials via VTK.js GLTFImporter + */ + +import { app } from "../../../scripts/app.js"; + +// Auto-detect extension folder name (handles ComfyUI-GeometryPack or comfyui-geometrypack) +const EXTENSION_FOLDER = (() => { + const url = import.meta.url; + const match = url.match(/\/extensions\/([^/]+)\//); + return match ? match[1] : "ComfyUI-GeometryPack"; +})(); + +console.log("[GeomPack] Loading VTK.js textured mesh preview extension..."); + +app.registerExtension({ + name: "geompack.meshpreview.vtk.textured", + + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name === "GeomPackPreviewMeshVTKWithTexture") { + console.log("[GeomPack] Registering Preview Mesh (VTK with Textures) node"); + + const onNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function() { + const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined; + + // Create container for viewer + info panel + const container = document.createElement("div"); + container.style.width = "100%"; + container.style.height = "100%"; + container.style.display = "flex"; + container.style.flexDirection = "column"; + container.style.backgroundColor = "#2a2a2a"; + container.style.overflow = "hidden"; + + // Create iframe for VTK.js textured viewer + const iframe = document.createElement("iframe"); + iframe.style.width = "100%"; + iframe.style.flex = "1 1 0"; + iframe.style.minHeight = "0"; + iframe.style.border = "none"; + iframe.style.backgroundColor = "#2a2a2a"; + + // Point to VTK.js textured HTML viewer (with cache buster) + // Use unified v2 viewer with modular architecture + iframe.src = `/extensions/${EXTENSION_FOLDER}/viewer_vtk_textured.html?v=` + Date.now(); + + // Create mesh info panel + const infoPanel = document.createElement("div"); + infoPanel.style.backgroundColor = "#1a1a1a"; + infoPanel.style.borderTop = "1px solid #444"; + infoPanel.style.padding = "6px 12px"; + infoPanel.style.fontSize = "10px"; + infoPanel.style.fontFamily = "monospace"; + infoPanel.style.color = "#ccc"; + infoPanel.style.lineHeight = "1.3"; + infoPanel.style.flexShrink = "0"; + infoPanel.style.overflow = "hidden"; + infoPanel.innerHTML = 'Textured mesh info will appear here after execution'; + + // Add iframe and info panel to container + container.appendChild(iframe); + container.appendChild(infoPanel); + + // Add widget with required options + const widget = this.addDOMWidget("preview_vtk_textured", "MESH_PREVIEW_VTK_TEXTURED", container, { + getValue() { return ""; }, + setValue(v) { } + }); + + widget.computeSize = () => [512, 640]; // Increased height for viewer + info panel + + // Store iframe and info panel references + this.meshViewerIframeVTKTextured = iframe; + this.meshInfoPanelVTKTextured = infoPanel; + + // Track iframe load state + let iframeLoaded = false; + iframe.addEventListener('load', () => { + iframeLoaded = true; + }); + + // Listen for messages from iframe + window.addEventListener('message', async (event) => { + // Handle screenshot messages + if (event.data.type === 'SCREENSHOT' && event.data.image) { + console.log('[GeomPack VTK Textured] Received screenshot from iframe'); + + try { + // Convert base64 data URL to blob + const base64Data = event.data.image.split(',')[1]; + const byteString = atob(base64Data); + const arrayBuffer = new ArrayBuffer(byteString.length); + const uint8Array = new Uint8Array(arrayBuffer); + + for (let i = 0; i < byteString.length; i++) { + uint8Array[i] = byteString.charCodeAt(i); + } + + const blob = new Blob([uint8Array], { type: 'image/png' }); + + // Generate filename with timestamp + const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); + const filename = `vtk-textured-screenshot-${timestamp}.png`; + + // Create FormData for upload + const formData = new FormData(); + formData.append('image', blob, filename); + formData.append('type', 'output'); // Save to output directory + formData.append('subfolder', ''); // Root of output folder + + // Upload to ComfyUI backend + console.log('[GeomPack VTK Textured] Uploading screenshot to server...'); + const response = await fetch('/upload/image', { + method: 'POST', + body: formData + }); + + if (response.ok) { + const result = await response.json(); + console.log('[GeomPack VTK Textured] Screenshot saved to outputs folder:', result.name); + } else { + throw new Error(`Upload failed: ${response.status} ${response.statusText}`); + } + + } catch (error) { + console.error('[GeomPack VTK Textured] Error saving screenshot:', error); + } + } + // Handle error messages from iframe + else if (event.data.type === 'MESH_ERROR' && event.data.error) { + console.error('[GeomPack VTK Textured] Error from viewer:', event.data.error); + if (infoPanel) { + infoPanel.innerHTML = `
Error: ${event.data.error}
`; + } + } + }); + + // Set initial node size (increased for info panel) + this.setSize([512, 640]); + + // Handle execution + const onExecuted = this.onExecuted; + this.onExecuted = function(message) { + onExecuted?.apply(this, arguments); + + // The message IS the UI data (not message.ui) + if (message?.mesh_file && message.mesh_file[0]) { + const filename = message.mesh_file[0]; + + // Update mesh info panel with metadata + const vertices = message.vertex_count?.[0] || 'N/A'; + const faces = message.face_count?.[0] || 'N/A'; + const boundsMin = message.bounds_min?.[0] || []; + const boundsMax = message.bounds_max?.[0] || []; + const extents = message.extents?.[0] || []; + + // Texture/material info + const hasTexture = message.has_texture?.[0] || false; + const hasVertexColors = message.has_vertex_colors?.[0] || false; + const hasMaterial = message.has_material?.[0] || false; + const visualKind = message.visual_kind?.[0] || 'none'; + + // Format bounds + let boundsStr = 'N/A'; + if (boundsMin.length === 3 && boundsMax.length === 3) { + boundsStr = `[${boundsMin.map(v => v.toFixed(2)).join(', ')}] to [${boundsMax.map(v => v.toFixed(2)).join(', ')}]`; + } + + // Format extents + let extentsStr = 'N/A'; + if (extents.length === 3) { + extentsStr = `${extents.map(v => v.toFixed(2)).join(' x ')}`; + } + + // Build info HTML + let infoHTML = ` +
+ Vertices: + ${vertices.toLocaleString()} + + Faces: + ${faces.toLocaleString()} + + Bounds: + ${boundsStr} + + Extents: + ${extentsStr} + + Visual Type: + ${visualKind} + + Texture: + ${hasTexture ? 'Yes' : 'No'} + + Vertex Colors: + ${hasVertexColors ? 'Yes' : 'No'} + + Material: + ${hasMaterial ? 'Yes' : 'No'} + `; + + // Add optional fields if available + if (message.is_watertight !== undefined) { + const watertight = message.is_watertight[0] ? 'Yes' : 'No'; + const color = message.is_watertight[0] ? '#6c6' : '#c66'; + infoHTML += ` + Watertight: + ${watertight} + `; + } + + infoHTML += '
'; + + infoPanel.innerHTML = infoHTML; + + // ComfyUI serves output files via /view API endpoint + const filepath = `/view?filename=${encodeURIComponent(filename)}&type=output&subfolder=`; + + // Prepare metadata to pass to viewer + const metadata = { + has_texture: hasTexture, + has_vertex_colors: hasVertexColors, + has_material: hasMaterial, + visual_kind: visualKind + }; + + // Function to send message + const sendMessage = () => { + if (iframe.contentWindow) { + iframe.contentWindow.postMessage({ + type: "LOAD_MESH", + filepath: filepath, + metadata: metadata, + timestamp: Date.now() + }, "*"); + } else { + console.error("[GeomPack VTK Textured] Iframe contentWindow not available"); + } + }; + + // Send message after iframe is loaded + if (iframeLoaded) { + sendMessage(); + } else { + setTimeout(sendMessage, 500); + } + } else { + console.log("[GeomPack VTK Textured] No mesh_file in message data. Keys:", Object.keys(message || {})); + } + }; + + return r; + }; + } + } +}); + +console.log("[GeomPack] VTK.js textured mesh preview extension registered"); diff --git a/javascript/js/pointcloud_preview_vtk.js b/javascript/js/pointcloud_preview_vtk.js new file mode 100644 index 00000000..57ef7f50 --- /dev/null +++ b/javascript/js/pointcloud_preview_vtk.js @@ -0,0 +1,112 @@ +/** + * VTK.js Point Cloud Preview Widget + * For point cloud visualization nodes (SAM3, DepthAnythingV3, etc.) + */ + +import { app } from "../../../scripts/app.js"; +import { EXTENSION_FOLDER, getViewerUrl } from "./utils/extensionFolder.js"; +import { createContainer, createIframe, createInfoPanel, createWidgetOptions } from "./utils/uiComponents.js"; +import { createViewerManager, createErrorHandler, buildViewUrl } from "./utils/postMessage.js"; + +const POINTCLOUD_NODES = ["SAM3D_PreviewPointCloud", "DA3_PreviewPointCloud"]; + +app.registerExtension({ + name: "comfy3d.pointcloud.vtk", + + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (POINTCLOUD_NODES.includes(nodeData.name)) { + + const onNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function() { + const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined; + + // Create container for viewer + info panel + const container = createContainer(); + + // Create iframe for VTK.js viewer + const iframe = createIframe(getViewerUrl("viewer_vtk")); + + // Create info panel + const infoPanel = createInfoPanel("Point cloud will appear after execution"); + + // Add iframe and info panel to container + container.appendChild(iframe); + container.appendChild(infoPanel); + + // Add widget + const widget = this.addDOMWidget("preview_vtk", "POINTCLOUD_PREVIEW_VTK", container, createWidgetOptions()); + widget.computeSize = () => [512, 580]; + + // Store references + this._vtkIframe = iframe; + this._infoPanel = infoPanel; + + // Create viewer manager + const viewerManager = createViewerManager(iframe, "[PointCloud VTK]"); + + // Listen for error messages + window.addEventListener('message', createErrorHandler(infoPanel, "[PointCloud VTK]")); + + // Set initial node size + this.setSize([512, 580]); + + return r; + }; + + // Handle execution + const onExecuted = nodeType.prototype.onExecuted; + nodeType.prototype.onExecuted = function(message) { + onExecuted?.apply(this, arguments); + + // Get file path from ui.file_path + let filePath = null; + if (message?.ui?.file_path) { + filePath = Array.isArray(message.ui.file_path) ? message.ui.file_path[0] : message.ui.file_path; + } else if (message?.file_path) { + filePath = Array.isArray(message.file_path) ? message.file_path[0] : message.file_path; + } + + if (filePath && filePath.trim() !== '') { + // Normalize path + filePath = filePath.replace(/\\/g, '/').trim(); + + // Build URL for ComfyUI view endpoint + const outputMatch = filePath.match(/(?:^|\/)(output|input)\/(.+)$/); + let url; + if (outputMatch) { + const [, type, relativePath] = outputMatch; + const pathParts = relativePath.split('/'); + const filename = pathParts.pop(); + const subfolder = pathParts.join('/'); + url = `/view?filename=${encodeURIComponent(filename)}&type=${type}&subfolder=${encodeURIComponent(subfolder)}`; + } else { + const filename = filePath.split('/').pop(); + url = `/view?filename=${encodeURIComponent(filename)}&type=output&subfolder=`; + } + + // Update info panel + if (this._infoPanel) { + const filename = filePath.split('/').pop(); + this._infoPanel.innerHTML = `File: ${filename}`; + } + + // Send message to iframe + if (this._vtkIframe?.contentWindow) { + const sendMessage = () => { + this._vtkIframe.contentWindow.postMessage({ + type: 'LOAD_MESH', + filepath: url + }, '*'); + }; + + if (this._vtkIframe.contentDocument?.readyState === 'complete') { + sendMessage(); + } else { + this._vtkIframe.addEventListener('load', () => setTimeout(sendMessage, 100), { once: true }); + } + } + } + }; + } + } +}); diff --git a/web_src/preview_mesh_batch_render.js b/javascript/js/preview_mesh_batch_render.js similarity index 100% rename from web_src/preview_mesh_batch_render.js rename to javascript/js/preview_mesh_batch_render.js diff --git a/web_src/preview_mesh_boundaries.js b/javascript/js/preview_mesh_boundaries.js similarity index 100% rename from web_src/preview_mesh_boundaries.js rename to javascript/js/preview_mesh_boundaries.js diff --git a/web_src/preview_mesh_multi_batch.js b/javascript/js/preview_mesh_multi_batch.js similarity index 100% rename from web_src/preview_mesh_multi_batch.js rename to javascript/js/preview_mesh_multi_batch.js diff --git a/web_src/preview_mesh_slicer.js b/javascript/js/preview_mesh_slicer.js similarity index 100% rename from web_src/preview_mesh_slicer.js rename to javascript/js/preview_mesh_slicer.js diff --git a/javascript/js/text_report.js b/javascript/js/text_report.js new file mode 100644 index 00000000..161239c3 --- /dev/null +++ b/javascript/js/text_report.js @@ -0,0 +1,185 @@ +/** + * ComfyUI GeomPack - Generic Text Report Renderer + * Collapsible info panel. Arrow toggle at top of box. + */ + +import { app } from "../../../scripts/app.js"; +import { buildTextReportHTML } from "./utils/analysisPanel.js"; + +const TEXT_REPORT_NODES = [ + // CADabra + "CADUltimateInspection", + // Analysis + "GeomPackMeshInfo", + "GeomPackMeshQuality", + "GeomPackDegenerateFaces", + "GeomPackConnectedComponents", + "GeomPackOpenEdges", + "GeomPackComputeCurvature", + "GeomPackSegmentByCurvature", + "GeomPackComputeFilletField", + "GeomPackSegmentPatches", + "GeomPackClusterFaces", + // Repair + "GeomPackFillHoles", + "GeomPackMeshFix", + "GeomPackCheckNormals", + "GeomPackFixNormals", + "GeomPackMeshRepair", + "GeomPackRemoveDegenerateFaces", + "GeomPackMergeVertices", + "GeomPackVisualizeNormals", + "GeomPackAddNormalsToPointCloud", + "GeomPackFixSelfIntersectionsByRemoval", + "GeomPackDetectSelfIntersections", + "GeomPackFixSelfIntersectionsByPerturbation", + "GeomPackRemeshSelfIntersections", + // Smoothing / Decimation (unified dispatcher front nodes — info forwarded + // from the hidden backend via the executed event's display_node) + "GeomPackSharpenMesh", + "GeomPackDecimateMesh", + // Remeshing + "GeomPackRemesh", + "GeomPackRemeshCGAL", + "GeomPackRemeshBlender", + "GeomPackRemeshGPU", + "RefineMesh", + "GeomPackEdgeFlip", + // Reconstruction + "GeomPackReconstructSurface", + "GeomPackAlphaWrap", + // Texture remeshing + "GeomPackTextureToGeometry", + "GeomPackDepthNormalsToMesh", + "GeomPackRemeshWithTexture", + // Boolean + "GeomPackBooleanCGAL", + "GeomPackBooleanBlender", + // Combine + "GeomPackCombineMeshes", + "GeomPackCombineMeshesBatch", + "GeomPackSplitByField", + // Transforms + "GeomPackTransformMesh", + "GeomPackNormalizeMeshToBBox", + // UV + "GeomPackUVUnwrap", + // Distance + "GeomPackPointToMeshDistance", + "GeomPackMeshToMeshDistance", + // IO + "GeomPackLoadMeshFBX", + "GeomPackLoadMeshBlend", + // CADabra + "CADEdgeAnalysis", + "CAD_Quality_Metrics", + "CADCurvature", + "CADSewFaces", + "CADCheckOverlappingFaces", + "CADSplitComponents", + "CADHealShape", + "CADFixDegenerateFaces", + "CADPrimitiveReconstruction", + "CADFaceAnalysis", + // MeshSegmenter + "MeshSegGenerateMasks", + "MeshSegLift2DTo3DLabels", + "MeshSegSmoothLabels", + "MeshSegApplyLabelsToMesh", +]; + +const TOGGLE_HEIGHT = 28; +const DEFAULT_CONTENT_HEIGHT = 60; + +app.registerExtension({ + name: "geompack.text_report", + + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (!TEXT_REPORT_NODES.includes(nodeData.name)) return; + + const onNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function() { + const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined; + + let expanded = false; + let contentHeight = DEFAULT_CONTENT_HEIGHT; + let widgetHeight = TOGGLE_HEIGHT; + const node = this; + + // --- Single container widget --- + const container = document.createElement("div"); + container.style.cssText = "background:#1a1a2e; border:1px solid #333; border-radius:4px; overflow:hidden; display:flex; flex-direction:column; height:100%;"; + + // Header bar (always visible, top of box) + const header = document.createElement("div"); + header.style.cssText = "display:flex; align-items:center; gap:6px; padding:2px 8px; cursor:pointer; user-select:none; font-size:11px; color:#888; flex-shrink:0;"; + + const arrow = document.createElement("span"); + arrow.style.cssText = "font-size:8px; display:inline-block; transition:transform 0.15s;"; + arrow.textContent = "\u25B6"; + + const label = document.createElement("span"); + label.textContent = "Info"; + + header.appendChild(arrow); + header.appendChild(label); + + // Content area (hidden when collapsed) + const content = document.createElement("div"); + content.style.cssText = "padding:6px 8px; border-top:1px solid #333; font-size:11px; color:#ccc; display:none; overflow-y:auto; flex:1; min-height:0;"; + + container.appendChild(header); + container.appendChild(content); + + // Use getMinHeight/getHeight — the API ComfyUI's DOMWidgetImpl actually reads + const widget = this.addDOMWidget("report_panel", "REPORT_PANEL", container, { + getValue() { return expanded ? "true" : "false"; }, + setValue(v) { if (v === "true") setExpanded(true); }, + getMinHeight: () => widgetHeight, + getHeight: () => widgetHeight, + }); + + // Force node to grow to fit the widget + requestAnimationFrame(() => { + node.setSize([node.size[0], node.computeSize()[1]]); + node.setDirtyCanvas(true, true); + }); + + function resize() { + widgetHeight = expanded ? TOGGLE_HEIGHT + contentHeight : TOGGLE_HEIGHT; + node.setSize([node.size[0], node.computeSize()[1]]); + node.setDirtyCanvas(true, true); + } + + function setExpanded(val) { + expanded = val; + content.style.display = expanded ? "block" : "none"; + arrow.style.transform = expanded ? "rotate(90deg)" : ""; + resize(); + } + + // Toggle click + header.addEventListener("click", () => { + setExpanded(!expanded); + }); + + // Execution results + const onExecuted = this.onExecuted; + this.onExecuted = function(message) { + onExecuted?.apply(this, arguments); + + if (message?.text && message.text.length > 0) { + const text = message.text[0]; + content.innerHTML = buildTextReportHTML(text); + + const firstLine = text.split("\n")[0].trim(); + if (firstLine) label.textContent = firstLine; + + resize(); + } + }; + + return r; + }; + } +}); diff --git a/javascript/js/ultimate_mesh_inspection.js b/javascript/js/ultimate_mesh_inspection.js new file mode 100644 index 00000000..318df2af --- /dev/null +++ b/javascript/js/ultimate_mesh_inspection.js @@ -0,0 +1,173 @@ +/** + * ComfyUI GeomPack - Ultimate Mesh Inspection + * Embedded VTK.js viewer + clickable statistics table. Every defect is baked as a + * scalar field on the exported VTP; clicking a stat row reloads the viewer with that + * field as the active scalar (selectedField), lighting it up. + */ + +import { app } from "../../../scripts/app.js"; + +// Auto-detect extension folder name (same trick as the other viewers). +const EXTENSION_FOLDER = (() => { + const url = import.meta.url; + const match = url.match(/\/extensions\/([^/]+)\//); + return match ? match[1] : "ComfyUI-GeometryPack"; +})(); + +app.registerExtension({ + name: "geompack.ultimate_mesh_inspection", + + async beforeRegisterNodeDef(nodeType, nodeData) { + if (nodeData.name !== "GeomPackUltimateMeshInspection") return; + + const onNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function () { + const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined; + const node = this; + node._umiFilename = null; + node._umiActiveField = null; + + const container = document.createElement("div"); + container.style.cssText = + "width:100%;height:100%;display:flex;flex-direction:column;background:#222;overflow:hidden;"; + + // --- title / status bar --- + const bar = document.createElement("div"); + bar.style.cssText = + "display:flex;align-items:center;gap:8px;padding:4px 8px;background:#1a1a1a;" + + "border-bottom:1px solid #444;font:11px monospace;color:#bbb;flex:0 0 auto;"; + const title = document.createElement("div"); + title.textContent = "Ultimate Mesh Inspection"; + title.style.cssText = "font-weight:bold;color:#9df;"; + const status = document.createElement("div"); + status.style.cssText = "flex:1;color:#888;text-align:right;"; + status.textContent = "(run to inspect)"; + const clearBtn = document.createElement("button"); + clearBtn.textContent = "clear highlight"; + clearBtn.style.cssText = + "font:10px monospace;padding:2px 6px;border:1px solid #555;border-radius:3px;" + + "background:#333;color:#ccc;cursor:pointer;"; + bar.appendChild(title); bar.appendChild(status); bar.appendChild(clearBtn); + + // --- vtk.js iframe viewer --- + const iframe = document.createElement("iframe"); + iframe.style.cssText = "width:100%;flex:1 1 0;min-height:0;border:none;background:#2a2a2a;"; + iframe.src = `/extensions/${EXTENSION_FOLDER}/viewer_vtk.html?v=` + Date.now(); + let iframeLoaded = false; + iframe.addEventListener("load", () => { iframeLoaded = true; }); + + // --- scrollable statistics table --- + const tableWrap = document.createElement("div"); + tableWrap.style.cssText = + "flex:0 0 auto;max-height:260px;overflow:auto;background:#1a1a1a;border-top:1px solid #444;" + + "font:11px monospace;color:#ccc;"; + const table = document.createElement("table"); + table.style.cssText = "width:100%;border-collapse:collapse;"; + tableWrap.appendChild(table); + + container.appendChild(bar); + container.appendChild(iframe); + container.appendChild(tableWrap); + + const widget = this.addDOMWidget("ultimate_inspection", "UMI", container, { + getValue() { return ""; }, setValue() {}, + }); + widget.computeSize = () => [520, 720]; + this.setSize([520, 720]); + + // --- helpers --- + const loadMesh = (selectedField, focus) => { + if (!node._umiFilename || !iframe.contentWindow) return; + const filepath = `/view?filename=${encodeURIComponent(node._umiFilename)}&type=output&subfolder=`; + iframe.contentWindow.postMessage({ + type: "LOAD_MESH", + filepath, + selectedField: selectedField || null, + timestamp: Date.now(), + }, "*"); + node._umiActiveField = selectedField || null; + // for "worst" rows: zoom the camera onto that single face after it loads + if (focus && focus.length === 3) { + setTimeout(() => { + iframe.contentWindow?.postMessage({ + type: "FOCUS_ON_POINT", point: focus, timestamp: Date.now(), + }, "*"); + }, 500); + } + }; + + clearBtn.addEventListener("click", () => { + loadMesh(null, null); + table.querySelectorAll("tr.umi-active").forEach(tr => tr.classList.remove("umi-active")); + }); + + const buildTable = (rows) => { + table.innerHTML = ""; + let curGroup = null; + rows.forEach((row) => { + if (row.group !== curGroup) { + curGroup = row.group; + const gtr = document.createElement("tr"); + const gtd = document.createElement("td"); + gtd.colSpan = 2; + gtd.textContent = curGroup; + gtd.style.cssText = + "padding:4px 8px 2px;color:#9df;font-weight:bold;border-top:1px solid #333;"; + gtr.appendChild(gtd); table.appendChild(gtr); + } + const tr = document.createElement("tr"); + const tdL = document.createElement("td"); + tdL.textContent = row.label; + tdL.style.cssText = "padding:2px 8px;color:#999;white-space:nowrap;"; + const tdV = document.createElement("td"); + tdV.textContent = row.value; + tdV.style.cssText = "padding:2px 8px;color:#eee;width:100%;"; + tr.appendChild(tdL); tr.appendChild(tdV); + if (row.field) { + tr.title = `highlight: ${row.field}`; + tr.style.cursor = "pointer"; + tdL.style.color = "#cfc"; + tr.addEventListener("mouseenter", () => { + if (!tr.classList.contains("umi-active")) tr.style.background = "#2c2c2c"; + }); + tr.addEventListener("mouseleave", () => { + if (!tr.classList.contains("umi-active")) tr.style.background = ""; + }); + tr.addEventListener("click", () => { + table.querySelectorAll("tr.umi-active").forEach(x => { + x.classList.remove("umi-active"); x.style.background = ""; + }); + tr.classList.add("umi-active"); + tr.style.background = "#264"; + loadMesh(row.field, row.focus); + }); + } + table.appendChild(tr); + }); + }; + + // --- on execute --- + const onExecuted = this.onExecuted; + this.onExecuted = function (message) { + onExecuted?.apply(this, arguments); + const rows = message?.report?.[0] || []; + buildTable(rows); + + const vc = message?.vertex_count?.[0] ?? 0; + const fc = message?.face_count?.[0] ?? 0; + const wt = message?.is_watertight?.[0]; + status.textContent = `V ${vc.toLocaleString?.() ?? vc} | F ${fc.toLocaleString?.() ?? fc} | ` + + `watertight ${wt ? "yes" : "no"} — click a green row to highlight`; + + const fn = message?.mesh_file?.[0]; + if (fn) { + node._umiFilename = fn; + const fire = () => loadMesh(null); + if (iframeLoaded) fire(); else setTimeout(fire, 600); + } + }; + + return r; + }; + }, +}); diff --git a/javascript/js/utils/analysisPanel.js b/javascript/js/utils/analysisPanel.js new file mode 100644 index 00000000..e0db3f1b --- /dev/null +++ b/javascript/js/utils/analysisPanel.js @@ -0,0 +1,296 @@ +/** + * Analysis panel utilities for mesh analysis nodes + * (Connected components, degenerate faces, open edges, self-intersections) + */ + +/** + * Build table header HTML + * @param {string[]} columns - Column headers + * @returns {string} HTML string + */ +export function buildTableHeader(columns) { + let html = ''; + for (const col of columns) { + const align = col.align || 'left'; + html += `${col.label}`; + } + html += ''; + return html; +} + +/** + * Build table row HTML + * @param {Object[]} cells - Cell data [{value, color, align}] + * @returns {string} HTML string + */ +export function buildTableRow(cells) { + let html = ''; + for (const cell of cells) { + const color = cell.color || '#ccc'; + const align = cell.align || 'left'; + const value = cell.value; + html += `${value}`; + } + html += ''; + return html; +} + +/** + * Build "and N more" row + * @param {number} remaining - Number of remaining items + * @param {number} colSpan - Number of columns to span + * @param {string} itemName - Name of items (e.g., "components", "faces") + * @returns {string} HTML string + */ +export function buildMoreRow(remaining, colSpan, itemName = "items") { + return ` + + ... and ${remaining} more ${itemName} + + `; +} + +/** + * Build connected components HTML + * @param {Object} meshData - Mesh component data + * @param {number} maxDisplay - Max components to display (default: 20) + * @returns {string} HTML string + */ +export function buildConnectedComponentsHTML(meshData, maxDisplay = 20) { + const { mesh_name, num_components, total_faces, total_vertices, components } = meshData; + + let html = '
'; + + // Header + html += `
`; + html += `${mesh_name}: ${num_components} component(s)`; + html += `
`; + + html += `
`; + html += `Total: ${total_vertices.toLocaleString()} verts, ${total_faces.toLocaleString()} faces`; + html += `
`; + + // Table + html += ``; + html += buildTableHeader([ + { label: '#', align: 'left' }, + { label: 'Faces', align: 'right' }, + { label: 'Vertices', align: 'right' } + ]); + + const displayComponents = components.slice(0, maxDisplay); + const maxFaces = Math.max(...components.map(c => c.faces)); + + for (const comp of displayComponents) { + const color = comp.faces === maxFaces ? '#6f6' : '#ccc'; + + html += buildTableRow([ + { value: comp.id, color: '#888', align: 'left' }, + { value: comp.faces.toLocaleString(), color: color, align: 'right' }, + { value: comp.vertices.toLocaleString(), color: '#ccc', align: 'right' } + ]); + + // Face indices for small components + if (comp.face_indices && comp.face_indices.length > 0) { + html += ``; + html += ``; + } + } + + if (components.length > maxDisplay) { + html += buildMoreRow(components.length - maxDisplay, 3, "components"); + } + + html += '
`; + html += `faces: ${comp.face_indices.join(', ')}`; + html += `
'; + return html; +} + +/** + * Build self-intersections HTML + * @param {Object} data - Self-intersection data + * @param {number} maxDisplay - Max faces to display (default: 20) + * @returns {string} HTML string + */ +export function buildSelfIntersectionsHTML(data, maxDisplay = 20) { + const { mesh_name, num_intersecting_faces, num_intersection_pairs, total_faces, total_vertices, has_cgal, faces } = data; + + let html = '
'; + + const statusColor = num_intersecting_faces === 0 ? '#6f6' : '#f66'; + const statusText = num_intersecting_faces === 0 ? 'Clean' : `${num_intersecting_faces} intersecting face(s)`; + + html += `
`; + html += `${mesh_name}: ${statusText}`; + html += `
`; + + if (!has_cgal) { + html += `
`; + html += `CGAL not available - results may be incomplete`; + html += `
`; + } + + if (num_intersecting_faces > 0) { + html += `
`; + html += `${num_intersection_pairs} intersection pair(s) detected`; + html += `
`; + + html += ``; + html += buildTableHeader([ + { label: 'Face', align: 'left' }, + { label: 'Vertices', align: 'left' } + ]); + + const displayFaces = faces.slice(0, maxDisplay); + for (const face of displayFaces) { + html += buildTableRow([ + { value: face.id, color: '#f66', align: 'left' }, + { value: `[${face.vertices.join(', ')}]`, color: '#888', align: 'left' } + ]); + } + + if (faces.length > maxDisplay) { + html += buildMoreRow(faces.length - maxDisplay, 2, "faces"); + } + + html += '
'; + } else { + html += `
`; + html += `Total: ${total_vertices.toLocaleString()} vertices, ${total_faces.toLocaleString()} faces`; + html += `
`; + } + + html += '
'; + return html; +} + +/** + * Build degenerate faces HTML + * @param {Object} data - Degenerate faces data + * @param {number} maxDisplay - Max faces to display (default: 20) + * @returns {string} HTML string + */ +export function buildDegenerateFacesHTML(data, maxDisplay = 20) { + const { mesh_name, num_degenerate, total_faces, total_vertices, faces } = data; + + let html = '
'; + + const statusColor = num_degenerate === 0 ? '#6f6' : '#f66'; + const statusText = num_degenerate === 0 ? 'Clean' : `${num_degenerate} degenerate face(s)`; + + html += `
`; + html += `${mesh_name}: ${statusText}`; + html += `
`; + + if (num_degenerate > 0 && faces && faces.length > 0) { + html += ``; + html += buildTableHeader([ + { label: 'Face', align: 'left' }, + { label: 'Type', align: 'left' }, + { label: 'Vertices', align: 'left' } + ]); + + const displayFaces = faces.slice(0, maxDisplay); + for (const face of displayFaces) { + html += buildTableRow([ + { value: face.id, color: '#f66', align: 'left' }, + { value: face.type || 'degenerate', color: '#888', align: 'left' }, + { value: `[${face.vertices.join(', ')}]`, color: '#888', align: 'left' } + ]); + } + + if (faces.length > maxDisplay) { + html += buildMoreRow(faces.length - maxDisplay, 3, "faces"); + } + + html += '
'; + } else { + html += `
`; + html += `Total: ${total_vertices.toLocaleString()} vertices, ${total_faces.toLocaleString()} faces`; + html += `
`; + } + + html += '
'; + return html; +} + +/** + * Build open edges HTML + * @param {Object} data - Open edges data + * @param {number} maxDisplay - Max edges to display (default: 20) + * @returns {string} HTML string + */ +export function buildOpenEdgesHTML(data, maxDisplay = 20) { + const { mesh_name, num_open_edges, total_faces, total_vertices, edges } = data; + + let html = '
'; + + const statusColor = num_open_edges === 0 ? '#6f6' : '#fc6'; + const statusText = num_open_edges === 0 ? 'Watertight' : `${num_open_edges} open edge(s)`; + + html += `
`; + html += `${mesh_name}: ${statusText}`; + html += `
`; + + if (num_open_edges > 0 && edges && edges.length > 0) { + html += ``; + html += buildTableHeader([ + { label: 'Edge', align: 'left' }, + { label: 'Vertices', align: 'left' } + ]); + + const displayEdges = edges.slice(0, maxDisplay); + for (let i = 0; i < displayEdges.length; i++) { + const edge = displayEdges[i]; + html += buildTableRow([ + { value: i, color: '#fc6', align: 'left' }, + { value: `[${edge.vertices.join(', ')}]`, color: '#888', align: 'left' } + ]); + } + + if (edges.length > maxDisplay) { + html += buildMoreRow(edges.length - maxDisplay, 2, "edges"); + } + + html += '
'; + } else { + html += `
`; + html += `Total: ${total_vertices.toLocaleString()} vertices, ${total_faces.toLocaleString()} faces`; + html += `
`; + } + + html += '
'; + return html; +} + +/** + * Calculate dynamic height for analysis panel based on content + * @param {number} numRows - Number of data rows + * @param {number} maxRows - Maximum rows before truncation (default: 20) + * @param {number} baseHeight - Base height for headers (default: 40) + * @param {number} rowHeight - Height per row (default: 16) + * @param {number} minHeight - Minimum panel height (default: 80) + * @param {number} maxHeight - Maximum panel height (default: 250) + * @returns {number} Panel height in pixels + */ +export function calculatePanelHeight(numRows, maxRows = 20, baseHeight = 40, rowHeight = 16, minHeight = 80, maxHeight = 250) { + const displayRows = Math.min(numRows, maxRows) + 3; // +3 for header rows + return Math.min(Math.max(minHeight, displayRows * rowHeight + baseHeight), maxHeight); +} + +/** + * Build text report HTML (for nodes that output plain text info/reports) + * @param {string} text - Plain text report + * @returns {string} HTML string with styling + */ +export function buildTextReportHTML(text) { + // Convert newlines to
, escape HTML + const escaped = text + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/\n/g, '
'); + + return `
${escaped}
`; +} diff --git a/javascript/js/utils/extensionFolder.js b/javascript/js/utils/extensionFolder.js new file mode 100644 index 00000000..10ed1731 --- /dev/null +++ b/javascript/js/utils/extensionFolder.js @@ -0,0 +1,19 @@ +/** + * Auto-detect extension folder name from import.meta.url + * Handles both ComfyUI-GeometryPack and comfyui-geometrypack (lowercase) + */ + +export const EXTENSION_FOLDER = (() => { + const url = import.meta.url; + const match = url.match(/\/extensions\/([^/]+)\//); + return match ? match[1] : "ComfyUI-GeometryPack"; +})(); + +/** + * Build a viewer URL with cache buster + * @param {string} viewerName - Name of the viewer HTML file (e.g., "viewer_vtk") + * @returns {string} Full URL with cache buster + */ +export function getViewerUrl(viewerName) { + return `/extensions/${EXTENSION_FOLDER}/${viewerName}.html?v=` + Date.now(); +} diff --git a/javascript/js/utils/formatting.js b/javascript/js/utils/formatting.js new file mode 100644 index 00000000..83e4a06c --- /dev/null +++ b/javascript/js/utils/formatting.js @@ -0,0 +1,290 @@ +/** + * Formatting utilities for mesh metadata display + */ + +/** + * Format bounds array as string + * @param {number[]} boundsMin - [x, y, z] minimum bounds + * @param {number[]} boundsMax - [x, y, z] maximum bounds + * @param {number} decimals - Number of decimal places (default: 2) + * @returns {string} Formatted bounds string or 'N/A' + */ +export function formatBounds(boundsMin, boundsMax, decimals = 2) { + if (!boundsMin || !boundsMax || boundsMin.length !== 3 || boundsMax.length !== 3) { + return 'N/A'; + } + const min = boundsMin.map(v => v.toFixed(decimals)).join(', '); + const max = boundsMax.map(v => v.toFixed(decimals)).join(', '); + return `[${min}] to [${max}]`; +} + +/** + * Format extents array as string + * @param {number[]} extents - [x, y, z] extents + * @param {number} decimals - Number of decimal places (default: 2) + * @returns {string} Formatted extents string or 'N/A' + */ +export function formatExtents(extents, decimals = 2) { + if (!extents || extents.length !== 3) { + return 'N/A'; + } + return extents.map(v => v.toFixed(decimals)).join(' x '); +} + +/** + * Format a {typeName: count} map as a sorted, human-readable string, e.g. + * "3 Planes, 2 Cylinders, 1 BSpline". + * @param {Object} counts + * @returns {string} Formatted string (empty string if counts is empty/missing) + */ +export function formatTypeCounts(counts) { + if (!counts) return ''; + return Object.entries(counts) + .sort((a, b) => b[1] - a[1]) + .map(([name, count]) => `${count} ${name}${count === 1 ? '' : 's'}`) + .join(', '); +} + +/** + * Get color for mode label + * @param {string} mode - Viewer mode (fields, texture, pbr) + * @returns {string} CSS color + */ +export function getModeColor(mode) { + switch (mode) { + case "texture (PBR)": + case "pbr": + return '#fc6'; + case "texture": + return '#c8c'; + default: + return '#6cc'; + } +} + +/** + * Get color for watertight status + * @param {boolean} isWatertight + * @returns {string} CSS color + */ +export function getWatertightColor(isWatertight) { + return isWatertight ? '#6c6' : '#c66'; +} + +/** + * Build mesh info HTML for single mesh viewer + * @param {Object} data - Mesh metadata + * @returns {string} HTML string + */ +export function buildMeshInfoHTML(data) { + const { + mode = "fields", + vertices = 'N/A', + faces = 'N/A', + boundsMin = [], + boundsMax = [], + extents = [], + avgEdge, + isWatertight, + fieldNames = [], + fieldRanges = [], + hasTexture, + hasVertexColors, + visualKind + } = data; + + const modeLabel = mode.charAt(0).toUpperCase() + mode.slice(1); + const modeColor = getModeColor(mode); + const boundsStr = formatBounds(boundsMin, boundsMax); + const extentsStr = formatExtents(extents); + + let html = ` +
+ Mode: + ${modeLabel} + + Vertices: + ${typeof vertices === 'number' ? vertices.toLocaleString() : vertices} + + Faces: + ${typeof faces === 'number' ? faces.toLocaleString() : faces} + + Bounds: + ${boundsStr} + + Extents: + ${extentsStr} + `; + + // Average edge length (mesh resolution) + if (avgEdge !== undefined && avgEdge !== null) { + const avgStr = (typeof avgEdge === 'number') + ? avgEdge.toLocaleString(undefined, { maximumSignificantDigits: 4 }) + : avgEdge; + html += ` + Avg edge: + ${avgStr} + `; + } + + // Watertight status + if (isWatertight !== undefined) { + const watertightText = isWatertight ? 'Yes' : 'No'; + const watertightColor = getWatertightColor(isWatertight); + html += ` + Watertight: + ${watertightText} + `; + } + + // Mode-specific info + if (mode === "texture" || mode === "pbr") { + if (visualKind !== undefined) { + html += ` + Visual Kind: + ${visualKind} + `; + } + if (hasTexture !== undefined) { + const texColor = hasTexture ? '#c8c' : '#888'; + html += ` + Textures: + ${hasTexture ? 'Yes' : 'No'} + `; + } + if (hasVertexColors !== undefined) { + html += ` + Vertex Colors: + ${hasVertexColors ? 'Yes' : 'No'} + `; + } + } else { + // Fields mode — annotate each field with its [min, max] value range + if (fieldNames && fieldNames.length > 0) { + const fmt = (n) => { + if (n == null || !isFinite(n)) return '?'; + if (Number.isInteger(n) && Math.abs(n) < 1e7) return String(n); + return Number(Number(n).toPrecision(4)).toString(); + }; + const ext = (i, which, v) => + `${fmt(v)}`; + const fields = fieldNames.map((name, i) => { + const r = fieldRanges && fieldRanges[i]; + return (r && r.length === 2) + ? `${name} [${ext(i, 'min', r[0])}, ${ext(i, 'max', r[1])}]` + : name; + }).join(', '); + html += ` + Fields: + ${fields} + `; + } else { + html += ` + Fields: + None + `; + } + } + + html += '
'; + return html; +} + +/** + * Build dual mesh info HTML for side-by-side comparison + * @param {Object} data - Dual mesh metadata + * @returns {string} HTML string + */ +export function buildDualMeshInfoHTML(data) { + const { + mode = "fields", + layout = "side_by_side", + mesh1 = {}, + mesh2 = {}, + commonFields = [] + } = data; + + const modeLabel = mode.charAt(0).toUpperCase() + mode.slice(1); + const modeColor = getModeColor(mode); + + const extentsStr1 = formatExtents(mesh1.extents); + const extentsStr2 = formatExtents(mesh2.extents); + + const layoutSuffix = layout === "overlay" ? " (Overlay)" : ""; + + let html = ` +
+ Mode: + ${modeLabel}${layoutSuffix} + + + Mesh 1 + Mesh 2 + + Vertices: + ${(mesh1.vertices || 'N/A').toLocaleString()} + ${(mesh2.vertices || 'N/A').toLocaleString()} + + Faces: + ${(mesh1.faces || 'N/A').toLocaleString()} + ${(mesh2.faces || 'N/A').toLocaleString()} + `; + + if (mesh1.faceTypes !== undefined && mesh2.faceTypes !== undefined) { + html += ` + Face types: + ${mesh1.faceTypes || 'n/a'} + ${mesh2.faceTypes || 'n/a'} + `; + } + if (mesh1.edgeTypes !== undefined && mesh2.edgeTypes !== undefined) { + html += ` + Edge types: + ${mesh1.edgeTypes || 'n/a'} + ${mesh2.edgeTypes || 'n/a'} + `; + } + + html += ` + Extents: + ${extentsStr1} + ${extentsStr2} + `; + + // Watertight info + if (mesh1.isWatertight !== undefined && mesh2.isWatertight !== undefined) { + const color1 = getWatertightColor(mesh1.isWatertight); + const color2 = getWatertightColor(mesh2.isWatertight); + html += ` + Watertight: + ${mesh1.isWatertight ? 'Yes' : 'No'} + ${mesh2.isWatertight ? 'Yes' : 'No'} + `; + } + + // Mode-specific info + if (mode === "texture") { + if (mesh1.hasTexture !== undefined) { + const tex1 = mesh1.hasTexture ? 'Yes' : 'No'; + const tex2 = mesh2.hasTexture ? 'Yes' : 'No'; + html += ` + Textures: + ${tex1} + ${tex2} + `; + } + } else { + // Fields mode + if (commonFields && commonFields.length > 0) { + html += ` + Fields: + ${commonFields.length} shared field(s) + `; + } + } + + html += '
'; + return html; +} diff --git a/javascript/js/utils/index.js b/javascript/js/utils/index.js new file mode 100644 index 00000000..a2b1baba --- /dev/null +++ b/javascript/js/utils/index.js @@ -0,0 +1,11 @@ +/** + * ComfyUI 3D Viewer Utilities + * Shared utilities for ComfyUI 3D viewer integration + */ + +export * from './extensionFolder.js'; +export * from './screenshot.js'; +export * from './uiComponents.js'; +export * from './formatting.js'; +export * from './analysisPanel.js'; +export * from './postMessage.js'; diff --git a/javascript/js/utils/postMessage.js b/javascript/js/utils/postMessage.js new file mode 100644 index 00000000..31e19c1c --- /dev/null +++ b/javascript/js/utils/postMessage.js @@ -0,0 +1,196 @@ +/** + * PostMessage utilities for iframe communication + */ + +/** + * Create a message sender function for an iframe + * @param {HTMLIFrameElement} iframe - The iframe element + * @param {string} logPrefix - Logging prefix (e.g., "[GeomPack VTK]") + * @returns {Function} Message sending function + */ +export function createMessageSender(iframe, logPrefix = "[Viewer]") { + return (data) => { + if (iframe.contentWindow) { + iframe.contentWindow.postMessage(data, "*"); + } else { + console.error(`${logPrefix} Iframe contentWindow not available`); + } + }; +} + +/** + * Create a mesh load message + * @param {string} filepath - URL path to the mesh file + * @returns {Object} Message data object + */ +export function createLoadMeshMessage(filepath) { + return { + type: "LOAD_MESH", + filepath: filepath, + timestamp: Date.now() + }; +} + +/** + * Create a dual mesh load message + * @param {Object} options - Message options + * @returns {Object} Message data object + */ +export function createLoadDualMeshMessage(options) { + const { + layout, + mesh1Filepath, + mesh2Filepath, + meshFilepath, // For overlay mode + opacity1 = 1.0, + opacity2 = 1.0, + showEdges = false, + cameraState = "", + selectedField = "", + selectedChannel = "magnitude", + selectedColormap = "erdc_rainbow_bright", + } = options; + + return { + type: 'LOAD_DUAL_MESH', + layout: layout, + mesh1Filepath, + mesh2Filepath, + meshFilepath, + opacity1, + opacity2, + showEdges, + cameraState, + selectedField, + selectedChannel, + selectedColormap, + timestamp: Date.now() + }; +} + +/** + * Build ComfyUI view API URL for a file. + * Handles absolute paths (/home/.../output/sub/file.glb), + * relative paths (output/sub/file.glb), and bare filenames (file.glb). + * @param {string} filename - The filename or path + * @param {string} defaultType - Default file type (default: "output") + * @param {string} defaultSubfolder - Default subfolder path (default: "") + * @returns {string} API URL + */ +export function buildViewUrl(filename, defaultType = "output", defaultSubfolder = "") { + const normalized = filename.replace(/\\/g, '/'); + const pathMatch = normalized.match(/(?:^|\/)(output|input|temp)\/(.+)$/); + if (pathMatch) { + const [, type, relPath] = pathMatch; + const parts = relPath.split('/'); + const fname = parts.pop(); + const subfolder = parts.join('/'); + return `/view?filename=${encodeURIComponent(fname)}&type=${type}&subfolder=${encodeURIComponent(subfolder)}`; + } + // Bare filename fallback + const basename = normalized.split('/').pop(); + return `/view?filename=${encodeURIComponent(basename)}&type=${defaultType}&subfolder=${defaultSubfolder}`; +} + +/** + * Create an iframe viewer manager for handling viewer switching + * @param {HTMLIFrameElement} iframe - The iframe element + * @param {string} logPrefix - Logging prefix + * @returns {Object} Viewer manager object + */ +export function createViewerManager(iframe, logPrefix = "[Viewer]") { + let currentViewerType = null; + let iframeLoaded = false; + let pendingMessage = null; + + // Track iframe load state + iframe.addEventListener('load', () => { + iframeLoaded = true; + // Send pending message if any + if (pendingMessage && iframe.contentWindow) { + iframe.contentWindow.postMessage(pendingMessage, "*"); + pendingMessage = null; + } + }); + + return { + /** + * Get current viewer type + * @returns {string|null} + */ + getCurrentType() { + return currentViewerType; + }, + + /** + * Check if iframe is loaded + * @returns {boolean} + */ + isLoaded() { + return iframeLoaded; + }, + + /** + * Send a message to the iframe viewer + * If iframe is not loaded yet, queue the message + * @param {Object} data - Message data + */ + sendMessage(data) { + if (iframeLoaded && iframe.contentWindow) { + iframe.contentWindow.postMessage(data, "*"); + } else { + pendingMessage = data; + } + }, + + /** + * Switch to a different viewer type if needed + * @param {string} viewerType - New viewer type + * @param {string} viewerUrl - URL of the new viewer + * @param {Object} messageData - Message to send after viewer loads + * @returns {boolean} True if viewer was switched, false if already on correct viewer + */ + switchViewer(viewerType, viewerUrl, messageData) { + if (viewerType === currentViewerType) { + // No switch needed, just send message + this.sendMessage(messageData); + return false; + } + + // Viewer switch needed + currentViewerType = viewerType; + iframeLoaded = false; + pendingMessage = messageData; + + // Change iframe src to trigger reload + iframe.src = viewerUrl + "?v=" + Date.now(); + return true; + }, + + /** + * Reset the manager state + */ + reset() { + currentViewerType = null; + iframeLoaded = false; + pendingMessage = null; + } + }; +} + +/** + * Create an error message handler for iframe errors + * @param {HTMLElement} infoPanel - The info panel to display errors + * @param {string} logPrefix - Logging prefix + * @returns {Function} Event handler function + */ +export function createErrorHandler(infoPanel, logPrefix = "[Viewer]") { + return (event) => { + if (event.data.type === 'MESH_ERROR' && event.data.error) { + console.error(`${logPrefix} Error from viewer:`, event.data.error); + if (infoPanel) { + infoPanel.innerHTML = `
Error: ${event.data.error}
`; + } + } + }; +} diff --git a/javascript/js/utils/screenshot.js b/javascript/js/utils/screenshot.js new file mode 100644 index 00000000..2b9d09e4 --- /dev/null +++ b/javascript/js/utils/screenshot.js @@ -0,0 +1,71 @@ +/** + * Screenshot capture and upload utility for ComfyUI viewers + */ + +/** + * Convert base64 data URL to Blob + * @param {string} dataUrl - Base64 data URL (e.g., "data:image/png;base64,...") + * @returns {Blob} PNG image blob + */ +export function dataUrlToBlob(dataUrl) { + const base64Data = dataUrl.split(',')[1]; + const byteString = atob(base64Data); + const arrayBuffer = new ArrayBuffer(byteString.length); + const uint8Array = new Uint8Array(arrayBuffer); + + for (let i = 0; i < byteString.length; i++) { + uint8Array[i] = byteString.charCodeAt(i); + } + + return new Blob([uint8Array], { type: 'image/png' }); +} + +/** + * Upload screenshot to ComfyUI backend + * @param {string} dataUrl - Base64 data URL of the screenshot + * @param {string} prefix - Filename prefix (e.g., "vtk-screenshot") + * @returns {Promise<{name: string, subfolder: string, type: string}>} Upload result + */ +export async function uploadScreenshot(dataUrl, prefix = 'screenshot') { + const blob = dataUrlToBlob(dataUrl); + + // Generate filename with timestamp + const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); + const filename = `${prefix}-${timestamp}.png`; + + // Create FormData for upload + const formData = new FormData(); + formData.append('image', blob, filename); + formData.append('type', 'output'); // Save to output directory + formData.append('subfolder', ''); // Root of output folder + + // Upload to ComfyUI backend + const response = await fetch('/upload/image', { + method: 'POST', + body: formData + }); + + if (!response.ok) { + throw new Error(`Upload failed: ${response.status} ${response.statusText}`); + } + + return response.json(); +} + +/** + * Create a message handler for screenshot events from iframe + * @param {string} prefix - Filename prefix for screenshots + * @param {Function} onError - Error callback + * @returns {Function} Event handler function + */ +export function createScreenshotHandler(prefix = 'screenshot', onError = console.error) { + return async (event) => { + if (event.data.type === 'SCREENSHOT' && event.data.image) { + try { + await uploadScreenshot(event.data.image, prefix); + } catch (error) { + onError(`Error saving screenshot: ${error}`); + } + } + }; +} diff --git a/javascript/js/utils/uiComponents.js b/javascript/js/utils/uiComponents.js new file mode 100644 index 00000000..c6b5bd75 --- /dev/null +++ b/javascript/js/utils/uiComponents.js @@ -0,0 +1,133 @@ +/** + * UI component factory functions for ComfyUI 3D viewer widgets + */ + +/** + * Create a container div for viewer + info panel + * @param {Object} options - Container options + * @param {string} options.backgroundColor - Background color (default: "#2a2a2a") + * @returns {HTMLDivElement} Container element + */ +export function createContainer(options = {}) { + const { backgroundColor = "#2a2a2a" } = options; + + const container = document.createElement("div"); + container.style.width = "100%"; + container.style.height = "100%"; + container.style.display = "flex"; + container.style.flexDirection = "column"; + container.style.backgroundColor = backgroundColor; + container.style.overflow = "hidden"; + + return container; +} + +/** + * Create an iframe for embedding a viewer + * @param {string} src - Initial iframe source URL + * @param {Object} options - Iframe options + * @param {string} options.minHeight - Minimum height (default: "0") + * @param {string} options.backgroundColor - Background color (default: "#2a2a2a") + * @returns {HTMLIFrameElement} Iframe element + */ +export function createIframe(src, options = {}) { + const { + minHeight = "0", + backgroundColor = "#2a2a2a" + } = options; + + const iframe = document.createElement("iframe"); + iframe.style.width = "100%"; + iframe.style.flex = "1 1 0"; + iframe.style.minHeight = minHeight; + iframe.style.border = "none"; + iframe.style.backgroundColor = backgroundColor; + iframe.src = src; + + return iframe; +} + +/** + * Create an info panel for displaying mesh metadata + * @param {string} placeholder - Initial placeholder text + * @param {Object} options - Panel options + * @returns {HTMLDivElement} Info panel element + */ +export function createInfoPanel(placeholder = "Info will appear here after execution", options = {}) { + const { + backgroundColor = "#1a1a1a", + borderTop = "1px solid #444", + padding = "6px 12px", + fontSize = "10px", + fontFamily = "monospace", + color = "#ccc", + lineHeight = "1.3" + } = options; + + const infoPanel = document.createElement("div"); + infoPanel.style.backgroundColor = backgroundColor; + infoPanel.style.borderTop = borderTop; + infoPanel.style.padding = padding; + infoPanel.style.fontSize = fontSize; + infoPanel.style.fontFamily = fontFamily; + infoPanel.style.color = color; + infoPanel.style.lineHeight = lineHeight; + infoPanel.style.flexShrink = "0"; + infoPanel.style.overflow = "hidden"; + infoPanel.innerHTML = `${placeholder}`; + + return infoPanel; +} + +/** + * Create an analysis info panel (for connected components, self-intersections, etc.) + * @param {string} placeholder - Initial placeholder text + * @param {Object} options - Panel options + * @returns {HTMLDivElement} Analysis panel element + */ +export function createAnalysisPanel(placeholder = "Run workflow to see results", options = {}) { + const { + backgroundColor = "#1a1a1a", + padding = "8px", + fontSize = "10px", + fontFamily = "monospace", + color = "#ccc", + lineHeight = "1.4", + maxHeight = "200px", + borderRadius = "4px" + } = options; + + const panel = document.createElement("div"); + panel.style.backgroundColor = backgroundColor; + panel.style.padding = padding; + panel.style.fontSize = fontSize; + panel.style.fontFamily = fontFamily; + panel.style.color = color; + panel.style.lineHeight = lineHeight; + panel.style.maxHeight = maxHeight; + panel.style.overflowY = "auto"; + panel.style.borderRadius = borderRadius; + panel.innerHTML = `${placeholder}`; + + return panel; +} + +/** + * Show error in an info panel + * @param {HTMLElement} panel - The info panel element + * @param {string} message - Error message + */ +export function showPanelError(panel, message) { + panel.innerHTML = `
Error: ${message}
`; +} + +/** + * Create default widget options + * @returns {Object} Widget options object + */ +export function createWidgetOptions() { + return { + getValue() { return ""; }, + setValue(v) { } + }; +} diff --git a/javascript/js/viewer-bundle-three.js b/javascript/js/viewer-bundle-three.js new file mode 100644 index 00000000..7be31ad0 --- /dev/null +++ b/javascript/js/viewer-bundle-three.js @@ -0,0 +1,37242 @@ +var UniRigViewer = (() => { + var __defProp = Object.defineProperty; + var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); + }; + + // three.module.js + var three_module_exports = {}; + __export(three_module_exports, { + ACESFilmicToneMapping: () => ACESFilmicToneMapping, + AddEquation: () => AddEquation, + AddOperation: () => AddOperation, + AdditiveAnimationBlendMode: () => AdditiveAnimationBlendMode, + AdditiveBlending: () => AdditiveBlending, + AgXToneMapping: () => AgXToneMapping, + AlphaFormat: () => AlphaFormat, + AlwaysCompare: () => AlwaysCompare, + AlwaysDepth: () => AlwaysDepth, + AlwaysStencilFunc: () => AlwaysStencilFunc, + AmbientLight: () => AmbientLight, + AnimationAction: () => AnimationAction, + AnimationClip: () => AnimationClip, + AnimationLoader: () => AnimationLoader, + AnimationMixer: () => AnimationMixer, + AnimationObjectGroup: () => AnimationObjectGroup, + AnimationUtils: () => AnimationUtils, + ArcCurve: () => ArcCurve, + ArrayCamera: () => ArrayCamera, + ArrowHelper: () => ArrowHelper, + AttachedBindMode: () => AttachedBindMode, + Audio: () => Audio, + AudioAnalyser: () => AudioAnalyser, + AudioContext: () => AudioContext, + AudioListener: () => AudioListener, + AudioLoader: () => AudioLoader, + AxesHelper: () => AxesHelper, + BackSide: () => BackSide, + BasicDepthPacking: () => BasicDepthPacking, + BasicShadowMap: () => BasicShadowMap, + BatchedMesh: () => BatchedMesh, + Bone: () => Bone, + BooleanKeyframeTrack: () => BooleanKeyframeTrack, + Box2: () => Box2, + Box3: () => Box3, + Box3Helper: () => Box3Helper, + BoxGeometry: () => BoxGeometry, + BoxHelper: () => BoxHelper, + BufferAttribute: () => BufferAttribute, + BufferGeometry: () => BufferGeometry, + BufferGeometryLoader: () => BufferGeometryLoader, + ByteType: () => ByteType, + Cache: () => Cache, + Camera: () => Camera, + CameraHelper: () => CameraHelper, + CanvasTexture: () => CanvasTexture, + CapsuleGeometry: () => CapsuleGeometry, + CatmullRomCurve3: () => CatmullRomCurve3, + CineonToneMapping: () => CineonToneMapping, + CircleGeometry: () => CircleGeometry, + ClampToEdgeWrapping: () => ClampToEdgeWrapping, + Clock: () => Clock, + Color: () => Color, + ColorKeyframeTrack: () => ColorKeyframeTrack, + ColorManagement: () => ColorManagement, + CompressedArrayTexture: () => CompressedArrayTexture, + CompressedCubeTexture: () => CompressedCubeTexture, + CompressedTexture: () => CompressedTexture, + CompressedTextureLoader: () => CompressedTextureLoader, + ConeGeometry: () => ConeGeometry, + ConstantAlphaFactor: () => ConstantAlphaFactor, + ConstantColorFactor: () => ConstantColorFactor, + CubeCamera: () => CubeCamera, + CubeReflectionMapping: () => CubeReflectionMapping, + CubeRefractionMapping: () => CubeRefractionMapping, + CubeTexture: () => CubeTexture, + CubeTextureLoader: () => CubeTextureLoader, + CubeUVReflectionMapping: () => CubeUVReflectionMapping, + CubicBezierCurve: () => CubicBezierCurve, + CubicBezierCurve3: () => CubicBezierCurve3, + CubicInterpolant: () => CubicInterpolant, + CullFaceBack: () => CullFaceBack, + CullFaceFront: () => CullFaceFront, + CullFaceFrontBack: () => CullFaceFrontBack, + CullFaceNone: () => CullFaceNone, + Curve: () => Curve, + CurvePath: () => CurvePath, + CustomBlending: () => CustomBlending, + CustomToneMapping: () => CustomToneMapping, + CylinderGeometry: () => CylinderGeometry, + Cylindrical: () => Cylindrical, + Data3DTexture: () => Data3DTexture, + DataArrayTexture: () => DataArrayTexture, + DataTexture: () => DataTexture, + DataTextureLoader: () => DataTextureLoader, + DataUtils: () => DataUtils, + DecrementStencilOp: () => DecrementStencilOp, + DecrementWrapStencilOp: () => DecrementWrapStencilOp, + DefaultLoadingManager: () => DefaultLoadingManager, + DepthFormat: () => DepthFormat, + DepthStencilFormat: () => DepthStencilFormat, + DepthTexture: () => DepthTexture, + DetachedBindMode: () => DetachedBindMode, + DirectionalLight: () => DirectionalLight, + DirectionalLightHelper: () => DirectionalLightHelper, + DiscreteInterpolant: () => DiscreteInterpolant, + DisplayP3ColorSpace: () => DisplayP3ColorSpace, + DodecahedronGeometry: () => DodecahedronGeometry, + DoubleSide: () => DoubleSide, + DstAlphaFactor: () => DstAlphaFactor, + DstColorFactor: () => DstColorFactor, + DynamicCopyUsage: () => DynamicCopyUsage, + DynamicDrawUsage: () => DynamicDrawUsage, + DynamicReadUsage: () => DynamicReadUsage, + EdgesGeometry: () => EdgesGeometry, + EllipseCurve: () => EllipseCurve, + EqualCompare: () => EqualCompare, + EqualDepth: () => EqualDepth, + EqualStencilFunc: () => EqualStencilFunc, + EquirectangularReflectionMapping: () => EquirectangularReflectionMapping, + EquirectangularRefractionMapping: () => EquirectangularRefractionMapping, + Euler: () => Euler, + EventDispatcher: () => EventDispatcher, + ExtrudeGeometry: () => ExtrudeGeometry, + FileLoader: () => FileLoader, + Float16BufferAttribute: () => Float16BufferAttribute, + Float32BufferAttribute: () => Float32BufferAttribute, + Float64BufferAttribute: () => Float64BufferAttribute, + FloatType: () => FloatType, + Fog: () => Fog, + FogExp2: () => FogExp2, + FramebufferTexture: () => FramebufferTexture, + FrontSide: () => FrontSide, + Frustum: () => Frustum, + GLBufferAttribute: () => GLBufferAttribute, + GLSL1: () => GLSL1, + GLSL3: () => GLSL3, + GreaterCompare: () => GreaterCompare, + GreaterDepth: () => GreaterDepth, + GreaterEqualCompare: () => GreaterEqualCompare, + GreaterEqualDepth: () => GreaterEqualDepth, + GreaterEqualStencilFunc: () => GreaterEqualStencilFunc, + GreaterStencilFunc: () => GreaterStencilFunc, + GridHelper: () => GridHelper, + Group: () => Group, + HalfFloatType: () => HalfFloatType, + HemisphereLight: () => HemisphereLight, + HemisphereLightHelper: () => HemisphereLightHelper, + IcosahedronGeometry: () => IcosahedronGeometry, + ImageBitmapLoader: () => ImageBitmapLoader, + ImageLoader: () => ImageLoader, + ImageUtils: () => ImageUtils, + IncrementStencilOp: () => IncrementStencilOp, + IncrementWrapStencilOp: () => IncrementWrapStencilOp, + InstancedBufferAttribute: () => InstancedBufferAttribute, + InstancedBufferGeometry: () => InstancedBufferGeometry, + InstancedInterleavedBuffer: () => InstancedInterleavedBuffer, + InstancedMesh: () => InstancedMesh, + Int16BufferAttribute: () => Int16BufferAttribute, + Int32BufferAttribute: () => Int32BufferAttribute, + Int8BufferAttribute: () => Int8BufferAttribute, + IntType: () => IntType, + InterleavedBuffer: () => InterleavedBuffer, + InterleavedBufferAttribute: () => InterleavedBufferAttribute, + Interpolant: () => Interpolant, + InterpolateDiscrete: () => InterpolateDiscrete, + InterpolateLinear: () => InterpolateLinear, + InterpolateSmooth: () => InterpolateSmooth, + InvertStencilOp: () => InvertStencilOp, + KeepStencilOp: () => KeepStencilOp, + KeyframeTrack: () => KeyframeTrack, + LOD: () => LOD, + LatheGeometry: () => LatheGeometry, + Layers: () => Layers, + LessCompare: () => LessCompare, + LessDepth: () => LessDepth, + LessEqualCompare: () => LessEqualCompare, + LessEqualDepth: () => LessEqualDepth, + LessEqualStencilFunc: () => LessEqualStencilFunc, + LessStencilFunc: () => LessStencilFunc, + Light: () => Light, + LightProbe: () => LightProbe, + Line: () => Line, + Line3: () => Line3, + LineBasicMaterial: () => LineBasicMaterial, + LineCurve: () => LineCurve, + LineCurve3: () => LineCurve3, + LineDashedMaterial: () => LineDashedMaterial, + LineLoop: () => LineLoop, + LineSegments: () => LineSegments, + LinearDisplayP3ColorSpace: () => LinearDisplayP3ColorSpace, + LinearEncoding: () => LinearEncoding, + LinearFilter: () => LinearFilter, + LinearInterpolant: () => LinearInterpolant, + LinearMipMapLinearFilter: () => LinearMipMapLinearFilter, + LinearMipMapNearestFilter: () => LinearMipMapNearestFilter, + LinearMipmapLinearFilter: () => LinearMipmapLinearFilter, + LinearMipmapNearestFilter: () => LinearMipmapNearestFilter, + LinearSRGBColorSpace: () => LinearSRGBColorSpace, + LinearToneMapping: () => LinearToneMapping, + LinearTransfer: () => LinearTransfer, + Loader: () => Loader, + LoaderUtils: () => LoaderUtils, + LoadingManager: () => LoadingManager, + LoopOnce: () => LoopOnce, + LoopPingPong: () => LoopPingPong, + LoopRepeat: () => LoopRepeat, + LuminanceAlphaFormat: () => LuminanceAlphaFormat, + LuminanceFormat: () => LuminanceFormat, + MOUSE: () => MOUSE, + Material: () => Material, + MaterialLoader: () => MaterialLoader, + MathUtils: () => MathUtils, + Matrix3: () => Matrix3, + Matrix4: () => Matrix4, + MaxEquation: () => MaxEquation, + Mesh: () => Mesh, + MeshBasicMaterial: () => MeshBasicMaterial, + MeshDepthMaterial: () => MeshDepthMaterial, + MeshDistanceMaterial: () => MeshDistanceMaterial, + MeshLambertMaterial: () => MeshLambertMaterial, + MeshMatcapMaterial: () => MeshMatcapMaterial, + MeshNormalMaterial: () => MeshNormalMaterial, + MeshPhongMaterial: () => MeshPhongMaterial, + MeshPhysicalMaterial: () => MeshPhysicalMaterial, + MeshStandardMaterial: () => MeshStandardMaterial, + MeshToonMaterial: () => MeshToonMaterial, + MinEquation: () => MinEquation, + MirroredRepeatWrapping: () => MirroredRepeatWrapping, + MixOperation: () => MixOperation, + MultiplyBlending: () => MultiplyBlending, + MultiplyOperation: () => MultiplyOperation, + NearestFilter: () => NearestFilter, + NearestMipMapLinearFilter: () => NearestMipMapLinearFilter, + NearestMipMapNearestFilter: () => NearestMipMapNearestFilter, + NearestMipmapLinearFilter: () => NearestMipmapLinearFilter, + NearestMipmapNearestFilter: () => NearestMipmapNearestFilter, + NeverCompare: () => NeverCompare, + NeverDepth: () => NeverDepth, + NeverStencilFunc: () => NeverStencilFunc, + NoBlending: () => NoBlending, + NoColorSpace: () => NoColorSpace, + NoToneMapping: () => NoToneMapping, + NormalAnimationBlendMode: () => NormalAnimationBlendMode, + NormalBlending: () => NormalBlending, + NotEqualCompare: () => NotEqualCompare, + NotEqualDepth: () => NotEqualDepth, + NotEqualStencilFunc: () => NotEqualStencilFunc, + NumberKeyframeTrack: () => NumberKeyframeTrack, + Object3D: () => Object3D, + ObjectLoader: () => ObjectLoader, + ObjectSpaceNormalMap: () => ObjectSpaceNormalMap, + OctahedronGeometry: () => OctahedronGeometry, + OneFactor: () => OneFactor, + OneMinusConstantAlphaFactor: () => OneMinusConstantAlphaFactor, + OneMinusConstantColorFactor: () => OneMinusConstantColorFactor, + OneMinusDstAlphaFactor: () => OneMinusDstAlphaFactor, + OneMinusDstColorFactor: () => OneMinusDstColorFactor, + OneMinusSrcAlphaFactor: () => OneMinusSrcAlphaFactor, + OneMinusSrcColorFactor: () => OneMinusSrcColorFactor, + OrthographicCamera: () => OrthographicCamera, + P3Primaries: () => P3Primaries, + PCFShadowMap: () => PCFShadowMap, + PCFSoftShadowMap: () => PCFSoftShadowMap, + PMREMGenerator: () => PMREMGenerator, + Path: () => Path, + PerspectiveCamera: () => PerspectiveCamera, + Plane: () => Plane, + PlaneGeometry: () => PlaneGeometry, + PlaneHelper: () => PlaneHelper, + PointLight: () => PointLight, + PointLightHelper: () => PointLightHelper, + Points: () => Points, + PointsMaterial: () => PointsMaterial, + PolarGridHelper: () => PolarGridHelper, + PolyhedronGeometry: () => PolyhedronGeometry, + PositionalAudio: () => PositionalAudio, + PropertyBinding: () => PropertyBinding, + PropertyMixer: () => PropertyMixer, + QuadraticBezierCurve: () => QuadraticBezierCurve, + QuadraticBezierCurve3: () => QuadraticBezierCurve3, + Quaternion: () => Quaternion, + QuaternionKeyframeTrack: () => QuaternionKeyframeTrack, + QuaternionLinearInterpolant: () => QuaternionLinearInterpolant, + RED_GREEN_RGTC2_Format: () => RED_GREEN_RGTC2_Format, + RED_RGTC1_Format: () => RED_RGTC1_Format, + REVISION: () => REVISION, + RGBADepthPacking: () => RGBADepthPacking, + RGBAFormat: () => RGBAFormat, + RGBAIntegerFormat: () => RGBAIntegerFormat, + RGBA_ASTC_10x10_Format: () => RGBA_ASTC_10x10_Format, + RGBA_ASTC_10x5_Format: () => RGBA_ASTC_10x5_Format, + RGBA_ASTC_10x6_Format: () => RGBA_ASTC_10x6_Format, + RGBA_ASTC_10x8_Format: () => RGBA_ASTC_10x8_Format, + RGBA_ASTC_12x10_Format: () => RGBA_ASTC_12x10_Format, + RGBA_ASTC_12x12_Format: () => RGBA_ASTC_12x12_Format, + RGBA_ASTC_4x4_Format: () => RGBA_ASTC_4x4_Format, + RGBA_ASTC_5x4_Format: () => RGBA_ASTC_5x4_Format, + RGBA_ASTC_5x5_Format: () => RGBA_ASTC_5x5_Format, + RGBA_ASTC_6x5_Format: () => RGBA_ASTC_6x5_Format, + RGBA_ASTC_6x6_Format: () => RGBA_ASTC_6x6_Format, + RGBA_ASTC_8x5_Format: () => RGBA_ASTC_8x5_Format, + RGBA_ASTC_8x6_Format: () => RGBA_ASTC_8x6_Format, + RGBA_ASTC_8x8_Format: () => RGBA_ASTC_8x8_Format, + RGBA_BPTC_Format: () => RGBA_BPTC_Format, + RGBA_ETC2_EAC_Format: () => RGBA_ETC2_EAC_Format, + RGBA_PVRTC_2BPPV1_Format: () => RGBA_PVRTC_2BPPV1_Format, + RGBA_PVRTC_4BPPV1_Format: () => RGBA_PVRTC_4BPPV1_Format, + RGBA_S3TC_DXT1_Format: () => RGBA_S3TC_DXT1_Format, + RGBA_S3TC_DXT3_Format: () => RGBA_S3TC_DXT3_Format, + RGBA_S3TC_DXT5_Format: () => RGBA_S3TC_DXT5_Format, + RGB_BPTC_SIGNED_Format: () => RGB_BPTC_SIGNED_Format, + RGB_BPTC_UNSIGNED_Format: () => RGB_BPTC_UNSIGNED_Format, + RGB_ETC1_Format: () => RGB_ETC1_Format, + RGB_ETC2_Format: () => RGB_ETC2_Format, + RGB_PVRTC_2BPPV1_Format: () => RGB_PVRTC_2BPPV1_Format, + RGB_PVRTC_4BPPV1_Format: () => RGB_PVRTC_4BPPV1_Format, + RGB_S3TC_DXT1_Format: () => RGB_S3TC_DXT1_Format, + RGFormat: () => RGFormat, + RGIntegerFormat: () => RGIntegerFormat, + RawShaderMaterial: () => RawShaderMaterial, + Ray: () => Ray, + Raycaster: () => Raycaster, + Rec709Primaries: () => Rec709Primaries, + RectAreaLight: () => RectAreaLight, + RedFormat: () => RedFormat, + RedIntegerFormat: () => RedIntegerFormat, + ReinhardToneMapping: () => ReinhardToneMapping, + RenderTarget: () => RenderTarget, + RepeatWrapping: () => RepeatWrapping, + ReplaceStencilOp: () => ReplaceStencilOp, + ReverseSubtractEquation: () => ReverseSubtractEquation, + RingGeometry: () => RingGeometry, + SIGNED_RED_GREEN_RGTC2_Format: () => SIGNED_RED_GREEN_RGTC2_Format, + SIGNED_RED_RGTC1_Format: () => SIGNED_RED_RGTC1_Format, + SRGBColorSpace: () => SRGBColorSpace, + SRGBTransfer: () => SRGBTransfer, + Scene: () => Scene, + ShaderChunk: () => ShaderChunk, + ShaderLib: () => ShaderLib, + ShaderMaterial: () => ShaderMaterial, + ShadowMaterial: () => ShadowMaterial, + Shape: () => Shape, + ShapeGeometry: () => ShapeGeometry, + ShapePath: () => ShapePath, + ShapeUtils: () => ShapeUtils, + ShortType: () => ShortType, + Skeleton: () => Skeleton, + SkeletonHelper: () => SkeletonHelper, + SkinnedMesh: () => SkinnedMesh, + Source: () => Source, + Sphere: () => Sphere, + SphereGeometry: () => SphereGeometry, + Spherical: () => Spherical, + SphericalHarmonics3: () => SphericalHarmonics3, + SplineCurve: () => SplineCurve, + SpotLight: () => SpotLight, + SpotLightHelper: () => SpotLightHelper, + Sprite: () => Sprite, + SpriteMaterial: () => SpriteMaterial, + SrcAlphaFactor: () => SrcAlphaFactor, + SrcAlphaSaturateFactor: () => SrcAlphaSaturateFactor, + SrcColorFactor: () => SrcColorFactor, + StaticCopyUsage: () => StaticCopyUsage, + StaticDrawUsage: () => StaticDrawUsage, + StaticReadUsage: () => StaticReadUsage, + StereoCamera: () => StereoCamera, + StreamCopyUsage: () => StreamCopyUsage, + StreamDrawUsage: () => StreamDrawUsage, + StreamReadUsage: () => StreamReadUsage, + StringKeyframeTrack: () => StringKeyframeTrack, + SubtractEquation: () => SubtractEquation, + SubtractiveBlending: () => SubtractiveBlending, + TOUCH: () => TOUCH, + TangentSpaceNormalMap: () => TangentSpaceNormalMap, + TetrahedronGeometry: () => TetrahedronGeometry, + Texture: () => Texture, + TextureLoader: () => TextureLoader, + TorusGeometry: () => TorusGeometry, + TorusKnotGeometry: () => TorusKnotGeometry, + Triangle: () => Triangle, + TriangleFanDrawMode: () => TriangleFanDrawMode, + TriangleStripDrawMode: () => TriangleStripDrawMode, + TrianglesDrawMode: () => TrianglesDrawMode, + TubeGeometry: () => TubeGeometry, + TwoPassDoubleSide: () => TwoPassDoubleSide, + UVMapping: () => UVMapping, + Uint16BufferAttribute: () => Uint16BufferAttribute, + Uint32BufferAttribute: () => Uint32BufferAttribute, + Uint8BufferAttribute: () => Uint8BufferAttribute, + Uint8ClampedBufferAttribute: () => Uint8ClampedBufferAttribute, + Uniform: () => Uniform, + UniformsGroup: () => UniformsGroup, + UniformsLib: () => UniformsLib, + UniformsUtils: () => UniformsUtils, + UnsignedByteType: () => UnsignedByteType, + UnsignedInt248Type: () => UnsignedInt248Type, + UnsignedIntType: () => UnsignedIntType, + UnsignedShort4444Type: () => UnsignedShort4444Type, + UnsignedShort5551Type: () => UnsignedShort5551Type, + UnsignedShortType: () => UnsignedShortType, + VSMShadowMap: () => VSMShadowMap, + Vector2: () => Vector2, + Vector3: () => Vector3, + Vector4: () => Vector4, + VectorKeyframeTrack: () => VectorKeyframeTrack, + VideoTexture: () => VideoTexture, + WebGL1Renderer: () => WebGL1Renderer, + WebGL3DRenderTarget: () => WebGL3DRenderTarget, + WebGLArrayRenderTarget: () => WebGLArrayRenderTarget, + WebGLCoordinateSystem: () => WebGLCoordinateSystem, + WebGLCubeRenderTarget: () => WebGLCubeRenderTarget, + WebGLMultipleRenderTargets: () => WebGLMultipleRenderTargets, + WebGLRenderTarget: () => WebGLRenderTarget, + WebGLRenderer: () => WebGLRenderer, + WebGLUtils: () => WebGLUtils, + WebGPUCoordinateSystem: () => WebGPUCoordinateSystem, + WireframeGeometry: () => WireframeGeometry, + WrapAroundEnding: () => WrapAroundEnding, + ZeroCurvatureEnding: () => ZeroCurvatureEnding, + ZeroFactor: () => ZeroFactor, + ZeroSlopeEnding: () => ZeroSlopeEnding, + ZeroStencilOp: () => ZeroStencilOp, + _SRGBAFormat: () => _SRGBAFormat, + createCanvasElement: () => createCanvasElement, + sRGBEncoding: () => sRGBEncoding + }); + var REVISION = "160"; + var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; + var TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; + var CullFaceNone = 0; + var CullFaceBack = 1; + var CullFaceFront = 2; + var CullFaceFrontBack = 3; + var BasicShadowMap = 0; + var PCFShadowMap = 1; + var PCFSoftShadowMap = 2; + var VSMShadowMap = 3; + var FrontSide = 0; + var BackSide = 1; + var DoubleSide = 2; + var TwoPassDoubleSide = 2; + var NoBlending = 0; + var NormalBlending = 1; + var AdditiveBlending = 2; + var SubtractiveBlending = 3; + var MultiplyBlending = 4; + var CustomBlending = 5; + var AddEquation = 100; + var SubtractEquation = 101; + var ReverseSubtractEquation = 102; + var MinEquation = 103; + var MaxEquation = 104; + var ZeroFactor = 200; + var OneFactor = 201; + var SrcColorFactor = 202; + var OneMinusSrcColorFactor = 203; + var SrcAlphaFactor = 204; + var OneMinusSrcAlphaFactor = 205; + var DstAlphaFactor = 206; + var OneMinusDstAlphaFactor = 207; + var DstColorFactor = 208; + var OneMinusDstColorFactor = 209; + var SrcAlphaSaturateFactor = 210; + var ConstantColorFactor = 211; + var OneMinusConstantColorFactor = 212; + var ConstantAlphaFactor = 213; + var OneMinusConstantAlphaFactor = 214; + var NeverDepth = 0; + var AlwaysDepth = 1; + var LessDepth = 2; + var LessEqualDepth = 3; + var EqualDepth = 4; + var GreaterEqualDepth = 5; + var GreaterDepth = 6; + var NotEqualDepth = 7; + var MultiplyOperation = 0; + var MixOperation = 1; + var AddOperation = 2; + var NoToneMapping = 0; + var LinearToneMapping = 1; + var ReinhardToneMapping = 2; + var CineonToneMapping = 3; + var ACESFilmicToneMapping = 4; + var CustomToneMapping = 5; + var AgXToneMapping = 6; + var AttachedBindMode = "attached"; + var DetachedBindMode = "detached"; + var UVMapping = 300; + var CubeReflectionMapping = 301; + var CubeRefractionMapping = 302; + var EquirectangularReflectionMapping = 303; + var EquirectangularRefractionMapping = 304; + var CubeUVReflectionMapping = 306; + var RepeatWrapping = 1e3; + var ClampToEdgeWrapping = 1001; + var MirroredRepeatWrapping = 1002; + var NearestFilter = 1003; + var NearestMipmapNearestFilter = 1004; + var NearestMipMapNearestFilter = 1004; + var NearestMipmapLinearFilter = 1005; + var NearestMipMapLinearFilter = 1005; + var LinearFilter = 1006; + var LinearMipmapNearestFilter = 1007; + var LinearMipMapNearestFilter = 1007; + var LinearMipmapLinearFilter = 1008; + var LinearMipMapLinearFilter = 1008; + var UnsignedByteType = 1009; + var ByteType = 1010; + var ShortType = 1011; + var UnsignedShortType = 1012; + var IntType = 1013; + var UnsignedIntType = 1014; + var FloatType = 1015; + var HalfFloatType = 1016; + var UnsignedShort4444Type = 1017; + var UnsignedShort5551Type = 1018; + var UnsignedInt248Type = 1020; + var AlphaFormat = 1021; + var RGBAFormat = 1023; + var LuminanceFormat = 1024; + var LuminanceAlphaFormat = 1025; + var DepthFormat = 1026; + var DepthStencilFormat = 1027; + var RedFormat = 1028; + var RedIntegerFormat = 1029; + var RGFormat = 1030; + var RGIntegerFormat = 1031; + var RGBAIntegerFormat = 1033; + var RGB_S3TC_DXT1_Format = 33776; + var RGBA_S3TC_DXT1_Format = 33777; + var RGBA_S3TC_DXT3_Format = 33778; + var RGBA_S3TC_DXT5_Format = 33779; + var RGB_PVRTC_4BPPV1_Format = 35840; + var RGB_PVRTC_2BPPV1_Format = 35841; + var RGBA_PVRTC_4BPPV1_Format = 35842; + var RGBA_PVRTC_2BPPV1_Format = 35843; + var RGB_ETC1_Format = 36196; + var RGB_ETC2_Format = 37492; + var RGBA_ETC2_EAC_Format = 37496; + var RGBA_ASTC_4x4_Format = 37808; + var RGBA_ASTC_5x4_Format = 37809; + var RGBA_ASTC_5x5_Format = 37810; + var RGBA_ASTC_6x5_Format = 37811; + var RGBA_ASTC_6x6_Format = 37812; + var RGBA_ASTC_8x5_Format = 37813; + var RGBA_ASTC_8x6_Format = 37814; + var RGBA_ASTC_8x8_Format = 37815; + var RGBA_ASTC_10x5_Format = 37816; + var RGBA_ASTC_10x6_Format = 37817; + var RGBA_ASTC_10x8_Format = 37818; + var RGBA_ASTC_10x10_Format = 37819; + var RGBA_ASTC_12x10_Format = 37820; + var RGBA_ASTC_12x12_Format = 37821; + var RGBA_BPTC_Format = 36492; + var RGB_BPTC_SIGNED_Format = 36494; + var RGB_BPTC_UNSIGNED_Format = 36495; + var RED_RGTC1_Format = 36283; + var SIGNED_RED_RGTC1_Format = 36284; + var RED_GREEN_RGTC2_Format = 36285; + var SIGNED_RED_GREEN_RGTC2_Format = 36286; + var LoopOnce = 2200; + var LoopRepeat = 2201; + var LoopPingPong = 2202; + var InterpolateDiscrete = 2300; + var InterpolateLinear = 2301; + var InterpolateSmooth = 2302; + var ZeroCurvatureEnding = 2400; + var ZeroSlopeEnding = 2401; + var WrapAroundEnding = 2402; + var NormalAnimationBlendMode = 2500; + var AdditiveAnimationBlendMode = 2501; + var TrianglesDrawMode = 0; + var TriangleStripDrawMode = 1; + var TriangleFanDrawMode = 2; + var LinearEncoding = 3e3; + var sRGBEncoding = 3001; + var BasicDepthPacking = 3200; + var RGBADepthPacking = 3201; + var TangentSpaceNormalMap = 0; + var ObjectSpaceNormalMap = 1; + var NoColorSpace = ""; + var SRGBColorSpace = "srgb"; + var LinearSRGBColorSpace = "srgb-linear"; + var DisplayP3ColorSpace = "display-p3"; + var LinearDisplayP3ColorSpace = "display-p3-linear"; + var LinearTransfer = "linear"; + var SRGBTransfer = "srgb"; + var Rec709Primaries = "rec709"; + var P3Primaries = "p3"; + var ZeroStencilOp = 0; + var KeepStencilOp = 7680; + var ReplaceStencilOp = 7681; + var IncrementStencilOp = 7682; + var DecrementStencilOp = 7683; + var IncrementWrapStencilOp = 34055; + var DecrementWrapStencilOp = 34056; + var InvertStencilOp = 5386; + var NeverStencilFunc = 512; + var LessStencilFunc = 513; + var EqualStencilFunc = 514; + var LessEqualStencilFunc = 515; + var GreaterStencilFunc = 516; + var NotEqualStencilFunc = 517; + var GreaterEqualStencilFunc = 518; + var AlwaysStencilFunc = 519; + var NeverCompare = 512; + var LessCompare = 513; + var EqualCompare = 514; + var LessEqualCompare = 515; + var GreaterCompare = 516; + var NotEqualCompare = 517; + var GreaterEqualCompare = 518; + var AlwaysCompare = 519; + var StaticDrawUsage = 35044; + var DynamicDrawUsage = 35048; + var StreamDrawUsage = 35040; + var StaticReadUsage = 35045; + var DynamicReadUsage = 35049; + var StreamReadUsage = 35041; + var StaticCopyUsage = 35046; + var DynamicCopyUsage = 35050; + var StreamCopyUsage = 35042; + var GLSL1 = "100"; + var GLSL3 = "300 es"; + var _SRGBAFormat = 1035; + var WebGLCoordinateSystem = 2e3; + var WebGPUCoordinateSystem = 2001; + var EventDispatcher = class { + addEventListener(type, listener) { + if (this._listeners === void 0) this._listeners = {}; + const listeners = this._listeners; + if (listeners[type] === void 0) { + listeners[type] = []; + } + if (listeners[type].indexOf(listener) === -1) { + listeners[type].push(listener); + } + } + hasEventListener(type, listener) { + if (this._listeners === void 0) return false; + const listeners = this._listeners; + return listeners[type] !== void 0 && listeners[type].indexOf(listener) !== -1; + } + removeEventListener(type, listener) { + if (this._listeners === void 0) return; + const listeners = this._listeners; + const listenerArray = listeners[type]; + if (listenerArray !== void 0) { + const index = listenerArray.indexOf(listener); + if (index !== -1) { + listenerArray.splice(index, 1); + } + } + } + dispatchEvent(event) { + if (this._listeners === void 0) return; + const listeners = this._listeners; + const listenerArray = listeners[event.type]; + if (listenerArray !== void 0) { + event.target = this; + const array = listenerArray.slice(0); + for (let i = 0, l = array.length; i < l; i++) { + array[i].call(this, event); + } + event.target = null; + } + } + }; + var _lut = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"]; + var _seed = 1234567; + var DEG2RAD = Math.PI / 180; + var RAD2DEG = 180 / Math.PI; + function generateUUID() { + const d0 = Math.random() * 4294967295 | 0; + const d1 = Math.random() * 4294967295 | 0; + const d2 = Math.random() * 4294967295 | 0; + const d3 = Math.random() * 4294967295 | 0; + const uuid = _lut[d0 & 255] + _lut[d0 >> 8 & 255] + _lut[d0 >> 16 & 255] + _lut[d0 >> 24 & 255] + "-" + _lut[d1 & 255] + _lut[d1 >> 8 & 255] + "-" + _lut[d1 >> 16 & 15 | 64] + _lut[d1 >> 24 & 255] + "-" + _lut[d2 & 63 | 128] + _lut[d2 >> 8 & 255] + "-" + _lut[d2 >> 16 & 255] + _lut[d2 >> 24 & 255] + _lut[d3 & 255] + _lut[d3 >> 8 & 255] + _lut[d3 >> 16 & 255] + _lut[d3 >> 24 & 255]; + return uuid.toLowerCase(); + } + function clamp(value, min, max2) { + return Math.max(min, Math.min(max2, value)); + } + function euclideanModulo(n, m) { + return (n % m + m) % m; + } + function mapLinear(x, a1, a2, b1, b2) { + return b1 + (x - a1) * (b2 - b1) / (a2 - a1); + } + function inverseLerp(x, y, value) { + if (x !== y) { + return (value - x) / (y - x); + } else { + return 0; + } + } + function lerp(x, y, t) { + return (1 - t) * x + t * y; + } + function damp(x, y, lambda, dt) { + return lerp(x, y, 1 - Math.exp(-lambda * dt)); + } + function pingpong(x, length = 1) { + return length - Math.abs(euclideanModulo(x, length * 2) - length); + } + function smoothstep(x, min, max2) { + if (x <= min) return 0; + if (x >= max2) return 1; + x = (x - min) / (max2 - min); + return x * x * (3 - 2 * x); + } + function smootherstep(x, min, max2) { + if (x <= min) return 0; + if (x >= max2) return 1; + x = (x - min) / (max2 - min); + return x * x * x * (x * (x * 6 - 15) + 10); + } + function randInt(low, high) { + return low + Math.floor(Math.random() * (high - low + 1)); + } + function randFloat(low, high) { + return low + Math.random() * (high - low); + } + function randFloatSpread(range) { + return range * (0.5 - Math.random()); + } + function seededRandom(s) { + if (s !== void 0) _seed = s; + let t = _seed += 1831565813; + t = Math.imul(t ^ t >>> 15, t | 1); + t ^= t + Math.imul(t ^ t >>> 7, t | 61); + return ((t ^ t >>> 14) >>> 0) / 4294967296; + } + function degToRad(degrees) { + return degrees * DEG2RAD; + } + function radToDeg(radians) { + return radians * RAD2DEG; + } + function isPowerOfTwo(value) { + return (value & value - 1) === 0 && value !== 0; + } + function ceilPowerOfTwo(value) { + return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2)); + } + function floorPowerOfTwo(value) { + return Math.pow(2, Math.floor(Math.log(value) / Math.LN2)); + } + function setQuaternionFromProperEuler(q, a, b, c, order) { + const cos = Math.cos; + const sin = Math.sin; + const c2 = cos(b / 2); + const s2 = sin(b / 2); + const c13 = cos((a + c) / 2); + const s13 = sin((a + c) / 2); + const c1_3 = cos((a - c) / 2); + const s1_3 = sin((a - c) / 2); + const c3_1 = cos((c - a) / 2); + const s3_1 = sin((c - a) / 2); + switch (order) { + case "XYX": + q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13); + break; + case "YZY": + q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13); + break; + case "ZXZ": + q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13); + break; + case "XZX": + q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13); + break; + case "YXY": + q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13); + break; + case "ZYZ": + q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13); + break; + default: + console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: " + order); + } + } + function denormalize(value, array) { + switch (array.constructor) { + case Float32Array: + return value; + case Uint32Array: + return value / 4294967295; + case Uint16Array: + return value / 65535; + case Uint8Array: + return value / 255; + case Int32Array: + return Math.max(value / 2147483647, -1); + case Int16Array: + return Math.max(value / 32767, -1); + case Int8Array: + return Math.max(value / 127, -1); + default: + throw new Error("Invalid component type."); + } + } + function normalize(value, array) { + switch (array.constructor) { + case Float32Array: + return value; + case Uint32Array: + return Math.round(value * 4294967295); + case Uint16Array: + return Math.round(value * 65535); + case Uint8Array: + return Math.round(value * 255); + case Int32Array: + return Math.round(value * 2147483647); + case Int16Array: + return Math.round(value * 32767); + case Int8Array: + return Math.round(value * 127); + default: + throw new Error("Invalid component type."); + } + } + var MathUtils = { + DEG2RAD, + RAD2DEG, + generateUUID, + clamp, + euclideanModulo, + mapLinear, + inverseLerp, + lerp, + damp, + pingpong, + smoothstep, + smootherstep, + randInt, + randFloat, + randFloatSpread, + seededRandom, + degToRad, + radToDeg, + isPowerOfTwo, + ceilPowerOfTwo, + floorPowerOfTwo, + setQuaternionFromProperEuler, + normalize, + denormalize + }; + var Vector2 = class _Vector2 { + constructor(x = 0, y = 0) { + _Vector2.prototype.isVector2 = true; + this.x = x; + this.y = y; + } + get width() { + return this.x; + } + set width(value) { + this.x = value; + } + get height() { + return this.y; + } + set height(value) { + this.y = value; + } + set(x, y) { + this.x = x; + this.y = y; + return this; + } + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + return this; + } + setX(x) { + this.x = x; + return this; + } + setY(y) { + this.y = y; + return this; + } + setComponent(index, value) { + switch (index) { + case 0: + this.x = value; + break; + case 1: + this.y = value; + break; + default: + throw new Error("index is out of range: " + index); + } + return this; + } + getComponent(index) { + switch (index) { + case 0: + return this.x; + case 1: + return this.y; + default: + throw new Error("index is out of range: " + index); + } + } + clone() { + return new this.constructor(this.x, this.y); + } + copy(v) { + this.x = v.x; + this.y = v.y; + return this; + } + add(v) { + this.x += v.x; + this.y += v.y; + return this; + } + addScalar(s) { + this.x += s; + this.y += s; + return this; + } + addVectors(a, b) { + this.x = a.x + b.x; + this.y = a.y + b.y; + return this; + } + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + return this; + } + sub(v) { + this.x -= v.x; + this.y -= v.y; + return this; + } + subScalar(s) { + this.x -= s; + this.y -= s; + return this; + } + subVectors(a, b) { + this.x = a.x - b.x; + this.y = a.y - b.y; + return this; + } + multiply(v) { + this.x *= v.x; + this.y *= v.y; + return this; + } + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + return this; + } + divide(v) { + this.x /= v.x; + this.y /= v.y; + return this; + } + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + applyMatrix3(m) { + const x = this.x, y = this.y; + const e = m.elements; + this.x = e[0] * x + e[3] * y + e[6]; + this.y = e[1] * x + e[4] * y + e[7]; + return this; + } + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + return this; + } + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + return this; + } + clamp(min, max2) { + this.x = Math.max(min.x, Math.min(max2.x, this.x)); + this.y = Math.max(min.y, Math.min(max2.y, this.y)); + return this; + } + clampScalar(minVal, maxVal) { + this.x = Math.max(minVal, Math.min(maxVal, this.x)); + this.y = Math.max(minVal, Math.min(maxVal, this.y)); + return this; + } + clampLength(min, max2) { + const length = this.length(); + return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max2, length))); + } + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + return this; + } + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + return this; + } + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + return this; + } + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + return this; + } + negate() { + this.x = -this.x; + this.y = -this.y; + return this; + } + dot(v) { + return this.x * v.x + this.y * v.y; + } + cross(v) { + return this.x * v.y - this.y * v.x; + } + lengthSq() { + return this.x * this.x + this.y * this.y; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y); + } + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y); + } + normalize() { + return this.divideScalar(this.length() || 1); + } + angle() { + const angle = Math.atan2(-this.y, -this.x) + Math.PI; + return angle; + } + angleTo(v) { + const denominator = Math.sqrt(this.lengthSq() * v.lengthSq()); + if (denominator === 0) return Math.PI / 2; + const theta = this.dot(v) / denominator; + return Math.acos(clamp(theta, -1, 1)); + } + distanceTo(v) { + return Math.sqrt(this.distanceToSquared(v)); + } + distanceToSquared(v) { + const dx = this.x - v.x, dy = this.y - v.y; + return dx * dx + dy * dy; + } + manhattanDistanceTo(v) { + return Math.abs(this.x - v.x) + Math.abs(this.y - v.y); + } + setLength(length) { + return this.normalize().multiplyScalar(length); + } + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + return this; + } + lerpVectors(v1, v2, alpha) { + this.x = v1.x + (v2.x - v1.x) * alpha; + this.y = v1.y + (v2.y - v1.y) * alpha; + return this; + } + equals(v) { + return v.x === this.x && v.y === this.y; + } + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + return array; + } + fromBufferAttribute(attribute, index) { + this.x = attribute.getX(index); + this.y = attribute.getY(index); + return this; + } + rotateAround(center, angle) { + const c = Math.cos(angle), s = Math.sin(angle); + const x = this.x - center.x; + const y = this.y - center.y; + this.x = x * c - y * s + center.x; + this.y = x * s + y * c + center.y; + return this; + } + random() { + this.x = Math.random(); + this.y = Math.random(); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + } + }; + var Matrix3 = class _Matrix3 { + constructor(n11, n12, n13, n21, n22, n23, n31, n32, n33) { + _Matrix3.prototype.isMatrix3 = true; + this.elements = [ + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1 + ]; + if (n11 !== void 0) { + this.set(n11, n12, n13, n21, n22, n23, n31, n32, n33); + } + } + set(n11, n12, n13, n21, n22, n23, n31, n32, n33) { + const te = this.elements; + te[0] = n11; + te[1] = n21; + te[2] = n31; + te[3] = n12; + te[4] = n22; + te[5] = n32; + te[6] = n13; + te[7] = n23; + te[8] = n33; + return this; + } + identity() { + this.set( + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1 + ); + return this; + } + copy(m) { + const te = this.elements; + const me = m.elements; + te[0] = me[0]; + te[1] = me[1]; + te[2] = me[2]; + te[3] = me[3]; + te[4] = me[4]; + te[5] = me[5]; + te[6] = me[6]; + te[7] = me[7]; + te[8] = me[8]; + return this; + } + extractBasis(xAxis, yAxis, zAxis) { + xAxis.setFromMatrix3Column(this, 0); + yAxis.setFromMatrix3Column(this, 1); + zAxis.setFromMatrix3Column(this, 2); + return this; + } + setFromMatrix4(m) { + const me = m.elements; + this.set( + me[0], + me[4], + me[8], + me[1], + me[5], + me[9], + me[2], + me[6], + me[10] + ); + return this; + } + multiply(m) { + return this.multiplyMatrices(this, m); + } + premultiply(m) { + return this.multiplyMatrices(m, this); + } + multiplyMatrices(a, b) { + const ae = a.elements; + const be = b.elements; + const te = this.elements; + const a11 = ae[0], a12 = ae[3], a13 = ae[6]; + const a21 = ae[1], a22 = ae[4], a23 = ae[7]; + const a31 = ae[2], a32 = ae[5], a33 = ae[8]; + const b11 = be[0], b12 = be[3], b13 = be[6]; + const b21 = be[1], b22 = be[4], b23 = be[7]; + const b31 = be[2], b32 = be[5], b33 = be[8]; + te[0] = a11 * b11 + a12 * b21 + a13 * b31; + te[3] = a11 * b12 + a12 * b22 + a13 * b32; + te[6] = a11 * b13 + a12 * b23 + a13 * b33; + te[1] = a21 * b11 + a22 * b21 + a23 * b31; + te[4] = a21 * b12 + a22 * b22 + a23 * b32; + te[7] = a21 * b13 + a22 * b23 + a23 * b33; + te[2] = a31 * b11 + a32 * b21 + a33 * b31; + te[5] = a31 * b12 + a32 * b22 + a33 * b32; + te[8] = a31 * b13 + a32 * b23 + a33 * b33; + return this; + } + multiplyScalar(s) { + const te = this.elements; + te[0] *= s; + te[3] *= s; + te[6] *= s; + te[1] *= s; + te[4] *= s; + te[7] *= s; + te[2] *= s; + te[5] *= s; + te[8] *= s; + return this; + } + determinant() { + const te = this.elements; + const a = te[0], b = te[1], c = te[2], d = te[3], e = te[4], f = te[5], g = te[6], h = te[7], i = te[8]; + return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; + } + invert() { + const te = this.elements, n11 = te[0], n21 = te[1], n31 = te[2], n12 = te[3], n22 = te[4], n32 = te[5], n13 = te[6], n23 = te[7], n33 = te[8], t11 = n33 * n22 - n32 * n23, t12 = n32 * n13 - n33 * n12, t13 = n23 * n12 - n22 * n13, det = n11 * t11 + n21 * t12 + n31 * t13; + if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0); + const detInv = 1 / det; + te[0] = t11 * detInv; + te[1] = (n31 * n23 - n33 * n21) * detInv; + te[2] = (n32 * n21 - n31 * n22) * detInv; + te[3] = t12 * detInv; + te[4] = (n33 * n11 - n31 * n13) * detInv; + te[5] = (n31 * n12 - n32 * n11) * detInv; + te[6] = t13 * detInv; + te[7] = (n21 * n13 - n23 * n11) * detInv; + te[8] = (n22 * n11 - n21 * n12) * detInv; + return this; + } + transpose() { + let tmp2; + const m = this.elements; + tmp2 = m[1]; + m[1] = m[3]; + m[3] = tmp2; + tmp2 = m[2]; + m[2] = m[6]; + m[6] = tmp2; + tmp2 = m[5]; + m[5] = m[7]; + m[7] = tmp2; + return this; + } + getNormalMatrix(matrix4) { + return this.setFromMatrix4(matrix4).invert().transpose(); + } + transposeIntoArray(r) { + const m = this.elements; + r[0] = m[0]; + r[1] = m[3]; + r[2] = m[6]; + r[3] = m[1]; + r[4] = m[4]; + r[5] = m[7]; + r[6] = m[2]; + r[7] = m[5]; + r[8] = m[8]; + return this; + } + setUvTransform(tx, ty, sx, sy, rotation, cx, cy) { + const c = Math.cos(rotation); + const s = Math.sin(rotation); + this.set( + sx * c, + sx * s, + -sx * (c * cx + s * cy) + cx + tx, + -sy * s, + sy * c, + -sy * (-s * cx + c * cy) + cy + ty, + 0, + 0, + 1 + ); + return this; + } + // + scale(sx, sy) { + this.premultiply(_m3.makeScale(sx, sy)); + return this; + } + rotate(theta) { + this.premultiply(_m3.makeRotation(-theta)); + return this; + } + translate(tx, ty) { + this.premultiply(_m3.makeTranslation(tx, ty)); + return this; + } + // for 2D Transforms + makeTranslation(x, y) { + if (x.isVector2) { + this.set( + 1, + 0, + x.x, + 0, + 1, + x.y, + 0, + 0, + 1 + ); + } else { + this.set( + 1, + 0, + x, + 0, + 1, + y, + 0, + 0, + 1 + ); + } + return this; + } + makeRotation(theta) { + const c = Math.cos(theta); + const s = Math.sin(theta); + this.set( + c, + -s, + 0, + s, + c, + 0, + 0, + 0, + 1 + ); + return this; + } + makeScale(x, y) { + this.set( + x, + 0, + 0, + 0, + y, + 0, + 0, + 0, + 1 + ); + return this; + } + // + equals(matrix) { + const te = this.elements; + const me = matrix.elements; + for (let i = 0; i < 9; i++) { + if (te[i] !== me[i]) return false; + } + return true; + } + fromArray(array, offset = 0) { + for (let i = 0; i < 9; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + toArray(array = [], offset = 0) { + const te = this.elements; + array[offset] = te[0]; + array[offset + 1] = te[1]; + array[offset + 2] = te[2]; + array[offset + 3] = te[3]; + array[offset + 4] = te[4]; + array[offset + 5] = te[5]; + array[offset + 6] = te[6]; + array[offset + 7] = te[7]; + array[offset + 8] = te[8]; + return array; + } + clone() { + return new this.constructor().fromArray(this.elements); + } + }; + var _m3 = /* @__PURE__ */ new Matrix3(); + function arrayNeedsUint32(array) { + for (let i = array.length - 1; i >= 0; --i) { + if (array[i] >= 65535) return true; + } + return false; + } + var TYPED_ARRAYS = { + Int8Array, + Uint8Array, + Uint8ClampedArray, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array + }; + function getTypedArray(type, buffer) { + return new TYPED_ARRAYS[type](buffer); + } + function createElementNS(name) { + return document.createElementNS("http://www.w3.org/1999/xhtml", name); + } + function createCanvasElement() { + const canvas = createElementNS("canvas"); + canvas.style.display = "block"; + return canvas; + } + var _cache = {}; + function warnOnce(message) { + if (message in _cache) return; + _cache[message] = true; + console.warn(message); + } + var LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /* @__PURE__ */ new Matrix3().set( + 0.8224621, + 0.177538, + 0, + 0.0331941, + 0.9668058, + 0, + 0.0170827, + 0.0723974, + 0.9105199 + ); + var LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /* @__PURE__ */ new Matrix3().set( + 1.2249401, + -0.2249404, + 0, + -0.0420569, + 1.0420571, + 0, + -0.0196376, + -0.0786361, + 1.0982735 + ); + var COLOR_SPACES = { + [LinearSRGBColorSpace]: { + transfer: LinearTransfer, + primaries: Rec709Primaries, + toReference: (color) => color, + fromReference: (color) => color + }, + [SRGBColorSpace]: { + transfer: SRGBTransfer, + primaries: Rec709Primaries, + toReference: (color) => color.convertSRGBToLinear(), + fromReference: (color) => color.convertLinearToSRGB() + }, + [LinearDisplayP3ColorSpace]: { + transfer: LinearTransfer, + primaries: P3Primaries, + toReference: (color) => color.applyMatrix3(LINEAR_DISPLAY_P3_TO_LINEAR_SRGB), + fromReference: (color) => color.applyMatrix3(LINEAR_SRGB_TO_LINEAR_DISPLAY_P3) + }, + [DisplayP3ColorSpace]: { + transfer: SRGBTransfer, + primaries: P3Primaries, + toReference: (color) => color.convertSRGBToLinear().applyMatrix3(LINEAR_DISPLAY_P3_TO_LINEAR_SRGB), + fromReference: (color) => color.applyMatrix3(LINEAR_SRGB_TO_LINEAR_DISPLAY_P3).convertLinearToSRGB() + } + }; + var SUPPORTED_WORKING_COLOR_SPACES = /* @__PURE__ */ new Set([LinearSRGBColorSpace, LinearDisplayP3ColorSpace]); + var ColorManagement = { + enabled: true, + _workingColorSpace: LinearSRGBColorSpace, + get workingColorSpace() { + return this._workingColorSpace; + }, + set workingColorSpace(colorSpace) { + if (!SUPPORTED_WORKING_COLOR_SPACES.has(colorSpace)) { + throw new Error(`Unsupported working color space, "${colorSpace}".`); + } + this._workingColorSpace = colorSpace; + }, + convert: function(color, sourceColorSpace, targetColorSpace) { + if (this.enabled === false || sourceColorSpace === targetColorSpace || !sourceColorSpace || !targetColorSpace) { + return color; + } + const sourceToReference = COLOR_SPACES[sourceColorSpace].toReference; + const targetFromReference = COLOR_SPACES[targetColorSpace].fromReference; + return targetFromReference(sourceToReference(color)); + }, + fromWorkingColorSpace: function(color, targetColorSpace) { + return this.convert(color, this._workingColorSpace, targetColorSpace); + }, + toWorkingColorSpace: function(color, sourceColorSpace) { + return this.convert(color, sourceColorSpace, this._workingColorSpace); + }, + getPrimaries: function(colorSpace) { + return COLOR_SPACES[colorSpace].primaries; + }, + getTransfer: function(colorSpace) { + if (colorSpace === NoColorSpace) return LinearTransfer; + return COLOR_SPACES[colorSpace].transfer; + } + }; + function SRGBToLinear(c) { + return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4); + } + function LinearToSRGB(c) { + return c < 31308e-7 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055; + } + var _canvas; + var ImageUtils = class { + static getDataURL(image) { + if (/^data:/i.test(image.src)) { + return image.src; + } + if (typeof HTMLCanvasElement === "undefined") { + return image.src; + } + let canvas; + if (image instanceof HTMLCanvasElement) { + canvas = image; + } else { + if (_canvas === void 0) _canvas = createElementNS("canvas"); + _canvas.width = image.width; + _canvas.height = image.height; + const context = _canvas.getContext("2d"); + if (image instanceof ImageData) { + context.putImageData(image, 0, 0); + } else { + context.drawImage(image, 0, 0, image.width, image.height); + } + canvas = _canvas; + } + if (canvas.width > 2048 || canvas.height > 2048) { + console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons", image); + return canvas.toDataURL("image/jpeg", 0.6); + } else { + return canvas.toDataURL("image/png"); + } + } + static sRGBToLinear(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { + const canvas = createElementNS("canvas"); + canvas.width = image.width; + canvas.height = image.height; + const context = canvas.getContext("2d"); + context.drawImage(image, 0, 0, image.width, image.height); + const imageData = context.getImageData(0, 0, image.width, image.height); + const data = imageData.data; + for (let i = 0; i < data.length; i++) { + data[i] = SRGBToLinear(data[i] / 255) * 255; + } + context.putImageData(imageData, 0, 0); + return canvas; + } else if (image.data) { + const data = image.data.slice(0); + for (let i = 0; i < data.length; i++) { + if (data instanceof Uint8Array || data instanceof Uint8ClampedArray) { + data[i] = Math.floor(SRGBToLinear(data[i] / 255) * 255); + } else { + data[i] = SRGBToLinear(data[i]); + } + } + return { + data, + width: image.width, + height: image.height + }; + } else { + console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."); + return image; + } + } + }; + var _sourceId = 0; + var Source = class { + constructor(data = null) { + this.isSource = true; + Object.defineProperty(this, "id", { value: _sourceId++ }); + this.uuid = generateUUID(); + this.data = data; + this.version = 0; + } + set needsUpdate(value) { + if (value === true) this.version++; + } + toJSON(meta) { + const isRootObject = meta === void 0 || typeof meta === "string"; + if (!isRootObject && meta.images[this.uuid] !== void 0) { + return meta.images[this.uuid]; + } + const output = { + uuid: this.uuid, + url: "" + }; + const data = this.data; + if (data !== null) { + let url; + if (Array.isArray(data)) { + url = []; + for (let i = 0, l = data.length; i < l; i++) { + if (data[i].isDataTexture) { + url.push(serializeImage(data[i].image)); + } else { + url.push(serializeImage(data[i])); + } + } + } else { + url = serializeImage(data); + } + output.url = url; + } + if (!isRootObject) { + meta.images[this.uuid] = output; + } + return output; + } + }; + function serializeImage(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { + return ImageUtils.getDataURL(image); + } else { + if (image.data) { + return { + data: Array.from(image.data), + width: image.width, + height: image.height, + type: image.data.constructor.name + }; + } else { + console.warn("THREE.Texture: Unable to serialize Texture."); + return {}; + } + } + } + var _textureId = 0; + var Texture = class _Texture extends EventDispatcher { + constructor(image = _Texture.DEFAULT_IMAGE, mapping = _Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = _Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace) { + super(); + this.isTexture = true; + Object.defineProperty(this, "id", { value: _textureId++ }); + this.uuid = generateUUID(); + this.name = ""; + this.source = new Source(image); + this.mipmaps = []; + this.mapping = mapping; + this.channel = 0; + this.wrapS = wrapS; + this.wrapT = wrapT; + this.magFilter = magFilter; + this.minFilter = minFilter; + this.anisotropy = anisotropy; + this.format = format; + this.internalFormat = null; + this.type = type; + this.offset = new Vector2(0, 0); + this.repeat = new Vector2(1, 1); + this.center = new Vector2(0, 0); + this.rotation = 0; + this.matrixAutoUpdate = true; + this.matrix = new Matrix3(); + this.generateMipmaps = true; + this.premultiplyAlpha = false; + this.flipY = true; + this.unpackAlignment = 4; + if (typeof colorSpace === "string") { + this.colorSpace = colorSpace; + } else { + warnOnce("THREE.Texture: Property .encoding has been replaced by .colorSpace."); + this.colorSpace = colorSpace === sRGBEncoding ? SRGBColorSpace : NoColorSpace; + } + this.userData = {}; + this.version = 0; + this.onUpdate = null; + this.isRenderTargetTexture = false; + this.needsPMREMUpdate = false; + } + get image() { + return this.source.data; + } + set image(value = null) { + this.source.data = value; + } + updateMatrix() { + this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y); + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.name = source.name; + this.source = source.source; + this.mipmaps = source.mipmaps.slice(0); + this.mapping = source.mapping; + this.channel = source.channel; + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; + this.anisotropy = source.anisotropy; + this.format = source.format; + this.internalFormat = source.internalFormat; + this.type = source.type; + this.offset.copy(source.offset); + this.repeat.copy(source.repeat); + this.center.copy(source.center); + this.rotation = source.rotation; + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrix.copy(source.matrix); + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.colorSpace = source.colorSpace; + this.userData = JSON.parse(JSON.stringify(source.userData)); + this.needsUpdate = true; + return this; + } + toJSON(meta) { + const isRootObject = meta === void 0 || typeof meta === "string"; + if (!isRootObject && meta.textures[this.uuid] !== void 0) { + return meta.textures[this.uuid]; + } + const output = { + metadata: { + version: 4.6, + type: "Texture", + generator: "Texture.toJSON" + }, + uuid: this.uuid, + name: this.name, + image: this.source.toJSON(meta).uuid, + mapping: this.mapping, + channel: this.channel, + repeat: [this.repeat.x, this.repeat.y], + offset: [this.offset.x, this.offset.y], + center: [this.center.x, this.center.y], + rotation: this.rotation, + wrap: [this.wrapS, this.wrapT], + format: this.format, + internalFormat: this.internalFormat, + type: this.type, + colorSpace: this.colorSpace, + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, + flipY: this.flipY, + generateMipmaps: this.generateMipmaps, + premultiplyAlpha: this.premultiplyAlpha, + unpackAlignment: this.unpackAlignment + }; + if (Object.keys(this.userData).length > 0) output.userData = this.userData; + if (!isRootObject) { + meta.textures[this.uuid] = output; + } + return output; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + transformUv(uv) { + if (this.mapping !== UVMapping) return uv; + uv.applyMatrix3(this.matrix); + if (uv.x < 0 || uv.x > 1) { + switch (this.wrapS) { + case RepeatWrapping: + uv.x = uv.x - Math.floor(uv.x); + break; + case ClampToEdgeWrapping: + uv.x = uv.x < 0 ? 0 : 1; + break; + case MirroredRepeatWrapping: + if (Math.abs(Math.floor(uv.x) % 2) === 1) { + uv.x = Math.ceil(uv.x) - uv.x; + } else { + uv.x = uv.x - Math.floor(uv.x); + } + break; + } + } + if (uv.y < 0 || uv.y > 1) { + switch (this.wrapT) { + case RepeatWrapping: + uv.y = uv.y - Math.floor(uv.y); + break; + case ClampToEdgeWrapping: + uv.y = uv.y < 0 ? 0 : 1; + break; + case MirroredRepeatWrapping: + if (Math.abs(Math.floor(uv.y) % 2) === 1) { + uv.y = Math.ceil(uv.y) - uv.y; + } else { + uv.y = uv.y - Math.floor(uv.y); + } + break; + } + } + if (this.flipY) { + uv.y = 1 - uv.y; + } + return uv; + } + set needsUpdate(value) { + if (value === true) { + this.version++; + this.source.needsUpdate = true; + } + } + get encoding() { + warnOnce("THREE.Texture: Property .encoding has been replaced by .colorSpace."); + return this.colorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding; + } + set encoding(encoding) { + warnOnce("THREE.Texture: Property .encoding has been replaced by .colorSpace."); + this.colorSpace = encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace; + } + }; + Texture.DEFAULT_IMAGE = null; + Texture.DEFAULT_MAPPING = UVMapping; + Texture.DEFAULT_ANISOTROPY = 1; + var Vector4 = class _Vector4 { + constructor(x = 0, y = 0, z = 0, w = 1) { + _Vector4.prototype.isVector4 = true; + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } + get width() { + return this.z; + } + set width(value) { + this.z = value; + } + get height() { + return this.w; + } + set height(value) { + this.w = value; + } + set(x, y, z, w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + return this; + } + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; + return this; + } + setX(x) { + this.x = x; + return this; + } + setY(y) { + this.y = y; + return this; + } + setZ(z) { + this.z = z; + return this; + } + setW(w) { + this.w = w; + return this; + } + setComponent(index, value) { + switch (index) { + case 0: + this.x = value; + break; + case 1: + this.y = value; + break; + case 2: + this.z = value; + break; + case 3: + this.w = value; + break; + default: + throw new Error("index is out of range: " + index); + } + return this; + } + getComponent(index) { + switch (index) { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + case 3: + return this.w; + default: + throw new Error("index is out of range: " + index); + } + } + clone() { + return new this.constructor(this.x, this.y, this.z, this.w); + } + copy(v) { + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = v.w !== void 0 ? v.w : 1; + return this; + } + add(v) { + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; + return this; + } + addScalar(s) { + this.x += s; + this.y += s; + this.z += s; + this.w += s; + return this; + } + addVectors(a, b) { + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + this.w = a.w + b.w; + return this; + } + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + this.w += v.w * s; + return this; + } + sub(v) { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; + return this; + } + subScalar(s) { + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; + return this; + } + subVectors(a, b) { + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + this.w = a.w - b.w; + return this; + } + multiply(v) { + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + this.w *= v.w; + return this; + } + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; + return this; + } + applyMatrix4(m) { + const x = this.x, y = this.y, z = this.z, w = this.w; + const e = m.elements; + this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w; + this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w; + this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w; + this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w; + return this; + } + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + setAxisAngleFromQuaternion(q) { + this.w = 2 * Math.acos(q.w); + const s = Math.sqrt(1 - q.w * q.w); + if (s < 1e-4) { + this.x = 1; + this.y = 0; + this.z = 0; + } else { + this.x = q.x / s; + this.y = q.y / s; + this.z = q.z / s; + } + return this; + } + setAxisAngleFromRotationMatrix(m) { + let angle, x, y, z; + const epsilon = 0.01, epsilon2 = 0.1, te = m.elements, m11 = te[0], m12 = te[4], m13 = te[8], m21 = te[1], m22 = te[5], m23 = te[9], m31 = te[2], m32 = te[6], m33 = te[10]; + if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) { + if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) { + this.set(1, 0, 0, 0); + return this; + } + angle = Math.PI; + const xx = (m11 + 1) / 2; + const yy = (m22 + 1) / 2; + const zz = (m33 + 1) / 2; + const xy = (m12 + m21) / 4; + const xz = (m13 + m31) / 4; + const yz = (m23 + m32) / 4; + if (xx > yy && xx > zz) { + if (xx < epsilon) { + x = 0; + y = 0.707106781; + z = 0.707106781; + } else { + x = Math.sqrt(xx); + y = xy / x; + z = xz / x; + } + } else if (yy > zz) { + if (yy < epsilon) { + x = 0.707106781; + y = 0; + z = 0.707106781; + } else { + y = Math.sqrt(yy); + x = xy / y; + z = yz / y; + } + } else { + if (zz < epsilon) { + x = 0.707106781; + y = 0.707106781; + z = 0; + } else { + z = Math.sqrt(zz); + x = xz / z; + y = yz / z; + } + } + this.set(x, y, z, angle); + return this; + } + let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); + if (Math.abs(s) < 1e-3) s = 1; + this.x = (m32 - m23) / s; + this.y = (m13 - m31) / s; + this.z = (m21 - m12) / s; + this.w = Math.acos((m11 + m22 + m33 - 1) / 2); + return this; + } + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + this.z = Math.min(this.z, v.z); + this.w = Math.min(this.w, v.w); + return this; + } + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + this.z = Math.max(this.z, v.z); + this.w = Math.max(this.w, v.w); + return this; + } + clamp(min, max2) { + this.x = Math.max(min.x, Math.min(max2.x, this.x)); + this.y = Math.max(min.y, Math.min(max2.y, this.y)); + this.z = Math.max(min.z, Math.min(max2.z, this.z)); + this.w = Math.max(min.w, Math.min(max2.w, this.w)); + return this; + } + clampScalar(minVal, maxVal) { + this.x = Math.max(minVal, Math.min(maxVal, this.x)); + this.y = Math.max(minVal, Math.min(maxVal, this.y)); + this.z = Math.max(minVal, Math.min(maxVal, this.z)); + this.w = Math.max(minVal, Math.min(maxVal, this.w)); + return this; + } + clampLength(min, max2) { + const length = this.length(); + return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max2, length))); + } + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.z = Math.floor(this.z); + this.w = Math.floor(this.w); + return this; + } + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.z = Math.ceil(this.z); + this.w = Math.ceil(this.w); + return this; + } + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + this.z = Math.round(this.z); + this.w = Math.round(this.w); + return this; + } + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + this.z = Math.trunc(this.z); + this.w = Math.trunc(this.w); + return this; + } + negate() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + this.w = -this.w; + return this; + } + dot(v) { + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + } + lengthSq() { + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); + } + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w); + } + normalize() { + return this.divideScalar(this.length() || 1); + } + setLength(length) { + return this.normalize().multiplyScalar(length); + } + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + this.z += (v.z - this.z) * alpha; + this.w += (v.w - this.w) * alpha; + return this; + } + lerpVectors(v1, v2, alpha) { + this.x = v1.x + (v2.x - v1.x) * alpha; + this.y = v1.y + (v2.y - v1.y) * alpha; + this.z = v1.z + (v2.z - v1.z) * alpha; + this.w = v1.w + (v2.w - v1.w) * alpha; + return this; + } + equals(v) { + return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w; + } + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + this.z = array[offset + 2]; + this.w = array[offset + 3]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + array[offset + 2] = this.z; + array[offset + 3] = this.w; + return array; + } + fromBufferAttribute(attribute, index) { + this.x = attribute.getX(index); + this.y = attribute.getY(index); + this.z = attribute.getZ(index); + this.w = attribute.getW(index); + return this; + } + random() { + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + this.w = Math.random(); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + yield this.z; + yield this.w; + } + }; + var RenderTarget = class extends EventDispatcher { + constructor(width = 1, height = 1, options = {}) { + super(); + this.isRenderTarget = true; + this.width = width; + this.height = height; + this.depth = 1; + this.scissor = new Vector4(0, 0, width, height); + this.scissorTest = false; + this.viewport = new Vector4(0, 0, width, height); + const image = { width, height, depth: 1 }; + if (options.encoding !== void 0) { + warnOnce("THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace."); + options.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace; + } + options = Object.assign({ + generateMipmaps: false, + internalFormat: null, + minFilter: LinearFilter, + depthBuffer: true, + stencilBuffer: false, + depthTexture: null, + samples: 0 + }, options); + this.texture = new Texture(image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace); + this.texture.isRenderTargetTexture = true; + this.texture.flipY = false; + this.texture.generateMipmaps = options.generateMipmaps; + this.texture.internalFormat = options.internalFormat; + this.depthBuffer = options.depthBuffer; + this.stencilBuffer = options.stencilBuffer; + this.depthTexture = options.depthTexture; + this.samples = options.samples; + } + setSize(width, height, depth = 1) { + if (this.width !== width || this.height !== height || this.depth !== depth) { + this.width = width; + this.height = height; + this.depth = depth; + this.texture.image.width = width; + this.texture.image.height = height; + this.texture.image.depth = depth; + this.dispose(); + } + this.viewport.set(0, 0, width, height); + this.scissor.set(0, 0, width, height); + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.width = source.width; + this.height = source.height; + this.depth = source.depth; + this.scissor.copy(source.scissor); + this.scissorTest = source.scissorTest; + this.viewport.copy(source.viewport); + this.texture = source.texture.clone(); + this.texture.isRenderTargetTexture = true; + const image = Object.assign({}, source.texture.image); + this.texture.source = new Source(image); + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + if (source.depthTexture !== null) this.depthTexture = source.depthTexture.clone(); + this.samples = source.samples; + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + }; + var WebGLRenderTarget = class extends RenderTarget { + constructor(width = 1, height = 1, options = {}) { + super(width, height, options); + this.isWebGLRenderTarget = true; + } + }; + var DataArrayTexture = class extends Texture { + constructor(data = null, width = 1, height = 1, depth = 1) { + super(null); + this.isDataArrayTexture = true; + this.image = { data, width, height, depth }; + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + this.wrapR = ClampToEdgeWrapping; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + } + }; + var WebGLArrayRenderTarget = class extends WebGLRenderTarget { + constructor(width = 1, height = 1, depth = 1, options = {}) { + super(width, height, options); + this.isWebGLArrayRenderTarget = true; + this.depth = depth; + this.texture = new DataArrayTexture(null, width, height, depth); + this.texture.isRenderTargetTexture = true; + } + }; + var Data3DTexture = class extends Texture { + constructor(data = null, width = 1, height = 1, depth = 1) { + super(null); + this.isData3DTexture = true; + this.image = { data, width, height, depth }; + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + this.wrapR = ClampToEdgeWrapping; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + } + }; + var WebGL3DRenderTarget = class extends WebGLRenderTarget { + constructor(width = 1, height = 1, depth = 1, options = {}) { + super(width, height, options); + this.isWebGL3DRenderTarget = true; + this.depth = depth; + this.texture = new Data3DTexture(null, width, height, depth); + this.texture.isRenderTargetTexture = true; + } + }; + var WebGLMultipleRenderTargets = class extends WebGLRenderTarget { + constructor(width = 1, height = 1, count = 1, options = {}) { + super(width, height, options); + this.isWebGLMultipleRenderTargets = true; + const texture = this.texture; + this.texture = []; + for (let i = 0; i < count; i++) { + this.texture[i] = texture.clone(); + this.texture[i].isRenderTargetTexture = true; + } + } + setSize(width, height, depth = 1) { + if (this.width !== width || this.height !== height || this.depth !== depth) { + this.width = width; + this.height = height; + this.depth = depth; + for (let i = 0, il = this.texture.length; i < il; i++) { + this.texture[i].image.width = width; + this.texture[i].image.height = height; + this.texture[i].image.depth = depth; + } + this.dispose(); + } + this.viewport.set(0, 0, width, height); + this.scissor.set(0, 0, width, height); + } + copy(source) { + this.dispose(); + this.width = source.width; + this.height = source.height; + this.depth = source.depth; + this.scissor.copy(source.scissor); + this.scissorTest = source.scissorTest; + this.viewport.copy(source.viewport); + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + if (source.depthTexture !== null) this.depthTexture = source.depthTexture.clone(); + this.texture.length = 0; + for (let i = 0, il = source.texture.length; i < il; i++) { + this.texture[i] = source.texture[i].clone(); + this.texture[i].isRenderTargetTexture = true; + } + return this; + } + }; + var Quaternion = class { + constructor(x = 0, y = 0, z = 0, w = 1) { + this.isQuaternion = true; + this._x = x; + this._y = y; + this._z = z; + this._w = w; + } + static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) { + let x0 = src0[srcOffset0 + 0], y0 = src0[srcOffset0 + 1], z0 = src0[srcOffset0 + 2], w0 = src0[srcOffset0 + 3]; + const x1 = src1[srcOffset1 + 0], y1 = src1[srcOffset1 + 1], z1 = src1[srcOffset1 + 2], w1 = src1[srcOffset1 + 3]; + if (t === 0) { + dst[dstOffset + 0] = x0; + dst[dstOffset + 1] = y0; + dst[dstOffset + 2] = z0; + dst[dstOffset + 3] = w0; + return; + } + if (t === 1) { + dst[dstOffset + 0] = x1; + dst[dstOffset + 1] = y1; + dst[dstOffset + 2] = z1; + dst[dstOffset + 3] = w1; + return; + } + if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) { + let s = 1 - t; + const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, dir = cos >= 0 ? 1 : -1, sqrSin = 1 - cos * cos; + if (sqrSin > Number.EPSILON) { + const sin = Math.sqrt(sqrSin), len = Math.atan2(sin, cos * dir); + s = Math.sin(s * len) / sin; + t = Math.sin(t * len) / sin; + } + const tDir = t * dir; + x0 = x0 * s + x1 * tDir; + y0 = y0 * s + y1 * tDir; + z0 = z0 * s + z1 * tDir; + w0 = w0 * s + w1 * tDir; + if (s === 1 - t) { + const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0); + x0 *= f; + y0 *= f; + z0 *= f; + w0 *= f; + } + } + dst[dstOffset] = x0; + dst[dstOffset + 1] = y0; + dst[dstOffset + 2] = z0; + dst[dstOffset + 3] = w0; + } + static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) { + const x0 = src0[srcOffset0]; + const y0 = src0[srcOffset0 + 1]; + const z0 = src0[srcOffset0 + 2]; + const w0 = src0[srcOffset0 + 3]; + const x1 = src1[srcOffset1]; + const y1 = src1[srcOffset1 + 1]; + const z1 = src1[srcOffset1 + 2]; + const w1 = src1[srcOffset1 + 3]; + dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; + dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; + dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; + dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; + return dst; + } + get x() { + return this._x; + } + set x(value) { + this._x = value; + this._onChangeCallback(); + } + get y() { + return this._y; + } + set y(value) { + this._y = value; + this._onChangeCallback(); + } + get z() { + return this._z; + } + set z(value) { + this._z = value; + this._onChangeCallback(); + } + get w() { + return this._w; + } + set w(value) { + this._w = value; + this._onChangeCallback(); + } + set(x, y, z, w) { + this._x = x; + this._y = y; + this._z = z; + this._w = w; + this._onChangeCallback(); + return this; + } + clone() { + return new this.constructor(this._x, this._y, this._z, this._w); + } + copy(quaternion) { + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; + this._onChangeCallback(); + return this; + } + setFromEuler(euler, update = true) { + const x = euler._x, y = euler._y, z = euler._z, order = euler._order; + const cos = Math.cos; + const sin = Math.sin; + const c1 = cos(x / 2); + const c2 = cos(y / 2); + const c3 = cos(z / 2); + const s1 = sin(x / 2); + const s2 = sin(y / 2); + const s3 = sin(z / 2); + switch (order) { + case "XYZ": + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + case "YXZ": + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + case "ZXY": + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + case "ZYX": + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + case "YZX": + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + case "XZY": + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + default: + console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: " + order); + } + if (update === true) this._onChangeCallback(); + return this; + } + setFromAxisAngle(axis, angle) { + const halfAngle = angle / 2, s = Math.sin(halfAngle); + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos(halfAngle); + this._onChangeCallback(); + return this; + } + setFromRotationMatrix(m) { + const te = m.elements, m11 = te[0], m12 = te[4], m13 = te[8], m21 = te[1], m22 = te[5], m23 = te[9], m31 = te[2], m32 = te[6], m33 = te[10], trace = m11 + m22 + m33; + if (trace > 0) { + const s = 0.5 / Math.sqrt(trace + 1); + this._w = 0.25 / s; + this._x = (m32 - m23) * s; + this._y = (m13 - m31) * s; + this._z = (m21 - m12) * s; + } else if (m11 > m22 && m11 > m33) { + const s = 2 * Math.sqrt(1 + m11 - m22 - m33); + this._w = (m32 - m23) / s; + this._x = 0.25 * s; + this._y = (m12 + m21) / s; + this._z = (m13 + m31) / s; + } else if (m22 > m33) { + const s = 2 * Math.sqrt(1 + m22 - m11 - m33); + this._w = (m13 - m31) / s; + this._x = (m12 + m21) / s; + this._y = 0.25 * s; + this._z = (m23 + m32) / s; + } else { + const s = 2 * Math.sqrt(1 + m33 - m11 - m22); + this._w = (m21 - m12) / s; + this._x = (m13 + m31) / s; + this._y = (m23 + m32) / s; + this._z = 0.25 * s; + } + this._onChangeCallback(); + return this; + } + setFromUnitVectors(vFrom, vTo) { + let r = vFrom.dot(vTo) + 1; + if (r < Number.EPSILON) { + r = 0; + if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) { + this._x = -vFrom.y; + this._y = vFrom.x; + this._z = 0; + this._w = r; + } else { + this._x = 0; + this._y = -vFrom.z; + this._z = vFrom.y; + this._w = r; + } + } else { + this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; + this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; + this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; + this._w = r; + } + return this.normalize(); + } + angleTo(q) { + return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1))); + } + rotateTowards(q, step) { + const angle = this.angleTo(q); + if (angle === 0) return this; + const t = Math.min(1, step / angle); + this.slerp(q, t); + return this; + } + identity() { + return this.set(0, 0, 0, 1); + } + invert() { + return this.conjugate(); + } + conjugate() { + this._x *= -1; + this._y *= -1; + this._z *= -1; + this._onChangeCallback(); + return this; + } + dot(v) { + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; + } + lengthSq() { + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + } + length() { + return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w); + } + normalize() { + let l = this.length(); + if (l === 0) { + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; + } else { + l = 1 / l; + this._x = this._x * l; + this._y = this._y * l; + this._z = this._z * l; + this._w = this._w * l; + } + this._onChangeCallback(); + return this; + } + multiply(q) { + return this.multiplyQuaternions(this, q); + } + premultiply(q) { + return this.multiplyQuaternions(q, this); + } + multiplyQuaternions(a, b) { + const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; + const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; + this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; + this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; + this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; + this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; + this._onChangeCallback(); + return this; + } + slerp(qb, t) { + if (t === 0) return this; + if (t === 1) return this.copy(qb); + const x = this._x, y = this._y, z = this._z, w = this._w; + let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; + if (cosHalfTheta < 0) { + this._w = -qb._w; + this._x = -qb._x; + this._y = -qb._y; + this._z = -qb._z; + cosHalfTheta = -cosHalfTheta; + } else { + this.copy(qb); + } + if (cosHalfTheta >= 1) { + this._w = w; + this._x = x; + this._y = y; + this._z = z; + return this; + } + const sqrSinHalfTheta = 1 - cosHalfTheta * cosHalfTheta; + if (sqrSinHalfTheta <= Number.EPSILON) { + const s = 1 - t; + this._w = s * w + t * this._w; + this._x = s * x + t * this._x; + this._y = s * y + t * this._y; + this._z = s * z + t * this._z; + this.normalize(); + return this; + } + const sinHalfTheta = Math.sqrt(sqrSinHalfTheta); + const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta); + const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta, ratioB = Math.sin(t * halfTheta) / sinHalfTheta; + this._w = w * ratioA + this._w * ratioB; + this._x = x * ratioA + this._x * ratioB; + this._y = y * ratioA + this._y * ratioB; + this._z = z * ratioA + this._z * ratioB; + this._onChangeCallback(); + return this; + } + slerpQuaternions(qa, qb, t) { + return this.copy(qa).slerp(qb, t); + } + random() { + const u1 = Math.random(); + const sqrt1u1 = Math.sqrt(1 - u1); + const sqrtu1 = Math.sqrt(u1); + const u2 = 2 * Math.PI * Math.random(); + const u3 = 2 * Math.PI * Math.random(); + return this.set( + sqrt1u1 * Math.cos(u2), + sqrtu1 * Math.sin(u3), + sqrtu1 * Math.cos(u3), + sqrt1u1 * Math.sin(u2) + ); + } + equals(quaternion) { + return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w; + } + fromArray(array, offset = 0) { + this._x = array[offset]; + this._y = array[offset + 1]; + this._z = array[offset + 2]; + this._w = array[offset + 3]; + this._onChangeCallback(); + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this._x; + array[offset + 1] = this._y; + array[offset + 2] = this._z; + array[offset + 3] = this._w; + return array; + } + fromBufferAttribute(attribute, index) { + this._x = attribute.getX(index); + this._y = attribute.getY(index); + this._z = attribute.getZ(index); + this._w = attribute.getW(index); + this._onChangeCallback(); + return this; + } + toJSON() { + return this.toArray(); + } + _onChange(callback) { + this._onChangeCallback = callback; + return this; + } + _onChangeCallback() { + } + *[Symbol.iterator]() { + yield this._x; + yield this._y; + yield this._z; + yield this._w; + } + }; + var Vector3 = class _Vector3 { + constructor(x = 0, y = 0, z = 0) { + _Vector3.prototype.isVector3 = true; + this.x = x; + this.y = y; + this.z = z; + } + set(x, y, z) { + if (z === void 0) z = this.z; + this.x = x; + this.y = y; + this.z = z; + return this; + } + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + this.z = scalar; + return this; + } + setX(x) { + this.x = x; + return this; + } + setY(y) { + this.y = y; + return this; + } + setZ(z) { + this.z = z; + return this; + } + setComponent(index, value) { + switch (index) { + case 0: + this.x = value; + break; + case 1: + this.y = value; + break; + case 2: + this.z = value; + break; + default: + throw new Error("index is out of range: " + index); + } + return this; + } + getComponent(index) { + switch (index) { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + default: + throw new Error("index is out of range: " + index); + } + } + clone() { + return new this.constructor(this.x, this.y, this.z); + } + copy(v) { + this.x = v.x; + this.y = v.y; + this.z = v.z; + return this; + } + add(v) { + this.x += v.x; + this.y += v.y; + this.z += v.z; + return this; + } + addScalar(s) { + this.x += s; + this.y += s; + this.z += s; + return this; + } + addVectors(a, b) { + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + return this; + } + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + return this; + } + sub(v) { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + return this; + } + subScalar(s) { + this.x -= s; + this.y -= s; + this.z -= s; + return this; + } + subVectors(a, b) { + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + return this; + } + multiply(v) { + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + return this; + } + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + return this; + } + multiplyVectors(a, b) { + this.x = a.x * b.x; + this.y = a.y * b.y; + this.z = a.z * b.z; + return this; + } + applyEuler(euler) { + return this.applyQuaternion(_quaternion$4.setFromEuler(euler)); + } + applyAxisAngle(axis, angle) { + return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle)); + } + applyMatrix3(m) { + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + this.x = e[0] * x + e[3] * y + e[6] * z; + this.y = e[1] * x + e[4] * y + e[7] * z; + this.z = e[2] * x + e[5] * y + e[8] * z; + return this; + } + applyNormalMatrix(m) { + return this.applyMatrix3(m).normalize(); + } + applyMatrix4(m) { + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]); + this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w; + this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w; + this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w; + return this; + } + applyQuaternion(q) { + const vx = this.x, vy = this.y, vz = this.z; + const qx = q.x, qy = q.y, qz = q.z, qw = q.w; + const tx = 2 * (qy * vz - qz * vy); + const ty = 2 * (qz * vx - qx * vz); + const tz = 2 * (qx * vy - qy * vx); + this.x = vx + qw * tx + qy * tz - qz * ty; + this.y = vy + qw * ty + qz * tx - qx * tz; + this.z = vz + qw * tz + qx * ty - qy * tx; + return this; + } + project(camera) { + return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix); + } + unproject(camera) { + return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld); + } + transformDirection(m) { + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + this.x = e[0] * x + e[4] * y + e[8] * z; + this.y = e[1] * x + e[5] * y + e[9] * z; + this.z = e[2] * x + e[6] * y + e[10] * z; + return this.normalize(); + } + divide(v) { + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + return this; + } + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + this.z = Math.min(this.z, v.z); + return this; + } + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + this.z = Math.max(this.z, v.z); + return this; + } + clamp(min, max2) { + this.x = Math.max(min.x, Math.min(max2.x, this.x)); + this.y = Math.max(min.y, Math.min(max2.y, this.y)); + this.z = Math.max(min.z, Math.min(max2.z, this.z)); + return this; + } + clampScalar(minVal, maxVal) { + this.x = Math.max(minVal, Math.min(maxVal, this.x)); + this.y = Math.max(minVal, Math.min(maxVal, this.y)); + this.z = Math.max(minVal, Math.min(maxVal, this.z)); + return this; + } + clampLength(min, max2) { + const length = this.length(); + return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max2, length))); + } + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.z = Math.floor(this.z); + return this; + } + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.z = Math.ceil(this.z); + return this; + } + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + this.z = Math.round(this.z); + return this; + } + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + this.z = Math.trunc(this.z); + return this; + } + negate() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + return this; + } + dot(v) { + return this.x * v.x + this.y * v.y + this.z * v.z; + } + // TODO lengthSquared? + lengthSq() { + return this.x * this.x + this.y * this.y + this.z * this.z; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); + } + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z); + } + normalize() { + return this.divideScalar(this.length() || 1); + } + setLength(length) { + return this.normalize().multiplyScalar(length); + } + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + this.z += (v.z - this.z) * alpha; + return this; + } + lerpVectors(v1, v2, alpha) { + this.x = v1.x + (v2.x - v1.x) * alpha; + this.y = v1.y + (v2.y - v1.y) * alpha; + this.z = v1.z + (v2.z - v1.z) * alpha; + return this; + } + cross(v) { + return this.crossVectors(this, v); + } + crossVectors(a, b) { + const ax = a.x, ay = a.y, az = a.z; + const bx = b.x, by = b.y, bz = b.z; + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; + return this; + } + projectOnVector(v) { + const denominator = v.lengthSq(); + if (denominator === 0) return this.set(0, 0, 0); + const scalar = v.dot(this) / denominator; + return this.copy(v).multiplyScalar(scalar); + } + projectOnPlane(planeNormal) { + _vector$c.copy(this).projectOnVector(planeNormal); + return this.sub(_vector$c); + } + reflect(normal) { + return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal))); + } + angleTo(v) { + const denominator = Math.sqrt(this.lengthSq() * v.lengthSq()); + if (denominator === 0) return Math.PI / 2; + const theta = this.dot(v) / denominator; + return Math.acos(clamp(theta, -1, 1)); + } + distanceTo(v) { + return Math.sqrt(this.distanceToSquared(v)); + } + distanceToSquared(v) { + const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; + return dx * dx + dy * dy + dz * dz; + } + manhattanDistanceTo(v) { + return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z); + } + setFromSpherical(s) { + return this.setFromSphericalCoords(s.radius, s.phi, s.theta); + } + setFromSphericalCoords(radius, phi, theta) { + const sinPhiRadius = Math.sin(phi) * radius; + this.x = sinPhiRadius * Math.sin(theta); + this.y = Math.cos(phi) * radius; + this.z = sinPhiRadius * Math.cos(theta); + return this; + } + setFromCylindrical(c) { + return this.setFromCylindricalCoords(c.radius, c.theta, c.y); + } + setFromCylindricalCoords(radius, theta, y) { + this.x = radius * Math.sin(theta); + this.y = y; + this.z = radius * Math.cos(theta); + return this; + } + setFromMatrixPosition(m) { + const e = m.elements; + this.x = e[12]; + this.y = e[13]; + this.z = e[14]; + return this; + } + setFromMatrixScale(m) { + const sx = this.setFromMatrixColumn(m, 0).length(); + const sy = this.setFromMatrixColumn(m, 1).length(); + const sz = this.setFromMatrixColumn(m, 2).length(); + this.x = sx; + this.y = sy; + this.z = sz; + return this; + } + setFromMatrixColumn(m, index) { + return this.fromArray(m.elements, index * 4); + } + setFromMatrix3Column(m, index) { + return this.fromArray(m.elements, index * 3); + } + setFromEuler(e) { + this.x = e._x; + this.y = e._y; + this.z = e._z; + return this; + } + setFromColor(c) { + this.x = c.r; + this.y = c.g; + this.z = c.b; + return this; + } + equals(v) { + return v.x === this.x && v.y === this.y && v.z === this.z; + } + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + this.z = array[offset + 2]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + array[offset + 2] = this.z; + return array; + } + fromBufferAttribute(attribute, index) { + this.x = attribute.getX(index); + this.y = attribute.getY(index); + this.z = attribute.getZ(index); + return this; + } + random() { + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + return this; + } + randomDirection() { + const u = (Math.random() - 0.5) * 2; + const t = Math.random() * Math.PI * 2; + const f = Math.sqrt(1 - u ** 2); + this.x = f * Math.cos(t); + this.y = f * Math.sin(t); + this.z = u; + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + yield this.z; + } + }; + var _vector$c = /* @__PURE__ */ new Vector3(); + var _quaternion$4 = /* @__PURE__ */ new Quaternion(); + var Box3 = class { + constructor(min = new Vector3(Infinity, Infinity, Infinity), max2 = new Vector3(-Infinity, -Infinity, -Infinity)) { + this.isBox3 = true; + this.min = min; + this.max = max2; + } + set(min, max2) { + this.min.copy(min); + this.max.copy(max2); + return this; + } + setFromArray(array) { + this.makeEmpty(); + for (let i = 0, il = array.length; i < il; i += 3) { + this.expandByPoint(_vector$b.fromArray(array, i)); + } + return this; + } + setFromBufferAttribute(attribute) { + this.makeEmpty(); + for (let i = 0, il = attribute.count; i < il; i++) { + this.expandByPoint(_vector$b.fromBufferAttribute(attribute, i)); + } + return this; + } + setFromPoints(points) { + this.makeEmpty(); + for (let i = 0, il = points.length; i < il; i++) { + this.expandByPoint(points[i]); + } + return this; + } + setFromCenterAndSize(center, size) { + const halfSize = _vector$b.copy(size).multiplyScalar(0.5); + this.min.copy(center).sub(halfSize); + this.max.copy(center).add(halfSize); + return this; + } + setFromObject(object, precise = false) { + this.makeEmpty(); + return this.expandByObject(object, precise); + } + clone() { + return new this.constructor().copy(this); + } + copy(box) { + this.min.copy(box.min); + this.max.copy(box.max); + return this; + } + makeEmpty() { + this.min.x = this.min.y = this.min.z = Infinity; + this.max.x = this.max.y = this.max.z = -Infinity; + return this; + } + isEmpty() { + return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z; + } + getCenter(target) { + return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5); + } + getSize(target) { + return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min); + } + expandByPoint(point) { + this.min.min(point); + this.max.max(point); + return this; + } + expandByVector(vector) { + this.min.sub(vector); + this.max.add(vector); + return this; + } + expandByScalar(scalar) { + this.min.addScalar(-scalar); + this.max.addScalar(scalar); + return this; + } + expandByObject(object, precise = false) { + object.updateWorldMatrix(false, false); + const geometry = object.geometry; + if (geometry !== void 0) { + const positionAttribute = geometry.getAttribute("position"); + if (precise === true && positionAttribute !== void 0 && object.isInstancedMesh !== true) { + for (let i = 0, l = positionAttribute.count; i < l; i++) { + if (object.isMesh === true) { + object.getVertexPosition(i, _vector$b); + } else { + _vector$b.fromBufferAttribute(positionAttribute, i); + } + _vector$b.applyMatrix4(object.matrixWorld); + this.expandByPoint(_vector$b); + } + } else { + if (object.boundingBox !== void 0) { + if (object.boundingBox === null) { + object.computeBoundingBox(); + } + _box$4.copy(object.boundingBox); + } else { + if (geometry.boundingBox === null) { + geometry.computeBoundingBox(); + } + _box$4.copy(geometry.boundingBox); + } + _box$4.applyMatrix4(object.matrixWorld); + this.union(_box$4); + } + } + const children = object.children; + for (let i = 0, l = children.length; i < l; i++) { + this.expandByObject(children[i], precise); + } + return this; + } + containsPoint(point) { + return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y || point.z < this.min.z || point.z > this.max.z ? false : true; + } + containsBox(box) { + return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z; + } + getParameter(point, target) { + return target.set( + (point.x - this.min.x) / (this.max.x - this.min.x), + (point.y - this.min.y) / (this.max.y - this.min.y), + (point.z - this.min.z) / (this.max.z - this.min.z) + ); + } + intersectsBox(box) { + return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y || box.max.z < this.min.z || box.min.z > this.max.z ? false : true; + } + intersectsSphere(sphere) { + this.clampPoint(sphere.center, _vector$b); + return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius; + } + intersectsPlane(plane) { + let min, max2; + if (plane.normal.x > 0) { + min = plane.normal.x * this.min.x; + max2 = plane.normal.x * this.max.x; + } else { + min = plane.normal.x * this.max.x; + max2 = plane.normal.x * this.min.x; + } + if (plane.normal.y > 0) { + min += plane.normal.y * this.min.y; + max2 += plane.normal.y * this.max.y; + } else { + min += plane.normal.y * this.max.y; + max2 += plane.normal.y * this.min.y; + } + if (plane.normal.z > 0) { + min += plane.normal.z * this.min.z; + max2 += plane.normal.z * this.max.z; + } else { + min += plane.normal.z * this.max.z; + max2 += plane.normal.z * this.min.z; + } + return min <= -plane.constant && max2 >= -plane.constant; + } + intersectsTriangle(triangle) { + if (this.isEmpty()) { + return false; + } + this.getCenter(_center); + _extents.subVectors(this.max, _center); + _v0$2.subVectors(triangle.a, _center); + _v1$7.subVectors(triangle.b, _center); + _v2$4.subVectors(triangle.c, _center); + _f0.subVectors(_v1$7, _v0$2); + _f1.subVectors(_v2$4, _v1$7); + _f2.subVectors(_v0$2, _v2$4); + let axes = [ + 0, + -_f0.z, + _f0.y, + 0, + -_f1.z, + _f1.y, + 0, + -_f2.z, + _f2.y, + _f0.z, + 0, + -_f0.x, + _f1.z, + 0, + -_f1.x, + _f2.z, + 0, + -_f2.x, + -_f0.y, + _f0.x, + 0, + -_f1.y, + _f1.x, + 0, + -_f2.y, + _f2.x, + 0 + ]; + if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) { + return false; + } + axes = [1, 0, 0, 0, 1, 0, 0, 0, 1]; + if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) { + return false; + } + _triangleNormal.crossVectors(_f0, _f1); + axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z]; + return satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents); + } + clampPoint(point, target) { + return target.copy(point).clamp(this.min, this.max); + } + distanceToPoint(point) { + return this.clampPoint(point, _vector$b).distanceTo(point); + } + getBoundingSphere(target) { + if (this.isEmpty()) { + target.makeEmpty(); + } else { + this.getCenter(target.center); + target.radius = this.getSize(_vector$b).length() * 0.5; + } + return target; + } + intersect(box) { + this.min.max(box.min); + this.max.min(box.max); + if (this.isEmpty()) this.makeEmpty(); + return this; + } + union(box) { + this.min.min(box.min); + this.max.max(box.max); + return this; + } + applyMatrix4(matrix) { + if (this.isEmpty()) return this; + _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); + _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); + _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); + _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); + _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); + _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); + _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); + _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); + this.setFromPoints(_points); + return this; + } + translate(offset) { + this.min.add(offset); + this.max.add(offset); + return this; + } + equals(box) { + return box.min.equals(this.min) && box.max.equals(this.max); + } + }; + var _points = [ + /* @__PURE__ */ new Vector3(), + /* @__PURE__ */ new Vector3(), + /* @__PURE__ */ new Vector3(), + /* @__PURE__ */ new Vector3(), + /* @__PURE__ */ new Vector3(), + /* @__PURE__ */ new Vector3(), + /* @__PURE__ */ new Vector3(), + /* @__PURE__ */ new Vector3() + ]; + var _vector$b = /* @__PURE__ */ new Vector3(); + var _box$4 = /* @__PURE__ */ new Box3(); + var _v0$2 = /* @__PURE__ */ new Vector3(); + var _v1$7 = /* @__PURE__ */ new Vector3(); + var _v2$4 = /* @__PURE__ */ new Vector3(); + var _f0 = /* @__PURE__ */ new Vector3(); + var _f1 = /* @__PURE__ */ new Vector3(); + var _f2 = /* @__PURE__ */ new Vector3(); + var _center = /* @__PURE__ */ new Vector3(); + var _extents = /* @__PURE__ */ new Vector3(); + var _triangleNormal = /* @__PURE__ */ new Vector3(); + var _testAxis = /* @__PURE__ */ new Vector3(); + function satForAxes(axes, v0, v1, v2, extents) { + for (let i = 0, j = axes.length - 3; i <= j; i += 3) { + _testAxis.fromArray(axes, i); + const r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z); + const p0 = v0.dot(_testAxis); + const p1 = v1.dot(_testAxis); + const p2 = v2.dot(_testAxis); + if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) { + return false; + } + } + return true; + } + var _box$3 = /* @__PURE__ */ new Box3(); + var _v1$6 = /* @__PURE__ */ new Vector3(); + var _v2$3 = /* @__PURE__ */ new Vector3(); + var Sphere = class { + constructor(center = new Vector3(), radius = -1) { + this.isSphere = true; + this.center = center; + this.radius = radius; + } + set(center, radius) { + this.center.copy(center); + this.radius = radius; + return this; + } + setFromPoints(points, optionalCenter) { + const center = this.center; + if (optionalCenter !== void 0) { + center.copy(optionalCenter); + } else { + _box$3.setFromPoints(points).getCenter(center); + } + let maxRadiusSq = 0; + for (let i = 0, il = points.length; i < il; i++) { + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i])); + } + this.radius = Math.sqrt(maxRadiusSq); + return this; + } + copy(sphere) { + this.center.copy(sphere.center); + this.radius = sphere.radius; + return this; + } + isEmpty() { + return this.radius < 0; + } + makeEmpty() { + this.center.set(0, 0, 0); + this.radius = -1; + return this; + } + containsPoint(point) { + return point.distanceToSquared(this.center) <= this.radius * this.radius; + } + distanceToPoint(point) { + return point.distanceTo(this.center) - this.radius; + } + intersectsSphere(sphere) { + const radiusSum = this.radius + sphere.radius; + return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum; + } + intersectsBox(box) { + return box.intersectsSphere(this); + } + intersectsPlane(plane) { + return Math.abs(plane.distanceToPoint(this.center)) <= this.radius; + } + clampPoint(point, target) { + const deltaLengthSq = this.center.distanceToSquared(point); + target.copy(point); + if (deltaLengthSq > this.radius * this.radius) { + target.sub(this.center).normalize(); + target.multiplyScalar(this.radius).add(this.center); + } + return target; + } + getBoundingBox(target) { + if (this.isEmpty()) { + target.makeEmpty(); + return target; + } + target.set(this.center, this.center); + target.expandByScalar(this.radius); + return target; + } + applyMatrix4(matrix) { + this.center.applyMatrix4(matrix); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); + return this; + } + translate(offset) { + this.center.add(offset); + return this; + } + expandByPoint(point) { + if (this.isEmpty()) { + this.center.copy(point); + this.radius = 0; + return this; + } + _v1$6.subVectors(point, this.center); + const lengthSq = _v1$6.lengthSq(); + if (lengthSq > this.radius * this.radius) { + const length = Math.sqrt(lengthSq); + const delta = (length - this.radius) * 0.5; + this.center.addScaledVector(_v1$6, delta / length); + this.radius += delta; + } + return this; + } + union(sphere) { + if (sphere.isEmpty()) { + return this; + } + if (this.isEmpty()) { + this.copy(sphere); + return this; + } + if (this.center.equals(sphere.center) === true) { + this.radius = Math.max(this.radius, sphere.radius); + } else { + _v2$3.subVectors(sphere.center, this.center).setLength(sphere.radius); + this.expandByPoint(_v1$6.copy(sphere.center).add(_v2$3)); + this.expandByPoint(_v1$6.copy(sphere.center).sub(_v2$3)); + } + return this; + } + equals(sphere) { + return sphere.center.equals(this.center) && sphere.radius === this.radius; + } + clone() { + return new this.constructor().copy(this); + } + }; + var _vector$a = /* @__PURE__ */ new Vector3(); + var _segCenter = /* @__PURE__ */ new Vector3(); + var _segDir = /* @__PURE__ */ new Vector3(); + var _diff = /* @__PURE__ */ new Vector3(); + var _edge1 = /* @__PURE__ */ new Vector3(); + var _edge2 = /* @__PURE__ */ new Vector3(); + var _normal$1 = /* @__PURE__ */ new Vector3(); + var Ray = class { + constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) { + this.origin = origin; + this.direction = direction; + } + set(origin, direction) { + this.origin.copy(origin); + this.direction.copy(direction); + return this; + } + copy(ray) { + this.origin.copy(ray.origin); + this.direction.copy(ray.direction); + return this; + } + at(t, target) { + return target.copy(this.origin).addScaledVector(this.direction, t); + } + lookAt(v) { + this.direction.copy(v).sub(this.origin).normalize(); + return this; + } + recast(t) { + this.origin.copy(this.at(t, _vector$a)); + return this; + } + closestPointToPoint(point, target) { + target.subVectors(point, this.origin); + const directionDistance = target.dot(this.direction); + if (directionDistance < 0) { + return target.copy(this.origin); + } + return target.copy(this.origin).addScaledVector(this.direction, directionDistance); + } + distanceToPoint(point) { + return Math.sqrt(this.distanceSqToPoint(point)); + } + distanceSqToPoint(point) { + const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); + if (directionDistance < 0) { + return this.origin.distanceToSquared(point); + } + _vector$a.copy(this.origin).addScaledVector(this.direction, directionDistance); + return _vector$a.distanceToSquared(point); + } + distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) { + _segCenter.copy(v0).add(v1).multiplyScalar(0.5); + _segDir.copy(v1).sub(v0).normalize(); + _diff.copy(this.origin).sub(_segCenter); + const segExtent = v0.distanceTo(v1) * 0.5; + const a01 = -this.direction.dot(_segDir); + const b0 = _diff.dot(this.direction); + const b1 = -_diff.dot(_segDir); + const c = _diff.lengthSq(); + const det = Math.abs(1 - a01 * a01); + let s0, s1, sqrDist, extDet; + if (det > 0) { + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; + if (s0 >= 0) { + if (s1 >= -extDet) { + if (s1 <= extDet) { + const invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c; + } else { + s1 = segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + } else { + s1 = -segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + } else { + if (s1 <= -extDet) { + s0 = Math.max(0, -(-a01 * segExtent + b0)); + s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } else if (s1 <= extDet) { + s0 = 0; + s1 = Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = s1 * (s1 + 2 * b1) + c; + } else { + s0 = Math.max(0, -(a01 * segExtent + b0)); + s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + } + } else { + s1 = a01 > 0 ? -segExtent : segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + if (optionalPointOnRay) { + optionalPointOnRay.copy(this.origin).addScaledVector(this.direction, s0); + } + if (optionalPointOnSegment) { + optionalPointOnSegment.copy(_segCenter).addScaledVector(_segDir, s1); + } + return sqrDist; + } + intersectSphere(sphere, target) { + _vector$a.subVectors(sphere.center, this.origin); + const tca = _vector$a.dot(this.direction); + const d2 = _vector$a.dot(_vector$a) - tca * tca; + const radius2 = sphere.radius * sphere.radius; + if (d2 > radius2) return null; + const thc = Math.sqrt(radius2 - d2); + const t0 = tca - thc; + const t1 = tca + thc; + if (t1 < 0) return null; + if (t0 < 0) return this.at(t1, target); + return this.at(t0, target); + } + intersectsSphere(sphere) { + return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius; + } + distanceToPlane(plane) { + const denominator = plane.normal.dot(this.direction); + if (denominator === 0) { + if (plane.distanceToPoint(this.origin) === 0) { + return 0; + } + return null; + } + const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; + return t >= 0 ? t : null; + } + intersectPlane(plane, target) { + const t = this.distanceToPlane(plane); + if (t === null) { + return null; + } + return this.at(t, target); + } + intersectsPlane(plane) { + const distToPoint = plane.distanceToPoint(this.origin); + if (distToPoint === 0) { + return true; + } + const denominator = plane.normal.dot(this.direction); + if (denominator * distToPoint < 0) { + return true; + } + return false; + } + intersectBox(box, target) { + let tmin, tmax, tymin, tymax, tzmin, tzmax; + const invdirx = 1 / this.direction.x, invdiry = 1 / this.direction.y, invdirz = 1 / this.direction.z; + const origin = this.origin; + if (invdirx >= 0) { + tmin = (box.min.x - origin.x) * invdirx; + tmax = (box.max.x - origin.x) * invdirx; + } else { + tmin = (box.max.x - origin.x) * invdirx; + tmax = (box.min.x - origin.x) * invdirx; + } + if (invdiry >= 0) { + tymin = (box.min.y - origin.y) * invdiry; + tymax = (box.max.y - origin.y) * invdiry; + } else { + tymin = (box.max.y - origin.y) * invdiry; + tymax = (box.min.y - origin.y) * invdiry; + } + if (tmin > tymax || tymin > tmax) return null; + if (tymin > tmin || isNaN(tmin)) tmin = tymin; + if (tymax < tmax || isNaN(tmax)) tmax = tymax; + if (invdirz >= 0) { + tzmin = (box.min.z - origin.z) * invdirz; + tzmax = (box.max.z - origin.z) * invdirz; + } else { + tzmin = (box.max.z - origin.z) * invdirz; + tzmax = (box.min.z - origin.z) * invdirz; + } + if (tmin > tzmax || tzmin > tmax) return null; + if (tzmin > tmin || tmin !== tmin) tmin = tzmin; + if (tzmax < tmax || tmax !== tmax) tmax = tzmax; + if (tmax < 0) return null; + return this.at(tmin >= 0 ? tmin : tmax, target); + } + intersectsBox(box) { + return this.intersectBox(box, _vector$a) !== null; + } + intersectTriangle(a, b, c, backfaceCulling, target) { + _edge1.subVectors(b, a); + _edge2.subVectors(c, a); + _normal$1.crossVectors(_edge1, _edge2); + let DdN = this.direction.dot(_normal$1); + let sign2; + if (DdN > 0) { + if (backfaceCulling) return null; + sign2 = 1; + } else if (DdN < 0) { + sign2 = -1; + DdN = -DdN; + } else { + return null; + } + _diff.subVectors(this.origin, a); + const DdQxE2 = sign2 * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); + if (DdQxE2 < 0) { + return null; + } + const DdE1xQ = sign2 * this.direction.dot(_edge1.cross(_diff)); + if (DdE1xQ < 0) { + return null; + } + if (DdQxE2 + DdE1xQ > DdN) { + return null; + } + const QdN = -sign2 * _diff.dot(_normal$1); + if (QdN < 0) { + return null; + } + return this.at(QdN / DdN, target); + } + applyMatrix4(matrix4) { + this.origin.applyMatrix4(matrix4); + this.direction.transformDirection(matrix4); + return this; + } + equals(ray) { + return ray.origin.equals(this.origin) && ray.direction.equals(this.direction); + } + clone() { + return new this.constructor().copy(this); + } + }; + var Matrix4 = class _Matrix4 { + constructor(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) { + _Matrix4.prototype.isMatrix4 = true; + this.elements = [ + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ]; + if (n11 !== void 0) { + this.set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44); + } + } + set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) { + const te = this.elements; + te[0] = n11; + te[4] = n12; + te[8] = n13; + te[12] = n14; + te[1] = n21; + te[5] = n22; + te[9] = n23; + te[13] = n24; + te[2] = n31; + te[6] = n32; + te[10] = n33; + te[14] = n34; + te[3] = n41; + te[7] = n42; + te[11] = n43; + te[15] = n44; + return this; + } + identity() { + this.set( + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + clone() { + return new _Matrix4().fromArray(this.elements); + } + copy(m) { + const te = this.elements; + const me = m.elements; + te[0] = me[0]; + te[1] = me[1]; + te[2] = me[2]; + te[3] = me[3]; + te[4] = me[4]; + te[5] = me[5]; + te[6] = me[6]; + te[7] = me[7]; + te[8] = me[8]; + te[9] = me[9]; + te[10] = me[10]; + te[11] = me[11]; + te[12] = me[12]; + te[13] = me[13]; + te[14] = me[14]; + te[15] = me[15]; + return this; + } + copyPosition(m) { + const te = this.elements, me = m.elements; + te[12] = me[12]; + te[13] = me[13]; + te[14] = me[14]; + return this; + } + setFromMatrix3(m) { + const me = m.elements; + this.set( + me[0], + me[3], + me[6], + 0, + me[1], + me[4], + me[7], + 0, + me[2], + me[5], + me[8], + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + extractBasis(xAxis, yAxis, zAxis) { + xAxis.setFromMatrixColumn(this, 0); + yAxis.setFromMatrixColumn(this, 1); + zAxis.setFromMatrixColumn(this, 2); + return this; + } + makeBasis(xAxis, yAxis, zAxis) { + this.set( + xAxis.x, + yAxis.x, + zAxis.x, + 0, + xAxis.y, + yAxis.y, + zAxis.y, + 0, + xAxis.z, + yAxis.z, + zAxis.z, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + extractRotation(m) { + const te = this.elements; + const me = m.elements; + const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length(); + const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length(); + const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length(); + te[0] = me[0] * scaleX; + te[1] = me[1] * scaleX; + te[2] = me[2] * scaleX; + te[3] = 0; + te[4] = me[4] * scaleY; + te[5] = me[5] * scaleY; + te[6] = me[6] * scaleY; + te[7] = 0; + te[8] = me[8] * scaleZ; + te[9] = me[9] * scaleZ; + te[10] = me[10] * scaleZ; + te[11] = 0; + te[12] = 0; + te[13] = 0; + te[14] = 0; + te[15] = 1; + return this; + } + makeRotationFromEuler(euler) { + const te = this.elements; + const x = euler.x, y = euler.y, z = euler.z; + const a = Math.cos(x), b = Math.sin(x); + const c = Math.cos(y), d = Math.sin(y); + const e = Math.cos(z), f = Math.sin(z); + if (euler.order === "XYZ") { + const ae = a * e, af = a * f, be = b * e, bf = b * f; + te[0] = c * e; + te[4] = -c * f; + te[8] = d; + te[1] = af + be * d; + te[5] = ae - bf * d; + te[9] = -b * c; + te[2] = bf - ae * d; + te[6] = be + af * d; + te[10] = a * c; + } else if (euler.order === "YXZ") { + const ce = c * e, cf = c * f, de = d * e, df = d * f; + te[0] = ce + df * b; + te[4] = de * b - cf; + te[8] = a * d; + te[1] = a * f; + te[5] = a * e; + te[9] = -b; + te[2] = cf * b - de; + te[6] = df + ce * b; + te[10] = a * c; + } else if (euler.order === "ZXY") { + const ce = c * e, cf = c * f, de = d * e, df = d * f; + te[0] = ce - df * b; + te[4] = -a * f; + te[8] = de + cf * b; + te[1] = cf + de * b; + te[5] = a * e; + te[9] = df - ce * b; + te[2] = -a * d; + te[6] = b; + te[10] = a * c; + } else if (euler.order === "ZYX") { + const ae = a * e, af = a * f, be = b * e, bf = b * f; + te[0] = c * e; + te[4] = be * d - af; + te[8] = ae * d + bf; + te[1] = c * f; + te[5] = bf * d + ae; + te[9] = af * d - be; + te[2] = -d; + te[6] = b * c; + te[10] = a * c; + } else if (euler.order === "YZX") { + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; + te[0] = c * e; + te[4] = bd - ac * f; + te[8] = bc * f + ad; + te[1] = f; + te[5] = a * e; + te[9] = -b * e; + te[2] = -d * e; + te[6] = ad * f + bc; + te[10] = ac - bd * f; + } else if (euler.order === "XZY") { + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; + te[0] = c * e; + te[4] = -f; + te[8] = d * e; + te[1] = ac * f + bd; + te[5] = a * e; + te[9] = ad * f - bc; + te[2] = bc * f - ad; + te[6] = b * e; + te[10] = bd * f + ac; + } + te[3] = 0; + te[7] = 0; + te[11] = 0; + te[12] = 0; + te[13] = 0; + te[14] = 0; + te[15] = 1; + return this; + } + makeRotationFromQuaternion(q) { + return this.compose(_zero, q, _one); + } + lookAt(eye, target, up) { + const te = this.elements; + _z.subVectors(eye, target); + if (_z.lengthSq() === 0) { + _z.z = 1; + } + _z.normalize(); + _x.crossVectors(up, _z); + if (_x.lengthSq() === 0) { + if (Math.abs(up.z) === 1) { + _z.x += 1e-4; + } else { + _z.z += 1e-4; + } + _z.normalize(); + _x.crossVectors(up, _z); + } + _x.normalize(); + _y.crossVectors(_z, _x); + te[0] = _x.x; + te[4] = _y.x; + te[8] = _z.x; + te[1] = _x.y; + te[5] = _y.y; + te[9] = _z.y; + te[2] = _x.z; + te[6] = _y.z; + te[10] = _z.z; + return this; + } + multiply(m) { + return this.multiplyMatrices(this, m); + } + premultiply(m) { + return this.multiplyMatrices(m, this); + } + multiplyMatrices(a, b) { + const ae = a.elements; + const be = b.elements; + const te = this.elements; + const a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12]; + const a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13]; + const a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14]; + const a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15]; + const b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12]; + const b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13]; + const b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14]; + const b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15]; + te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; + te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; + te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; + te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; + te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; + te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; + te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; + te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; + te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; + te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; + te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; + te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; + te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; + te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; + te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; + te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; + return this; + } + multiplyScalar(s) { + const te = this.elements; + te[0] *= s; + te[4] *= s; + te[8] *= s; + te[12] *= s; + te[1] *= s; + te[5] *= s; + te[9] *= s; + te[13] *= s; + te[2] *= s; + te[6] *= s; + te[10] *= s; + te[14] *= s; + te[3] *= s; + te[7] *= s; + te[11] *= s; + te[15] *= s; + return this; + } + determinant() { + const te = this.elements; + const n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12]; + const n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13]; + const n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14]; + const n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15]; + return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31); + } + transpose() { + const te = this.elements; + let tmp2; + tmp2 = te[1]; + te[1] = te[4]; + te[4] = tmp2; + tmp2 = te[2]; + te[2] = te[8]; + te[8] = tmp2; + tmp2 = te[6]; + te[6] = te[9]; + te[9] = tmp2; + tmp2 = te[3]; + te[3] = te[12]; + te[12] = tmp2; + tmp2 = te[7]; + te[7] = te[13]; + te[13] = tmp2; + tmp2 = te[11]; + te[11] = te[14]; + te[14] = tmp2; + return this; + } + setPosition(x, y, z) { + const te = this.elements; + if (x.isVector3) { + te[12] = x.x; + te[13] = x.y; + te[14] = x.z; + } else { + te[12] = x; + te[13] = y; + te[14] = z; + } + return this; + } + invert() { + const te = this.elements, n11 = te[0], n21 = te[1], n31 = te[2], n41 = te[3], n12 = te[4], n22 = te[5], n32 = te[6], n42 = te[7], n13 = te[8], n23 = te[9], n33 = te[10], n43 = te[11], n14 = te[12], n24 = te[13], n34 = te[14], n44 = te[15], t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; + if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + const detInv = 1 / det; + te[0] = t11 * detInv; + te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv; + te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv; + te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv; + te[4] = t12 * detInv; + te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv; + te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv; + te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv; + te[8] = t13 * detInv; + te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv; + te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv; + te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv; + te[12] = t14 * detInv; + te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv; + te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv; + te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv; + return this; + } + scale(v) { + const te = this.elements; + const x = v.x, y = v.y, z = v.z; + te[0] *= x; + te[4] *= y; + te[8] *= z; + te[1] *= x; + te[5] *= y; + te[9] *= z; + te[2] *= x; + te[6] *= y; + te[10] *= z; + te[3] *= x; + te[7] *= y; + te[11] *= z; + return this; + } + getMaxScaleOnAxis() { + const te = this.elements; + const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2]; + const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6]; + const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10]; + return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq)); + } + makeTranslation(x, y, z) { + if (x.isVector3) { + this.set( + 1, + 0, + 0, + x.x, + 0, + 1, + 0, + x.y, + 0, + 0, + 1, + x.z, + 0, + 0, + 0, + 1 + ); + } else { + this.set( + 1, + 0, + 0, + x, + 0, + 1, + 0, + y, + 0, + 0, + 1, + z, + 0, + 0, + 0, + 1 + ); + } + return this; + } + makeRotationX(theta) { + const c = Math.cos(theta), s = Math.sin(theta); + this.set( + 1, + 0, + 0, + 0, + 0, + c, + -s, + 0, + 0, + s, + c, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + makeRotationY(theta) { + const c = Math.cos(theta), s = Math.sin(theta); + this.set( + c, + 0, + s, + 0, + 0, + 1, + 0, + 0, + -s, + 0, + c, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + makeRotationZ(theta) { + const c = Math.cos(theta), s = Math.sin(theta); + this.set( + c, + -s, + 0, + 0, + s, + c, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + makeRotationAxis(axis, angle) { + const c = Math.cos(angle); + const s = Math.sin(angle); + const t = 1 - c; + const x = axis.x, y = axis.y, z = axis.z; + const tx = t * x, ty = t * y; + this.set( + tx * x + c, + tx * y - s * z, + tx * z + s * y, + 0, + tx * y + s * z, + ty * y + c, + ty * z - s * x, + 0, + tx * z - s * y, + ty * z + s * x, + t * z * z + c, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + makeScale(x, y, z) { + this.set( + x, + 0, + 0, + 0, + 0, + y, + 0, + 0, + 0, + 0, + z, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + makeShear(xy, xz, yx, yz, zx, zy) { + this.set( + 1, + yx, + zx, + 0, + xy, + 1, + zy, + 0, + xz, + yz, + 1, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + compose(position, quaternion, scale) { + const te = this.elements; + const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w; + const x2 = x + x, y2 = y + y, z2 = z + z; + const xx = x * x2, xy = x * y2, xz = x * z2; + const yy = y * y2, yz = y * z2, zz = z * z2; + const wx = w * x2, wy = w * y2, wz = w * z2; + const sx = scale.x, sy = scale.y, sz = scale.z; + te[0] = (1 - (yy + zz)) * sx; + te[1] = (xy + wz) * sx; + te[2] = (xz - wy) * sx; + te[3] = 0; + te[4] = (xy - wz) * sy; + te[5] = (1 - (xx + zz)) * sy; + te[6] = (yz + wx) * sy; + te[7] = 0; + te[8] = (xz + wy) * sz; + te[9] = (yz - wx) * sz; + te[10] = (1 - (xx + yy)) * sz; + te[11] = 0; + te[12] = position.x; + te[13] = position.y; + te[14] = position.z; + te[15] = 1; + return this; + } + decompose(position, quaternion, scale) { + const te = this.elements; + let sx = _v1$5.set(te[0], te[1], te[2]).length(); + const sy = _v1$5.set(te[4], te[5], te[6]).length(); + const sz = _v1$5.set(te[8], te[9], te[10]).length(); + const det = this.determinant(); + if (det < 0) sx = -sx; + position.x = te[12]; + position.y = te[13]; + position.z = te[14]; + _m1$2.copy(this); + const invSX = 1 / sx; + const invSY = 1 / sy; + const invSZ = 1 / sz; + _m1$2.elements[0] *= invSX; + _m1$2.elements[1] *= invSX; + _m1$2.elements[2] *= invSX; + _m1$2.elements[4] *= invSY; + _m1$2.elements[5] *= invSY; + _m1$2.elements[6] *= invSY; + _m1$2.elements[8] *= invSZ; + _m1$2.elements[9] *= invSZ; + _m1$2.elements[10] *= invSZ; + quaternion.setFromRotationMatrix(_m1$2); + scale.x = sx; + scale.y = sy; + scale.z = sz; + return this; + } + makePerspective(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem) { + const te = this.elements; + const x = 2 * near / (right - left); + const y = 2 * near / (top - bottom); + const a = (right + left) / (right - left); + const b = (top + bottom) / (top - bottom); + let c, d; + if (coordinateSystem === WebGLCoordinateSystem) { + c = -(far + near) / (far - near); + d = -2 * far * near / (far - near); + } else if (coordinateSystem === WebGPUCoordinateSystem) { + c = -far / (far - near); + d = -far * near / (far - near); + } else { + throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: " + coordinateSystem); + } + te[0] = x; + te[4] = 0; + te[8] = a; + te[12] = 0; + te[1] = 0; + te[5] = y; + te[9] = b; + te[13] = 0; + te[2] = 0; + te[6] = 0; + te[10] = c; + te[14] = d; + te[3] = 0; + te[7] = 0; + te[11] = -1; + te[15] = 0; + return this; + } + makeOrthographic(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem) { + const te = this.elements; + const w = 1 / (right - left); + const h = 1 / (top - bottom); + const p = 1 / (far - near); + const x = (right + left) * w; + const y = (top + bottom) * h; + let z, zInv; + if (coordinateSystem === WebGLCoordinateSystem) { + z = (far + near) * p; + zInv = -2 * p; + } else if (coordinateSystem === WebGPUCoordinateSystem) { + z = near * p; + zInv = -1 * p; + } else { + throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: " + coordinateSystem); + } + te[0] = 2 * w; + te[4] = 0; + te[8] = 0; + te[12] = -x; + te[1] = 0; + te[5] = 2 * h; + te[9] = 0; + te[13] = -y; + te[2] = 0; + te[6] = 0; + te[10] = zInv; + te[14] = -z; + te[3] = 0; + te[7] = 0; + te[11] = 0; + te[15] = 1; + return this; + } + equals(matrix) { + const te = this.elements; + const me = matrix.elements; + for (let i = 0; i < 16; i++) { + if (te[i] !== me[i]) return false; + } + return true; + } + fromArray(array, offset = 0) { + for (let i = 0; i < 16; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + toArray(array = [], offset = 0) { + const te = this.elements; + array[offset] = te[0]; + array[offset + 1] = te[1]; + array[offset + 2] = te[2]; + array[offset + 3] = te[3]; + array[offset + 4] = te[4]; + array[offset + 5] = te[5]; + array[offset + 6] = te[6]; + array[offset + 7] = te[7]; + array[offset + 8] = te[8]; + array[offset + 9] = te[9]; + array[offset + 10] = te[10]; + array[offset + 11] = te[11]; + array[offset + 12] = te[12]; + array[offset + 13] = te[13]; + array[offset + 14] = te[14]; + array[offset + 15] = te[15]; + return array; + } + }; + var _v1$5 = /* @__PURE__ */ new Vector3(); + var _m1$2 = /* @__PURE__ */ new Matrix4(); + var _zero = /* @__PURE__ */ new Vector3(0, 0, 0); + var _one = /* @__PURE__ */ new Vector3(1, 1, 1); + var _x = /* @__PURE__ */ new Vector3(); + var _y = /* @__PURE__ */ new Vector3(); + var _z = /* @__PURE__ */ new Vector3(); + var _matrix$1 = /* @__PURE__ */ new Matrix4(); + var _quaternion$3 = /* @__PURE__ */ new Quaternion(); + var Euler = class _Euler { + constructor(x = 0, y = 0, z = 0, order = _Euler.DEFAULT_ORDER) { + this.isEuler = true; + this._x = x; + this._y = y; + this._z = z; + this._order = order; + } + get x() { + return this._x; + } + set x(value) { + this._x = value; + this._onChangeCallback(); + } + get y() { + return this._y; + } + set y(value) { + this._y = value; + this._onChangeCallback(); + } + get z() { + return this._z; + } + set z(value) { + this._z = value; + this._onChangeCallback(); + } + get order() { + return this._order; + } + set order(value) { + this._order = value; + this._onChangeCallback(); + } + set(x, y, z, order = this._order) { + this._x = x; + this._y = y; + this._z = z; + this._order = order; + this._onChangeCallback(); + return this; + } + clone() { + return new this.constructor(this._x, this._y, this._z, this._order); + } + copy(euler) { + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; + this._onChangeCallback(); + return this; + } + setFromRotationMatrix(m, order = this._order, update = true) { + const te = m.elements; + const m11 = te[0], m12 = te[4], m13 = te[8]; + const m21 = te[1], m22 = te[5], m23 = te[9]; + const m31 = te[2], m32 = te[6], m33 = te[10]; + switch (order) { + case "XYZ": + this._y = Math.asin(clamp(m13, -1, 1)); + if (Math.abs(m13) < 0.9999999) { + this._x = Math.atan2(-m23, m33); + this._z = Math.atan2(-m12, m11); + } else { + this._x = Math.atan2(m32, m22); + this._z = 0; + } + break; + case "YXZ": + this._x = Math.asin(-clamp(m23, -1, 1)); + if (Math.abs(m23) < 0.9999999) { + this._y = Math.atan2(m13, m33); + this._z = Math.atan2(m21, m22); + } else { + this._y = Math.atan2(-m31, m11); + this._z = 0; + } + break; + case "ZXY": + this._x = Math.asin(clamp(m32, -1, 1)); + if (Math.abs(m32) < 0.9999999) { + this._y = Math.atan2(-m31, m33); + this._z = Math.atan2(-m12, m22); + } else { + this._y = 0; + this._z = Math.atan2(m21, m11); + } + break; + case "ZYX": + this._y = Math.asin(-clamp(m31, -1, 1)); + if (Math.abs(m31) < 0.9999999) { + this._x = Math.atan2(m32, m33); + this._z = Math.atan2(m21, m11); + } else { + this._x = 0; + this._z = Math.atan2(-m12, m22); + } + break; + case "YZX": + this._z = Math.asin(clamp(m21, -1, 1)); + if (Math.abs(m21) < 0.9999999) { + this._x = Math.atan2(-m23, m22); + this._y = Math.atan2(-m31, m11); + } else { + this._x = 0; + this._y = Math.atan2(m13, m33); + } + break; + case "XZY": + this._z = Math.asin(-clamp(m12, -1, 1)); + if (Math.abs(m12) < 0.9999999) { + this._x = Math.atan2(m32, m22); + this._y = Math.atan2(m13, m11); + } else { + this._x = Math.atan2(-m23, m33); + this._y = 0; + } + break; + default: + console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: " + order); + } + this._order = order; + if (update === true) this._onChangeCallback(); + return this; + } + setFromQuaternion(q, order, update) { + _matrix$1.makeRotationFromQuaternion(q); + return this.setFromRotationMatrix(_matrix$1, order, update); + } + setFromVector3(v, order = this._order) { + return this.set(v.x, v.y, v.z, order); + } + reorder(newOrder) { + _quaternion$3.setFromEuler(this); + return this.setFromQuaternion(_quaternion$3, newOrder); + } + equals(euler) { + return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order; + } + fromArray(array) { + this._x = array[0]; + this._y = array[1]; + this._z = array[2]; + if (array[3] !== void 0) this._order = array[3]; + this._onChangeCallback(); + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this._x; + array[offset + 1] = this._y; + array[offset + 2] = this._z; + array[offset + 3] = this._order; + return array; + } + _onChange(callback) { + this._onChangeCallback = callback; + return this; + } + _onChangeCallback() { + } + *[Symbol.iterator]() { + yield this._x; + yield this._y; + yield this._z; + yield this._order; + } + }; + Euler.DEFAULT_ORDER = "XYZ"; + var Layers = class { + constructor() { + this.mask = 1 | 0; + } + set(channel) { + this.mask = (1 << channel | 0) >>> 0; + } + enable(channel) { + this.mask |= 1 << channel | 0; + } + enableAll() { + this.mask = 4294967295 | 0; + } + toggle(channel) { + this.mask ^= 1 << channel | 0; + } + disable(channel) { + this.mask &= ~(1 << channel | 0); + } + disableAll() { + this.mask = 0; + } + test(layers) { + return (this.mask & layers.mask) !== 0; + } + isEnabled(channel) { + return (this.mask & (1 << channel | 0)) !== 0; + } + }; + var _object3DId = 0; + var _v1$4 = /* @__PURE__ */ new Vector3(); + var _q1 = /* @__PURE__ */ new Quaternion(); + var _m1$1 = /* @__PURE__ */ new Matrix4(); + var _target = /* @__PURE__ */ new Vector3(); + var _position$3 = /* @__PURE__ */ new Vector3(); + var _scale$2 = /* @__PURE__ */ new Vector3(); + var _quaternion$2 = /* @__PURE__ */ new Quaternion(); + var _xAxis = /* @__PURE__ */ new Vector3(1, 0, 0); + var _yAxis = /* @__PURE__ */ new Vector3(0, 1, 0); + var _zAxis = /* @__PURE__ */ new Vector3(0, 0, 1); + var _addedEvent = { type: "added" }; + var _removedEvent = { type: "removed" }; + var Object3D = class _Object3D extends EventDispatcher { + constructor() { + super(); + this.isObject3D = true; + Object.defineProperty(this, "id", { value: _object3DId++ }); + this.uuid = generateUUID(); + this.name = ""; + this.type = "Object3D"; + this.parent = null; + this.children = []; + this.up = _Object3D.DEFAULT_UP.clone(); + const position = new Vector3(); + const rotation = new Euler(); + const quaternion = new Quaternion(); + const scale = new Vector3(1, 1, 1); + function onRotationChange() { + quaternion.setFromEuler(rotation, false); + } + function onQuaternionChange() { + rotation.setFromQuaternion(quaternion, void 0, false); + } + rotation._onChange(onRotationChange); + quaternion._onChange(onQuaternionChange); + Object.defineProperties(this, { + position: { + configurable: true, + enumerable: true, + value: position + }, + rotation: { + configurable: true, + enumerable: true, + value: rotation + }, + quaternion: { + configurable: true, + enumerable: true, + value: quaternion + }, + scale: { + configurable: true, + enumerable: true, + value: scale + }, + modelViewMatrix: { + value: new Matrix4() + }, + normalMatrix: { + value: new Matrix3() + } + }); + this.matrix = new Matrix4(); + this.matrixWorld = new Matrix4(); + this.matrixAutoUpdate = _Object3D.DEFAULT_MATRIX_AUTO_UPDATE; + this.matrixWorldAutoUpdate = _Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; + this.matrixWorldNeedsUpdate = false; + this.layers = new Layers(); + this.visible = true; + this.castShadow = false; + this.receiveShadow = false; + this.frustumCulled = true; + this.renderOrder = 0; + this.animations = []; + this.userData = {}; + } + onBeforeShadow() { + } + onAfterShadow() { + } + onBeforeRender() { + } + onAfterRender() { + } + applyMatrix4(matrix) { + if (this.matrixAutoUpdate) this.updateMatrix(); + this.matrix.premultiply(matrix); + this.matrix.decompose(this.position, this.quaternion, this.scale); + } + applyQuaternion(q) { + this.quaternion.premultiply(q); + return this; + } + setRotationFromAxisAngle(axis, angle) { + this.quaternion.setFromAxisAngle(axis, angle); + } + setRotationFromEuler(euler) { + this.quaternion.setFromEuler(euler, true); + } + setRotationFromMatrix(m) { + this.quaternion.setFromRotationMatrix(m); + } + setRotationFromQuaternion(q) { + this.quaternion.copy(q); + } + rotateOnAxis(axis, angle) { + _q1.setFromAxisAngle(axis, angle); + this.quaternion.multiply(_q1); + return this; + } + rotateOnWorldAxis(axis, angle) { + _q1.setFromAxisAngle(axis, angle); + this.quaternion.premultiply(_q1); + return this; + } + rotateX(angle) { + return this.rotateOnAxis(_xAxis, angle); + } + rotateY(angle) { + return this.rotateOnAxis(_yAxis, angle); + } + rotateZ(angle) { + return this.rotateOnAxis(_zAxis, angle); + } + translateOnAxis(axis, distance) { + _v1$4.copy(axis).applyQuaternion(this.quaternion); + this.position.add(_v1$4.multiplyScalar(distance)); + return this; + } + translateX(distance) { + return this.translateOnAxis(_xAxis, distance); + } + translateY(distance) { + return this.translateOnAxis(_yAxis, distance); + } + translateZ(distance) { + return this.translateOnAxis(_zAxis, distance); + } + localToWorld(vector) { + this.updateWorldMatrix(true, false); + return vector.applyMatrix4(this.matrixWorld); + } + worldToLocal(vector) { + this.updateWorldMatrix(true, false); + return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert()); + } + lookAt(x, y, z) { + if (x.isVector3) { + _target.copy(x); + } else { + _target.set(x, y, z); + } + const parent = this.parent; + this.updateWorldMatrix(true, false); + _position$3.setFromMatrixPosition(this.matrixWorld); + if (this.isCamera || this.isLight) { + _m1$1.lookAt(_position$3, _target, this.up); + } else { + _m1$1.lookAt(_target, _position$3, this.up); + } + this.quaternion.setFromRotationMatrix(_m1$1); + if (parent) { + _m1$1.extractRotation(parent.matrixWorld); + _q1.setFromRotationMatrix(_m1$1); + this.quaternion.premultiply(_q1.invert()); + } + } + add(object) { + if (arguments.length > 1) { + for (let i = 0; i < arguments.length; i++) { + this.add(arguments[i]); + } + return this; + } + if (object === this) { + console.error("THREE.Object3D.add: object can't be added as a child of itself.", object); + return this; + } + if (object && object.isObject3D) { + if (object.parent !== null) { + object.parent.remove(object); + } + object.parent = this; + this.children.push(object); + object.dispatchEvent(_addedEvent); + } else { + console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object); + } + return this; + } + remove(object) { + if (arguments.length > 1) { + for (let i = 0; i < arguments.length; i++) { + this.remove(arguments[i]); + } + return this; + } + const index = this.children.indexOf(object); + if (index !== -1) { + object.parent = null; + this.children.splice(index, 1); + object.dispatchEvent(_removedEvent); + } + return this; + } + removeFromParent() { + const parent = this.parent; + if (parent !== null) { + parent.remove(this); + } + return this; + } + clear() { + return this.remove(...this.children); + } + attach(object) { + this.updateWorldMatrix(true, false); + _m1$1.copy(this.matrixWorld).invert(); + if (object.parent !== null) { + object.parent.updateWorldMatrix(true, false); + _m1$1.multiply(object.parent.matrixWorld); + } + object.applyMatrix4(_m1$1); + this.add(object); + object.updateWorldMatrix(false, true); + return this; + } + getObjectById(id) { + return this.getObjectByProperty("id", id); + } + getObjectByName(name) { + return this.getObjectByProperty("name", name); + } + getObjectByProperty(name, value) { + if (this[name] === value) return this; + for (let i = 0, l = this.children.length; i < l; i++) { + const child = this.children[i]; + const object = child.getObjectByProperty(name, value); + if (object !== void 0) { + return object; + } + } + return void 0; + } + getObjectsByProperty(name, value, result = []) { + if (this[name] === value) result.push(this); + const children = this.children; + for (let i = 0, l = children.length; i < l; i++) { + children[i].getObjectsByProperty(name, value, result); + } + return result; + } + getWorldPosition(target) { + this.updateWorldMatrix(true, false); + return target.setFromMatrixPosition(this.matrixWorld); + } + getWorldQuaternion(target) { + this.updateWorldMatrix(true, false); + this.matrixWorld.decompose(_position$3, target, _scale$2); + return target; + } + getWorldScale(target) { + this.updateWorldMatrix(true, false); + this.matrixWorld.decompose(_position$3, _quaternion$2, target); + return target; + } + getWorldDirection(target) { + this.updateWorldMatrix(true, false); + const e = this.matrixWorld.elements; + return target.set(e[8], e[9], e[10]).normalize(); + } + raycast() { + } + traverse(callback) { + callback(this); + const children = this.children; + for (let i = 0, l = children.length; i < l; i++) { + children[i].traverse(callback); + } + } + traverseVisible(callback) { + if (this.visible === false) return; + callback(this); + const children = this.children; + for (let i = 0, l = children.length; i < l; i++) { + children[i].traverseVisible(callback); + } + } + traverseAncestors(callback) { + const parent = this.parent; + if (parent !== null) { + callback(parent); + parent.traverseAncestors(callback); + } + } + updateMatrix() { + this.matrix.compose(this.position, this.quaternion, this.scale); + this.matrixWorldNeedsUpdate = true; + } + updateMatrixWorld(force) { + if (this.matrixAutoUpdate) this.updateMatrix(); + if (this.matrixWorldNeedsUpdate || force) { + if (this.parent === null) { + this.matrixWorld.copy(this.matrix); + } else { + this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); + } + this.matrixWorldNeedsUpdate = false; + force = true; + } + const children = this.children; + for (let i = 0, l = children.length; i < l; i++) { + const child = children[i]; + if (child.matrixWorldAutoUpdate === true || force === true) { + child.updateMatrixWorld(force); + } + } + } + updateWorldMatrix(updateParents, updateChildren) { + const parent = this.parent; + if (updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true) { + parent.updateWorldMatrix(true, false); + } + if (this.matrixAutoUpdate) this.updateMatrix(); + if (this.parent === null) { + this.matrixWorld.copy(this.matrix); + } else { + this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); + } + if (updateChildren === true) { + const children = this.children; + for (let i = 0, l = children.length; i < l; i++) { + const child = children[i]; + if (child.matrixWorldAutoUpdate === true) { + child.updateWorldMatrix(false, true); + } + } + } + } + toJSON(meta) { + const isRootObject = meta === void 0 || typeof meta === "string"; + const output = {}; + if (isRootObject) { + meta = { + geometries: {}, + materials: {}, + textures: {}, + images: {}, + shapes: {}, + skeletons: {}, + animations: {}, + nodes: {} + }; + output.metadata = { + version: 4.6, + type: "Object", + generator: "Object3D.toJSON" + }; + } + const object = {}; + object.uuid = this.uuid; + object.type = this.type; + if (this.name !== "") object.name = this.name; + if (this.castShadow === true) object.castShadow = true; + if (this.receiveShadow === true) object.receiveShadow = true; + if (this.visible === false) object.visible = false; + if (this.frustumCulled === false) object.frustumCulled = false; + if (this.renderOrder !== 0) object.renderOrder = this.renderOrder; + if (Object.keys(this.userData).length > 0) object.userData = this.userData; + object.layers = this.layers.mask; + object.matrix = this.matrix.toArray(); + object.up = this.up.toArray(); + if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; + if (this.isInstancedMesh) { + object.type = "InstancedMesh"; + object.count = this.count; + object.instanceMatrix = this.instanceMatrix.toJSON(); + if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON(); + } + if (this.isBatchedMesh) { + object.type = "BatchedMesh"; + object.perObjectFrustumCulled = this.perObjectFrustumCulled; + object.sortObjects = this.sortObjects; + object.drawRanges = this._drawRanges; + object.reservedRanges = this._reservedRanges; + object.visibility = this._visibility; + object.active = this._active; + object.bounds = this._bounds.map((bound) => ({ + boxInitialized: bound.boxInitialized, + boxMin: bound.box.min.toArray(), + boxMax: bound.box.max.toArray(), + sphereInitialized: bound.sphereInitialized, + sphereRadius: bound.sphere.radius, + sphereCenter: bound.sphere.center.toArray() + })); + object.maxGeometryCount = this._maxGeometryCount; + object.maxVertexCount = this._maxVertexCount; + object.maxIndexCount = this._maxIndexCount; + object.geometryInitialized = this._geometryInitialized; + object.geometryCount = this._geometryCount; + object.matricesTexture = this._matricesTexture.toJSON(meta); + if (this.boundingSphere !== null) { + object.boundingSphere = { + center: object.boundingSphere.center.toArray(), + radius: object.boundingSphere.radius + }; + } + if (this.boundingBox !== null) { + object.boundingBox = { + min: object.boundingBox.min.toArray(), + max: object.boundingBox.max.toArray() + }; + } + } + function serialize(library, element) { + if (library[element.uuid] === void 0) { + library[element.uuid] = element.toJSON(meta); + } + return element.uuid; + } + if (this.isScene) { + if (this.background) { + if (this.background.isColor) { + object.background = this.background.toJSON(); + } else if (this.background.isTexture) { + object.background = this.background.toJSON(meta).uuid; + } + } + if (this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true) { + object.environment = this.environment.toJSON(meta).uuid; + } + } else if (this.isMesh || this.isLine || this.isPoints) { + object.geometry = serialize(meta.geometries, this.geometry); + const parameters = this.geometry.parameters; + if (parameters !== void 0 && parameters.shapes !== void 0) { + const shapes = parameters.shapes; + if (Array.isArray(shapes)) { + for (let i = 0, l = shapes.length; i < l; i++) { + const shape = shapes[i]; + serialize(meta.shapes, shape); + } + } else { + serialize(meta.shapes, shapes); + } + } + } + if (this.isSkinnedMesh) { + object.bindMode = this.bindMode; + object.bindMatrix = this.bindMatrix.toArray(); + if (this.skeleton !== void 0) { + serialize(meta.skeletons, this.skeleton); + object.skeleton = this.skeleton.uuid; + } + } + if (this.material !== void 0) { + if (Array.isArray(this.material)) { + const uuids = []; + for (let i = 0, l = this.material.length; i < l; i++) { + uuids.push(serialize(meta.materials, this.material[i])); + } + object.material = uuids; + } else { + object.material = serialize(meta.materials, this.material); + } + } + if (this.children.length > 0) { + object.children = []; + for (let i = 0; i < this.children.length; i++) { + object.children.push(this.children[i].toJSON(meta).object); + } + } + if (this.animations.length > 0) { + object.animations = []; + for (let i = 0; i < this.animations.length; i++) { + const animation = this.animations[i]; + object.animations.push(serialize(meta.animations, animation)); + } + } + if (isRootObject) { + const geometries = extractFromCache(meta.geometries); + const materials = extractFromCache(meta.materials); + const textures = extractFromCache(meta.textures); + const images = extractFromCache(meta.images); + const shapes = extractFromCache(meta.shapes); + const skeletons = extractFromCache(meta.skeletons); + const animations = extractFromCache(meta.animations); + const nodes = extractFromCache(meta.nodes); + if (geometries.length > 0) output.geometries = geometries; + if (materials.length > 0) output.materials = materials; + if (textures.length > 0) output.textures = textures; + if (images.length > 0) output.images = images; + if (shapes.length > 0) output.shapes = shapes; + if (skeletons.length > 0) output.skeletons = skeletons; + if (animations.length > 0) output.animations = animations; + if (nodes.length > 0) output.nodes = nodes; + } + output.object = object; + return output; + function extractFromCache(cache) { + const values = []; + for (const key in cache) { + const data = cache[key]; + delete data.metadata; + values.push(data); + } + return values; + } + } + clone(recursive) { + return new this.constructor().copy(this, recursive); + } + copy(source, recursive = true) { + this.name = source.name; + this.up.copy(source.up); + this.position.copy(source.position); + this.rotation.order = source.rotation.order; + this.quaternion.copy(source.quaternion); + this.scale.copy(source.scale); + this.matrix.copy(source.matrix); + this.matrixWorld.copy(source.matrixWorld); + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + this.layers.mask = source.layers.mask; + this.visible = source.visible; + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; + this.animations = source.animations.slice(); + this.userData = JSON.parse(JSON.stringify(source.userData)); + if (recursive === true) { + for (let i = 0; i < source.children.length; i++) { + const child = source.children[i]; + this.add(child.clone()); + } + } + return this; + } + }; + Object3D.DEFAULT_UP = /* @__PURE__ */ new Vector3(0, 1, 0); + Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true; + Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true; + var _v0$1 = /* @__PURE__ */ new Vector3(); + var _v1$3 = /* @__PURE__ */ new Vector3(); + var _v2$2 = /* @__PURE__ */ new Vector3(); + var _v3$1 = /* @__PURE__ */ new Vector3(); + var _vab = /* @__PURE__ */ new Vector3(); + var _vac = /* @__PURE__ */ new Vector3(); + var _vbc = /* @__PURE__ */ new Vector3(); + var _vap = /* @__PURE__ */ new Vector3(); + var _vbp = /* @__PURE__ */ new Vector3(); + var _vcp = /* @__PURE__ */ new Vector3(); + var warnedGetUV = false; + var Triangle = class _Triangle { + constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) { + this.a = a; + this.b = b; + this.c = c; + } + static getNormal(a, b, c, target) { + target.subVectors(c, b); + _v0$1.subVectors(a, b); + target.cross(_v0$1); + const targetLengthSq = target.lengthSq(); + if (targetLengthSq > 0) { + return target.multiplyScalar(1 / Math.sqrt(targetLengthSq)); + } + return target.set(0, 0, 0); + } + // static/instance method to calculate barycentric coordinates + // based on: http://www.blackpawn.com/texts/pointinpoly/default.html + static getBarycoord(point, a, b, c, target) { + _v0$1.subVectors(c, a); + _v1$3.subVectors(b, a); + _v2$2.subVectors(point, a); + const dot00 = _v0$1.dot(_v0$1); + const dot01 = _v0$1.dot(_v1$3); + const dot02 = _v0$1.dot(_v2$2); + const dot11 = _v1$3.dot(_v1$3); + const dot12 = _v1$3.dot(_v2$2); + const denom = dot00 * dot11 - dot01 * dot01; + if (denom === 0) { + target.set(0, 0, 0); + return null; + } + const invDenom = 1 / denom; + const u = (dot11 * dot02 - dot01 * dot12) * invDenom; + const v = (dot00 * dot12 - dot01 * dot02) * invDenom; + return target.set(1 - u - v, v, u); + } + static containsPoint(point, a, b, c) { + if (this.getBarycoord(point, a, b, c, _v3$1) === null) { + return false; + } + return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1; + } + static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) { + if (warnedGetUV === false) { + console.warn("THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation()."); + warnedGetUV = true; + } + return this.getInterpolation(point, p1, p2, p3, uv1, uv2, uv3, target); + } + static getInterpolation(point, p1, p2, p3, v1, v2, v3, target) { + if (this.getBarycoord(point, p1, p2, p3, _v3$1) === null) { + target.x = 0; + target.y = 0; + if ("z" in target) target.z = 0; + if ("w" in target) target.w = 0; + return null; + } + target.setScalar(0); + target.addScaledVector(v1, _v3$1.x); + target.addScaledVector(v2, _v3$1.y); + target.addScaledVector(v3, _v3$1.z); + return target; + } + static isFrontFacing(a, b, c, direction) { + _v0$1.subVectors(c, b); + _v1$3.subVectors(a, b); + return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false; + } + set(a, b, c) { + this.a.copy(a); + this.b.copy(b); + this.c.copy(c); + return this; + } + setFromPointsAndIndices(points, i0, i1, i2) { + this.a.copy(points[i0]); + this.b.copy(points[i1]); + this.c.copy(points[i2]); + return this; + } + setFromAttributeAndIndices(attribute, i0, i1, i2) { + this.a.fromBufferAttribute(attribute, i0); + this.b.fromBufferAttribute(attribute, i1); + this.c.fromBufferAttribute(attribute, i2); + return this; + } + clone() { + return new this.constructor().copy(this); + } + copy(triangle) { + this.a.copy(triangle.a); + this.b.copy(triangle.b); + this.c.copy(triangle.c); + return this; + } + getArea() { + _v0$1.subVectors(this.c, this.b); + _v1$3.subVectors(this.a, this.b); + return _v0$1.cross(_v1$3).length() * 0.5; + } + getMidpoint(target) { + return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3); + } + getNormal(target) { + return _Triangle.getNormal(this.a, this.b, this.c, target); + } + getPlane(target) { + return target.setFromCoplanarPoints(this.a, this.b, this.c); + } + getBarycoord(point, target) { + return _Triangle.getBarycoord(point, this.a, this.b, this.c, target); + } + getUV(point, uv1, uv2, uv3, target) { + if (warnedGetUV === false) { + console.warn("THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation()."); + warnedGetUV = true; + } + return _Triangle.getInterpolation(point, this.a, this.b, this.c, uv1, uv2, uv3, target); + } + getInterpolation(point, v1, v2, v3, target) { + return _Triangle.getInterpolation(point, this.a, this.b, this.c, v1, v2, v3, target); + } + containsPoint(point) { + return _Triangle.containsPoint(point, this.a, this.b, this.c); + } + isFrontFacing(direction) { + return _Triangle.isFrontFacing(this.a, this.b, this.c, direction); + } + intersectsBox(box) { + return box.intersectsTriangle(this); + } + closestPointToPoint(p, target) { + const a = this.a, b = this.b, c = this.c; + let v, w; + _vab.subVectors(b, a); + _vac.subVectors(c, a); + _vap.subVectors(p, a); + const d1 = _vab.dot(_vap); + const d2 = _vac.dot(_vap); + if (d1 <= 0 && d2 <= 0) { + return target.copy(a); + } + _vbp.subVectors(p, b); + const d3 = _vab.dot(_vbp); + const d4 = _vac.dot(_vbp); + if (d3 >= 0 && d4 <= d3) { + return target.copy(b); + } + const vc = d1 * d4 - d3 * d2; + if (vc <= 0 && d1 >= 0 && d3 <= 0) { + v = d1 / (d1 - d3); + return target.copy(a).addScaledVector(_vab, v); + } + _vcp.subVectors(p, c); + const d5 = _vab.dot(_vcp); + const d6 = _vac.dot(_vcp); + if (d6 >= 0 && d5 <= d6) { + return target.copy(c); + } + const vb = d5 * d2 - d1 * d6; + if (vb <= 0 && d2 >= 0 && d6 <= 0) { + w = d2 / (d2 - d6); + return target.copy(a).addScaledVector(_vac, w); + } + const va = d3 * d6 - d5 * d4; + if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) { + _vbc.subVectors(c, b); + w = (d4 - d3) / (d4 - d3 + (d5 - d6)); + return target.copy(b).addScaledVector(_vbc, w); + } + const denom = 1 / (va + vb + vc); + v = vb * denom; + w = vc * denom; + return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w); + } + equals(triangle) { + return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c); + } + }; + var _colorKeywords = { + "aliceblue": 15792383, + "antiquewhite": 16444375, + "aqua": 65535, + "aquamarine": 8388564, + "azure": 15794175, + "beige": 16119260, + "bisque": 16770244, + "black": 0, + "blanchedalmond": 16772045, + "blue": 255, + "blueviolet": 9055202, + "brown": 10824234, + "burlywood": 14596231, + "cadetblue": 6266528, + "chartreuse": 8388352, + "chocolate": 13789470, + "coral": 16744272, + "cornflowerblue": 6591981, + "cornsilk": 16775388, + "crimson": 14423100, + "cyan": 65535, + "darkblue": 139, + "darkcyan": 35723, + "darkgoldenrod": 12092939, + "darkgray": 11119017, + "darkgreen": 25600, + "darkgrey": 11119017, + "darkkhaki": 12433259, + "darkmagenta": 9109643, + "darkolivegreen": 5597999, + "darkorange": 16747520, + "darkorchid": 10040012, + "darkred": 9109504, + "darksalmon": 15308410, + "darkseagreen": 9419919, + "darkslateblue": 4734347, + "darkslategray": 3100495, + "darkslategrey": 3100495, + "darkturquoise": 52945, + "darkviolet": 9699539, + "deeppink": 16716947, + "deepskyblue": 49151, + "dimgray": 6908265, + "dimgrey": 6908265, + "dodgerblue": 2003199, + "firebrick": 11674146, + "floralwhite": 16775920, + "forestgreen": 2263842, + "fuchsia": 16711935, + "gainsboro": 14474460, + "ghostwhite": 16316671, + "gold": 16766720, + "goldenrod": 14329120, + "gray": 8421504, + "green": 32768, + "greenyellow": 11403055, + "grey": 8421504, + "honeydew": 15794160, + "hotpink": 16738740, + "indianred": 13458524, + "indigo": 4915330, + "ivory": 16777200, + "khaki": 15787660, + "lavender": 15132410, + "lavenderblush": 16773365, + "lawngreen": 8190976, + "lemonchiffon": 16775885, + "lightblue": 11393254, + "lightcoral": 15761536, + "lightcyan": 14745599, + "lightgoldenrodyellow": 16448210, + "lightgray": 13882323, + "lightgreen": 9498256, + "lightgrey": 13882323, + "lightpink": 16758465, + "lightsalmon": 16752762, + "lightseagreen": 2142890, + "lightskyblue": 8900346, + "lightslategray": 7833753, + "lightslategrey": 7833753, + "lightsteelblue": 11584734, + "lightyellow": 16777184, + "lime": 65280, + "limegreen": 3329330, + "linen": 16445670, + "magenta": 16711935, + "maroon": 8388608, + "mediumaquamarine": 6737322, + "mediumblue": 205, + "mediumorchid": 12211667, + "mediumpurple": 9662683, + "mediumseagreen": 3978097, + "mediumslateblue": 8087790, + "mediumspringgreen": 64154, + "mediumturquoise": 4772300, + "mediumvioletred": 13047173, + "midnightblue": 1644912, + "mintcream": 16121850, + "mistyrose": 16770273, + "moccasin": 16770229, + "navajowhite": 16768685, + "navy": 128, + "oldlace": 16643558, + "olive": 8421376, + "olivedrab": 7048739, + "orange": 16753920, + "orangered": 16729344, + "orchid": 14315734, + "palegoldenrod": 15657130, + "palegreen": 10025880, + "paleturquoise": 11529966, + "palevioletred": 14381203, + "papayawhip": 16773077, + "peachpuff": 16767673, + "peru": 13468991, + "pink": 16761035, + "plum": 14524637, + "powderblue": 11591910, + "purple": 8388736, + "rebeccapurple": 6697881, + "red": 16711680, + "rosybrown": 12357519, + "royalblue": 4286945, + "saddlebrown": 9127187, + "salmon": 16416882, + "sandybrown": 16032864, + "seagreen": 3050327, + "seashell": 16774638, + "sienna": 10506797, + "silver": 12632256, + "skyblue": 8900331, + "slateblue": 6970061, + "slategray": 7372944, + "slategrey": 7372944, + "snow": 16775930, + "springgreen": 65407, + "steelblue": 4620980, + "tan": 13808780, + "teal": 32896, + "thistle": 14204888, + "tomato": 16737095, + "turquoise": 4251856, + "violet": 15631086, + "wheat": 16113331, + "white": 16777215, + "whitesmoke": 16119285, + "yellow": 16776960, + "yellowgreen": 10145074 + }; + var _hslA = { h: 0, s: 0, l: 0 }; + var _hslB = { h: 0, s: 0, l: 0 }; + function hue2rgb(p, q, t) { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1 / 6) return p + (q - p) * 6 * t; + if (t < 1 / 2) return q; + if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t); + return p; + } + var Color = class { + constructor(r, g, b) { + this.isColor = true; + this.r = 1; + this.g = 1; + this.b = 1; + return this.set(r, g, b); + } + set(r, g, b) { + if (g === void 0 && b === void 0) { + const value = r; + if (value && value.isColor) { + this.copy(value); + } else if (typeof value === "number") { + this.setHex(value); + } else if (typeof value === "string") { + this.setStyle(value); + } + } else { + this.setRGB(r, g, b); + } + return this; + } + setScalar(scalar) { + this.r = scalar; + this.g = scalar; + this.b = scalar; + return this; + } + setHex(hex, colorSpace = SRGBColorSpace) { + hex = Math.floor(hex); + this.r = (hex >> 16 & 255) / 255; + this.g = (hex >> 8 & 255) / 255; + this.b = (hex & 255) / 255; + ColorManagement.toWorkingColorSpace(this, colorSpace); + return this; + } + setRGB(r, g, b, colorSpace = ColorManagement.workingColorSpace) { + this.r = r; + this.g = g; + this.b = b; + ColorManagement.toWorkingColorSpace(this, colorSpace); + return this; + } + setHSL(h, s, l, colorSpace = ColorManagement.workingColorSpace) { + h = euclideanModulo(h, 1); + s = clamp(s, 0, 1); + l = clamp(l, 0, 1); + if (s === 0) { + this.r = this.g = this.b = l; + } else { + const p = l <= 0.5 ? l * (1 + s) : l + s - l * s; + const q = 2 * l - p; + this.r = hue2rgb(q, p, h + 1 / 3); + this.g = hue2rgb(q, p, h); + this.b = hue2rgb(q, p, h - 1 / 3); + } + ColorManagement.toWorkingColorSpace(this, colorSpace); + return this; + } + setStyle(style, colorSpace = SRGBColorSpace) { + function handleAlpha(string) { + if (string === void 0) return; + if (parseFloat(string) < 1) { + console.warn("THREE.Color: Alpha component of " + style + " will be ignored."); + } + } + let m; + if (m = /^(\w+)\(([^\)]*)\)/.exec(style)) { + let color; + const name = m[1]; + const components = m[2]; + switch (name) { + case "rgb": + case "rgba": + if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setRGB( + Math.min(255, parseInt(color[1], 10)) / 255, + Math.min(255, parseInt(color[2], 10)) / 255, + Math.min(255, parseInt(color[3], 10)) / 255, + colorSpace + ); + } + if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setRGB( + Math.min(100, parseInt(color[1], 10)) / 100, + Math.min(100, parseInt(color[2], 10)) / 100, + Math.min(100, parseInt(color[3], 10)) / 100, + colorSpace + ); + } + break; + case "hsl": + case "hsla": + if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setHSL( + parseFloat(color[1]) / 360, + parseFloat(color[2]) / 100, + parseFloat(color[3]) / 100, + colorSpace + ); + } + break; + default: + console.warn("THREE.Color: Unknown color model " + style); + } + } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) { + const hex = m[1]; + const size = hex.length; + if (size === 3) { + return this.setRGB( + parseInt(hex.charAt(0), 16) / 15, + parseInt(hex.charAt(1), 16) / 15, + parseInt(hex.charAt(2), 16) / 15, + colorSpace + ); + } else if (size === 6) { + return this.setHex(parseInt(hex, 16), colorSpace); + } else { + console.warn("THREE.Color: Invalid hex color " + style); + } + } else if (style && style.length > 0) { + return this.setColorName(style, colorSpace); + } + return this; + } + setColorName(style, colorSpace = SRGBColorSpace) { + const hex = _colorKeywords[style.toLowerCase()]; + if (hex !== void 0) { + this.setHex(hex, colorSpace); + } else { + console.warn("THREE.Color: Unknown color " + style); + } + return this; + } + clone() { + return new this.constructor(this.r, this.g, this.b); + } + copy(color) { + this.r = color.r; + this.g = color.g; + this.b = color.b; + return this; + } + copySRGBToLinear(color) { + this.r = SRGBToLinear(color.r); + this.g = SRGBToLinear(color.g); + this.b = SRGBToLinear(color.b); + return this; + } + copyLinearToSRGB(color) { + this.r = LinearToSRGB(color.r); + this.g = LinearToSRGB(color.g); + this.b = LinearToSRGB(color.b); + return this; + } + convertSRGBToLinear() { + this.copySRGBToLinear(this); + return this; + } + convertLinearToSRGB() { + this.copyLinearToSRGB(this); + return this; + } + getHex(colorSpace = SRGBColorSpace) { + ColorManagement.fromWorkingColorSpace(_color.copy(this), colorSpace); + return Math.round(clamp(_color.r * 255, 0, 255)) * 65536 + Math.round(clamp(_color.g * 255, 0, 255)) * 256 + Math.round(clamp(_color.b * 255, 0, 255)); + } + getHexString(colorSpace = SRGBColorSpace) { + return ("000000" + this.getHex(colorSpace).toString(16)).slice(-6); + } + getHSL(target, colorSpace = ColorManagement.workingColorSpace) { + ColorManagement.fromWorkingColorSpace(_color.copy(this), colorSpace); + const r = _color.r, g = _color.g, b = _color.b; + const max2 = Math.max(r, g, b); + const min = Math.min(r, g, b); + let hue, saturation; + const lightness = (min + max2) / 2; + if (min === max2) { + hue = 0; + saturation = 0; + } else { + const delta = max2 - min; + saturation = lightness <= 0.5 ? delta / (max2 + min) : delta / (2 - max2 - min); + switch (max2) { + case r: + hue = (g - b) / delta + (g < b ? 6 : 0); + break; + case g: + hue = (b - r) / delta + 2; + break; + case b: + hue = (r - g) / delta + 4; + break; + } + hue /= 6; + } + target.h = hue; + target.s = saturation; + target.l = lightness; + return target; + } + getRGB(target, colorSpace = ColorManagement.workingColorSpace) { + ColorManagement.fromWorkingColorSpace(_color.copy(this), colorSpace); + target.r = _color.r; + target.g = _color.g; + target.b = _color.b; + return target; + } + getStyle(colorSpace = SRGBColorSpace) { + ColorManagement.fromWorkingColorSpace(_color.copy(this), colorSpace); + const r = _color.r, g = _color.g, b = _color.b; + if (colorSpace !== SRGBColorSpace) { + return `color(${colorSpace} ${r.toFixed(3)} ${g.toFixed(3)} ${b.toFixed(3)})`; + } + return `rgb(${Math.round(r * 255)},${Math.round(g * 255)},${Math.round(b * 255)})`; + } + offsetHSL(h, s, l) { + this.getHSL(_hslA); + return this.setHSL(_hslA.h + h, _hslA.s + s, _hslA.l + l); + } + add(color) { + this.r += color.r; + this.g += color.g; + this.b += color.b; + return this; + } + addColors(color1, color2) { + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; + return this; + } + addScalar(s) { + this.r += s; + this.g += s; + this.b += s; + return this; + } + sub(color) { + this.r = Math.max(0, this.r - color.r); + this.g = Math.max(0, this.g - color.g); + this.b = Math.max(0, this.b - color.b); + return this; + } + multiply(color) { + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; + return this; + } + multiplyScalar(s) { + this.r *= s; + this.g *= s; + this.b *= s; + return this; + } + lerp(color, alpha) { + this.r += (color.r - this.r) * alpha; + this.g += (color.g - this.g) * alpha; + this.b += (color.b - this.b) * alpha; + return this; + } + lerpColors(color1, color2, alpha) { + this.r = color1.r + (color2.r - color1.r) * alpha; + this.g = color1.g + (color2.g - color1.g) * alpha; + this.b = color1.b + (color2.b - color1.b) * alpha; + return this; + } + lerpHSL(color, alpha) { + this.getHSL(_hslA); + color.getHSL(_hslB); + const h = lerp(_hslA.h, _hslB.h, alpha); + const s = lerp(_hslA.s, _hslB.s, alpha); + const l = lerp(_hslA.l, _hslB.l, alpha); + this.setHSL(h, s, l); + return this; + } + setFromVector3(v) { + this.r = v.x; + this.g = v.y; + this.b = v.z; + return this; + } + applyMatrix3(m) { + const r = this.r, g = this.g, b = this.b; + const e = m.elements; + this.r = e[0] * r + e[3] * g + e[6] * b; + this.g = e[1] * r + e[4] * g + e[7] * b; + this.b = e[2] * r + e[5] * g + e[8] * b; + return this; + } + equals(c) { + return c.r === this.r && c.g === this.g && c.b === this.b; + } + fromArray(array, offset = 0) { + this.r = array[offset]; + this.g = array[offset + 1]; + this.b = array[offset + 2]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.r; + array[offset + 1] = this.g; + array[offset + 2] = this.b; + return array; + } + fromBufferAttribute(attribute, index) { + this.r = attribute.getX(index); + this.g = attribute.getY(index); + this.b = attribute.getZ(index); + return this; + } + toJSON() { + return this.getHex(); + } + *[Symbol.iterator]() { + yield this.r; + yield this.g; + yield this.b; + } + }; + var _color = /* @__PURE__ */ new Color(); + Color.NAMES = _colorKeywords; + var _materialId = 0; + var Material = class extends EventDispatcher { + constructor() { + super(); + this.isMaterial = true; + Object.defineProperty(this, "id", { value: _materialId++ }); + this.uuid = generateUUID(); + this.name = ""; + this.type = "Material"; + this.blending = NormalBlending; + this.side = FrontSide; + this.vertexColors = false; + this.opacity = 1; + this.transparent = false; + this.alphaHash = false; + this.blendSrc = SrcAlphaFactor; + this.blendDst = OneMinusSrcAlphaFactor; + this.blendEquation = AddEquation; + this.blendSrcAlpha = null; + this.blendDstAlpha = null; + this.blendEquationAlpha = null; + this.blendColor = new Color(0, 0, 0); + this.blendAlpha = 0; + this.depthFunc = LessEqualDepth; + this.depthTest = true; + this.depthWrite = true; + this.stencilWriteMask = 255; + this.stencilFunc = AlwaysStencilFunc; + this.stencilRef = 0; + this.stencilFuncMask = 255; + this.stencilFail = KeepStencilOp; + this.stencilZFail = KeepStencilOp; + this.stencilZPass = KeepStencilOp; + this.stencilWrite = false; + this.clippingPlanes = null; + this.clipIntersection = false; + this.clipShadows = false; + this.shadowSide = null; + this.colorWrite = true; + this.precision = null; + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; + this.dithering = false; + this.alphaToCoverage = false; + this.premultipliedAlpha = false; + this.forceSinglePass = false; + this.visible = true; + this.toneMapped = true; + this.userData = {}; + this.version = 0; + this._alphaTest = 0; + } + get alphaTest() { + return this._alphaTest; + } + set alphaTest(value) { + if (this._alphaTest > 0 !== value > 0) { + this.version++; + } + this._alphaTest = value; + } + onBuild() { + } + onBeforeRender() { + } + onBeforeCompile() { + } + customProgramCacheKey() { + return this.onBeforeCompile.toString(); + } + setValues(values) { + if (values === void 0) return; + for (const key in values) { + const newValue = values[key]; + if (newValue === void 0) { + console.warn(`THREE.Material: parameter '${key}' has value of undefined.`); + continue; + } + const currentValue = this[key]; + if (currentValue === void 0) { + console.warn(`THREE.Material: '${key}' is not a property of THREE.${this.type}.`); + continue; + } + if (currentValue && currentValue.isColor) { + currentValue.set(newValue); + } else if (currentValue && currentValue.isVector3 && (newValue && newValue.isVector3)) { + currentValue.copy(newValue); + } else { + this[key] = newValue; + } + } + } + toJSON(meta) { + const isRootObject = meta === void 0 || typeof meta === "string"; + if (isRootObject) { + meta = { + textures: {}, + images: {} + }; + } + const data = { + metadata: { + version: 4.6, + type: "Material", + generator: "Material.toJSON" + } + }; + data.uuid = this.uuid; + data.type = this.type; + if (this.name !== "") data.name = this.name; + if (this.color && this.color.isColor) data.color = this.color.getHex(); + if (this.roughness !== void 0) data.roughness = this.roughness; + if (this.metalness !== void 0) data.metalness = this.metalness; + if (this.sheen !== void 0) data.sheen = this.sheen; + if (this.sheenColor && this.sheenColor.isColor) data.sheenColor = this.sheenColor.getHex(); + if (this.sheenRoughness !== void 0) data.sheenRoughness = this.sheenRoughness; + if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex(); + if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity; + if (this.specular && this.specular.isColor) data.specular = this.specular.getHex(); + if (this.specularIntensity !== void 0) data.specularIntensity = this.specularIntensity; + if (this.specularColor && this.specularColor.isColor) data.specularColor = this.specularColor.getHex(); + if (this.shininess !== void 0) data.shininess = this.shininess; + if (this.clearcoat !== void 0) data.clearcoat = this.clearcoat; + if (this.clearcoatRoughness !== void 0) data.clearcoatRoughness = this.clearcoatRoughness; + if (this.clearcoatMap && this.clearcoatMap.isTexture) { + data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid; + } + if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) { + data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid; + } + if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) { + data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid; + data.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); + } + if (this.iridescence !== void 0) data.iridescence = this.iridescence; + if (this.iridescenceIOR !== void 0) data.iridescenceIOR = this.iridescenceIOR; + if (this.iridescenceThicknessRange !== void 0) data.iridescenceThicknessRange = this.iridescenceThicknessRange; + if (this.iridescenceMap && this.iridescenceMap.isTexture) { + data.iridescenceMap = this.iridescenceMap.toJSON(meta).uuid; + } + if (this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture) { + data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(meta).uuid; + } + if (this.anisotropy !== void 0) data.anisotropy = this.anisotropy; + if (this.anisotropyRotation !== void 0) data.anisotropyRotation = this.anisotropyRotation; + if (this.anisotropyMap && this.anisotropyMap.isTexture) { + data.anisotropyMap = this.anisotropyMap.toJSON(meta).uuid; + } + if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid; + if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid; + if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid; + if (this.lightMap && this.lightMap.isTexture) { + data.lightMap = this.lightMap.toJSON(meta).uuid; + data.lightMapIntensity = this.lightMapIntensity; + } + if (this.aoMap && this.aoMap.isTexture) { + data.aoMap = this.aoMap.toJSON(meta).uuid; + data.aoMapIntensity = this.aoMapIntensity; + } + if (this.bumpMap && this.bumpMap.isTexture) { + data.bumpMap = this.bumpMap.toJSON(meta).uuid; + data.bumpScale = this.bumpScale; + } + if (this.normalMap && this.normalMap.isTexture) { + data.normalMap = this.normalMap.toJSON(meta).uuid; + data.normalMapType = this.normalMapType; + data.normalScale = this.normalScale.toArray(); + } + if (this.displacementMap && this.displacementMap.isTexture) { + data.displacementMap = this.displacementMap.toJSON(meta).uuid; + data.displacementScale = this.displacementScale; + data.displacementBias = this.displacementBias; + } + if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid; + if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid; + if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid; + if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid; + if (this.specularIntensityMap && this.specularIntensityMap.isTexture) data.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid; + if (this.specularColorMap && this.specularColorMap.isTexture) data.specularColorMap = this.specularColorMap.toJSON(meta).uuid; + if (this.envMap && this.envMap.isTexture) { + data.envMap = this.envMap.toJSON(meta).uuid; + if (this.combine !== void 0) data.combine = this.combine; + } + if (this.envMapIntensity !== void 0) data.envMapIntensity = this.envMapIntensity; + if (this.reflectivity !== void 0) data.reflectivity = this.reflectivity; + if (this.refractionRatio !== void 0) data.refractionRatio = this.refractionRatio; + if (this.gradientMap && this.gradientMap.isTexture) { + data.gradientMap = this.gradientMap.toJSON(meta).uuid; + } + if (this.transmission !== void 0) data.transmission = this.transmission; + if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid; + if (this.thickness !== void 0) data.thickness = this.thickness; + if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid; + if (this.attenuationDistance !== void 0 && this.attenuationDistance !== Infinity) data.attenuationDistance = this.attenuationDistance; + if (this.attenuationColor !== void 0) data.attenuationColor = this.attenuationColor.getHex(); + if (this.size !== void 0) data.size = this.size; + if (this.shadowSide !== null) data.shadowSide = this.shadowSide; + if (this.sizeAttenuation !== void 0) data.sizeAttenuation = this.sizeAttenuation; + if (this.blending !== NormalBlending) data.blending = this.blending; + if (this.side !== FrontSide) data.side = this.side; + if (this.vertexColors === true) data.vertexColors = true; + if (this.opacity < 1) data.opacity = this.opacity; + if (this.transparent === true) data.transparent = true; + if (this.blendSrc !== SrcAlphaFactor) data.blendSrc = this.blendSrc; + if (this.blendDst !== OneMinusSrcAlphaFactor) data.blendDst = this.blendDst; + if (this.blendEquation !== AddEquation) data.blendEquation = this.blendEquation; + if (this.blendSrcAlpha !== null) data.blendSrcAlpha = this.blendSrcAlpha; + if (this.blendDstAlpha !== null) data.blendDstAlpha = this.blendDstAlpha; + if (this.blendEquationAlpha !== null) data.blendEquationAlpha = this.blendEquationAlpha; + if (this.blendColor && this.blendColor.isColor) data.blendColor = this.blendColor.getHex(); + if (this.blendAlpha !== 0) data.blendAlpha = this.blendAlpha; + if (this.depthFunc !== LessEqualDepth) data.depthFunc = this.depthFunc; + if (this.depthTest === false) data.depthTest = this.depthTest; + if (this.depthWrite === false) data.depthWrite = this.depthWrite; + if (this.colorWrite === false) data.colorWrite = this.colorWrite; + if (this.stencilWriteMask !== 255) data.stencilWriteMask = this.stencilWriteMask; + if (this.stencilFunc !== AlwaysStencilFunc) data.stencilFunc = this.stencilFunc; + if (this.stencilRef !== 0) data.stencilRef = this.stencilRef; + if (this.stencilFuncMask !== 255) data.stencilFuncMask = this.stencilFuncMask; + if (this.stencilFail !== KeepStencilOp) data.stencilFail = this.stencilFail; + if (this.stencilZFail !== KeepStencilOp) data.stencilZFail = this.stencilZFail; + if (this.stencilZPass !== KeepStencilOp) data.stencilZPass = this.stencilZPass; + if (this.stencilWrite === true) data.stencilWrite = this.stencilWrite; + if (this.rotation !== void 0 && this.rotation !== 0) data.rotation = this.rotation; + if (this.polygonOffset === true) data.polygonOffset = true; + if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor; + if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits; + if (this.linewidth !== void 0 && this.linewidth !== 1) data.linewidth = this.linewidth; + if (this.dashSize !== void 0) data.dashSize = this.dashSize; + if (this.gapSize !== void 0) data.gapSize = this.gapSize; + if (this.scale !== void 0) data.scale = this.scale; + if (this.dithering === true) data.dithering = true; + if (this.alphaTest > 0) data.alphaTest = this.alphaTest; + if (this.alphaHash === true) data.alphaHash = true; + if (this.alphaToCoverage === true) data.alphaToCoverage = true; + if (this.premultipliedAlpha === true) data.premultipliedAlpha = true; + if (this.forceSinglePass === true) data.forceSinglePass = true; + if (this.wireframe === true) data.wireframe = true; + if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth; + if (this.wireframeLinecap !== "round") data.wireframeLinecap = this.wireframeLinecap; + if (this.wireframeLinejoin !== "round") data.wireframeLinejoin = this.wireframeLinejoin; + if (this.flatShading === true) data.flatShading = true; + if (this.visible === false) data.visible = false; + if (this.toneMapped === false) data.toneMapped = false; + if (this.fog === false) data.fog = false; + if (Object.keys(this.userData).length > 0) data.userData = this.userData; + function extractFromCache(cache) { + const values = []; + for (const key in cache) { + const data2 = cache[key]; + delete data2.metadata; + values.push(data2); + } + return values; + } + if (isRootObject) { + const textures = extractFromCache(meta.textures); + const images = extractFromCache(meta.images); + if (textures.length > 0) data.textures = textures; + if (images.length > 0) data.images = images; + } + return data; + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.name = source.name; + this.blending = source.blending; + this.side = source.side; + this.vertexColors = source.vertexColors; + this.opacity = source.opacity; + this.transparent = source.transparent; + this.blendSrc = source.blendSrc; + this.blendDst = source.blendDst; + this.blendEquation = source.blendEquation; + this.blendSrcAlpha = source.blendSrcAlpha; + this.blendDstAlpha = source.blendDstAlpha; + this.blendEquationAlpha = source.blendEquationAlpha; + this.blendColor.copy(source.blendColor); + this.blendAlpha = source.blendAlpha; + this.depthFunc = source.depthFunc; + this.depthTest = source.depthTest; + this.depthWrite = source.depthWrite; + this.stencilWriteMask = source.stencilWriteMask; + this.stencilFunc = source.stencilFunc; + this.stencilRef = source.stencilRef; + this.stencilFuncMask = source.stencilFuncMask; + this.stencilFail = source.stencilFail; + this.stencilZFail = source.stencilZFail; + this.stencilZPass = source.stencilZPass; + this.stencilWrite = source.stencilWrite; + const srcPlanes = source.clippingPlanes; + let dstPlanes = null; + if (srcPlanes !== null) { + const n = srcPlanes.length; + dstPlanes = new Array(n); + for (let i = 0; i !== n; ++i) { + dstPlanes[i] = srcPlanes[i].clone(); + } + } + this.clippingPlanes = dstPlanes; + this.clipIntersection = source.clipIntersection; + this.clipShadows = source.clipShadows; + this.shadowSide = source.shadowSide; + this.colorWrite = source.colorWrite; + this.precision = source.precision; + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; + this.dithering = source.dithering; + this.alphaTest = source.alphaTest; + this.alphaHash = source.alphaHash; + this.alphaToCoverage = source.alphaToCoverage; + this.premultipliedAlpha = source.premultipliedAlpha; + this.forceSinglePass = source.forceSinglePass; + this.visible = source.visible; + this.toneMapped = source.toneMapped; + this.userData = JSON.parse(JSON.stringify(source.userData)); + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + set needsUpdate(value) { + if (value === true) this.version++; + } + }; + var MeshBasicMaterial = class extends Material { + constructor(parameters) { + super(); + this.isMeshBasicMaterial = true; + this.type = "MeshBasicMaterial"; + this.color = new Color(16777215); + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; + } + }; + var _tables = /* @__PURE__ */ _generateTables(); + function _generateTables() { + const buffer = new ArrayBuffer(4); + const floatView = new Float32Array(buffer); + const uint32View = new Uint32Array(buffer); + const baseTable = new Uint32Array(512); + const shiftTable = new Uint32Array(512); + for (let i = 0; i < 256; ++i) { + const e = i - 127; + if (e < -27) { + baseTable[i] = 0; + baseTable[i | 256] = 32768; + shiftTable[i] = 24; + shiftTable[i | 256] = 24; + } else if (e < -14) { + baseTable[i] = 1024 >> -e - 14; + baseTable[i | 256] = 1024 >> -e - 14 | 32768; + shiftTable[i] = -e - 1; + shiftTable[i | 256] = -e - 1; + } else if (e <= 15) { + baseTable[i] = e + 15 << 10; + baseTable[i | 256] = e + 15 << 10 | 32768; + shiftTable[i] = 13; + shiftTable[i | 256] = 13; + } else if (e < 128) { + baseTable[i] = 31744; + baseTable[i | 256] = 64512; + shiftTable[i] = 24; + shiftTable[i | 256] = 24; + } else { + baseTable[i] = 31744; + baseTable[i | 256] = 64512; + shiftTable[i] = 13; + shiftTable[i | 256] = 13; + } + } + const mantissaTable = new Uint32Array(2048); + const exponentTable = new Uint32Array(64); + const offsetTable = new Uint32Array(64); + for (let i = 1; i < 1024; ++i) { + let m = i << 13; + let e = 0; + while ((m & 8388608) === 0) { + m <<= 1; + e -= 8388608; + } + m &= ~8388608; + e += 947912704; + mantissaTable[i] = m | e; + } + for (let i = 1024; i < 2048; ++i) { + mantissaTable[i] = 939524096 + (i - 1024 << 13); + } + for (let i = 1; i < 31; ++i) { + exponentTable[i] = i << 23; + } + exponentTable[31] = 1199570944; + exponentTable[32] = 2147483648; + for (let i = 33; i < 63; ++i) { + exponentTable[i] = 2147483648 + (i - 32 << 23); + } + exponentTable[63] = 3347054592; + for (let i = 1; i < 64; ++i) { + if (i !== 32) { + offsetTable[i] = 1024; + } + } + return { + floatView, + uint32View, + baseTable, + shiftTable, + mantissaTable, + exponentTable, + offsetTable + }; + } + function toHalfFloat(val) { + if (Math.abs(val) > 65504) console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."); + val = clamp(val, -65504, 65504); + _tables.floatView[0] = val; + const f = _tables.uint32View[0]; + const e = f >> 23 & 511; + return _tables.baseTable[e] + ((f & 8388607) >> _tables.shiftTable[e]); + } + function fromHalfFloat(val) { + const m = val >> 10; + _tables.uint32View[0] = _tables.mantissaTable[_tables.offsetTable[m] + (val & 1023)] + _tables.exponentTable[m]; + return _tables.floatView[0]; + } + var DataUtils = { + toHalfFloat, + fromHalfFloat + }; + var _vector$9 = /* @__PURE__ */ new Vector3(); + var _vector2$1 = /* @__PURE__ */ new Vector2(); + var BufferAttribute = class { + constructor(array, itemSize, normalized = false) { + if (Array.isArray(array)) { + throw new TypeError("THREE.BufferAttribute: array should be a Typed Array."); + } + this.isBufferAttribute = true; + this.name = ""; + this.array = array; + this.itemSize = itemSize; + this.count = array !== void 0 ? array.length / itemSize : 0; + this.normalized = normalized; + this.usage = StaticDrawUsage; + this._updateRange = { offset: 0, count: -1 }; + this.updateRanges = []; + this.gpuType = FloatType; + this.version = 0; + } + onUploadCallback() { + } + set needsUpdate(value) { + if (value === true) this.version++; + } + get updateRange() { + console.warn("THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead."); + return this._updateRange; + } + setUsage(value) { + this.usage = value; + return this; + } + addUpdateRange(start, count) { + this.updateRanges.push({ start, count }); + } + clearUpdateRanges() { + this.updateRanges.length = 0; + } + copy(source) { + this.name = source.name; + this.array = new source.array.constructor(source.array); + this.itemSize = source.itemSize; + this.count = source.count; + this.normalized = source.normalized; + this.usage = source.usage; + this.gpuType = source.gpuType; + return this; + } + copyAt(index1, attribute, index2) { + index1 *= this.itemSize; + index2 *= attribute.itemSize; + for (let i = 0, l = this.itemSize; i < l; i++) { + this.array[index1 + i] = attribute.array[index2 + i]; + } + return this; + } + copyArray(array) { + this.array.set(array); + return this; + } + applyMatrix3(m) { + if (this.itemSize === 2) { + for (let i = 0, l = this.count; i < l; i++) { + _vector2$1.fromBufferAttribute(this, i); + _vector2$1.applyMatrix3(m); + this.setXY(i, _vector2$1.x, _vector2$1.y); + } + } else if (this.itemSize === 3) { + for (let i = 0, l = this.count; i < l; i++) { + _vector$9.fromBufferAttribute(this, i); + _vector$9.applyMatrix3(m); + this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); + } + } + return this; + } + applyMatrix4(m) { + for (let i = 0, l = this.count; i < l; i++) { + _vector$9.fromBufferAttribute(this, i); + _vector$9.applyMatrix4(m); + this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); + } + return this; + } + applyNormalMatrix(m) { + for (let i = 0, l = this.count; i < l; i++) { + _vector$9.fromBufferAttribute(this, i); + _vector$9.applyNormalMatrix(m); + this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); + } + return this; + } + transformDirection(m) { + for (let i = 0, l = this.count; i < l; i++) { + _vector$9.fromBufferAttribute(this, i); + _vector$9.transformDirection(m); + this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); + } + return this; + } + set(value, offset = 0) { + this.array.set(value, offset); + return this; + } + getComponent(index, component) { + let value = this.array[index * this.itemSize + component]; + if (this.normalized) value = denormalize(value, this.array); + return value; + } + setComponent(index, component, value) { + if (this.normalized) value = normalize(value, this.array); + this.array[index * this.itemSize + component] = value; + return this; + } + getX(index) { + let x = this.array[index * this.itemSize]; + if (this.normalized) x = denormalize(x, this.array); + return x; + } + setX(index, x) { + if (this.normalized) x = normalize(x, this.array); + this.array[index * this.itemSize] = x; + return this; + } + getY(index) { + let y = this.array[index * this.itemSize + 1]; + if (this.normalized) y = denormalize(y, this.array); + return y; + } + setY(index, y) { + if (this.normalized) y = normalize(y, this.array); + this.array[index * this.itemSize + 1] = y; + return this; + } + getZ(index) { + let z = this.array[index * this.itemSize + 2]; + if (this.normalized) z = denormalize(z, this.array); + return z; + } + setZ(index, z) { + if (this.normalized) z = normalize(z, this.array); + this.array[index * this.itemSize + 2] = z; + return this; + } + getW(index) { + let w = this.array[index * this.itemSize + 3]; + if (this.normalized) w = denormalize(w, this.array); + return w; + } + setW(index, w) { + if (this.normalized) w = normalize(w, this.array); + this.array[index * this.itemSize + 3] = w; + return this; + } + setXY(index, x, y) { + index *= this.itemSize; + if (this.normalized) { + x = normalize(x, this.array); + y = normalize(y, this.array); + } + this.array[index + 0] = x; + this.array[index + 1] = y; + return this; + } + setXYZ(index, x, y, z) { + index *= this.itemSize; + if (this.normalized) { + x = normalize(x, this.array); + y = normalize(y, this.array); + z = normalize(z, this.array); + } + this.array[index + 0] = x; + this.array[index + 1] = y; + this.array[index + 2] = z; + return this; + } + setXYZW(index, x, y, z, w) { + index *= this.itemSize; + if (this.normalized) { + x = normalize(x, this.array); + y = normalize(y, this.array); + z = normalize(z, this.array); + w = normalize(w, this.array); + } + this.array[index + 0] = x; + this.array[index + 1] = y; + this.array[index + 2] = z; + this.array[index + 3] = w; + return this; + } + onUpload(callback) { + this.onUploadCallback = callback; + return this; + } + clone() { + return new this.constructor(this.array, this.itemSize).copy(this); + } + toJSON() { + const data = { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: Array.from(this.array), + normalized: this.normalized + }; + if (this.name !== "") data.name = this.name; + if (this.usage !== StaticDrawUsage) data.usage = this.usage; + return data; + } + }; + var Int8BufferAttribute = class extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Int8Array(array), itemSize, normalized); + } + }; + var Uint8BufferAttribute = class extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Uint8Array(array), itemSize, normalized); + } + }; + var Uint8ClampedBufferAttribute = class extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Uint8ClampedArray(array), itemSize, normalized); + } + }; + var Int16BufferAttribute = class extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Int16Array(array), itemSize, normalized); + } + }; + var Uint16BufferAttribute = class extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Uint16Array(array), itemSize, normalized); + } + }; + var Int32BufferAttribute = class extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Int32Array(array), itemSize, normalized); + } + }; + var Uint32BufferAttribute = class extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Uint32Array(array), itemSize, normalized); + } + }; + var Float16BufferAttribute = class extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Uint16Array(array), itemSize, normalized); + this.isFloat16BufferAttribute = true; + } + getX(index) { + let x = fromHalfFloat(this.array[index * this.itemSize]); + if (this.normalized) x = denormalize(x, this.array); + return x; + } + setX(index, x) { + if (this.normalized) x = normalize(x, this.array); + this.array[index * this.itemSize] = toHalfFloat(x); + return this; + } + getY(index) { + let y = fromHalfFloat(this.array[index * this.itemSize + 1]); + if (this.normalized) y = denormalize(y, this.array); + return y; + } + setY(index, y) { + if (this.normalized) y = normalize(y, this.array); + this.array[index * this.itemSize + 1] = toHalfFloat(y); + return this; + } + getZ(index) { + let z = fromHalfFloat(this.array[index * this.itemSize + 2]); + if (this.normalized) z = denormalize(z, this.array); + return z; + } + setZ(index, z) { + if (this.normalized) z = normalize(z, this.array); + this.array[index * this.itemSize + 2] = toHalfFloat(z); + return this; + } + getW(index) { + let w = fromHalfFloat(this.array[index * this.itemSize + 3]); + if (this.normalized) w = denormalize(w, this.array); + return w; + } + setW(index, w) { + if (this.normalized) w = normalize(w, this.array); + this.array[index * this.itemSize + 3] = toHalfFloat(w); + return this; + } + setXY(index, x, y) { + index *= this.itemSize; + if (this.normalized) { + x = normalize(x, this.array); + y = normalize(y, this.array); + } + this.array[index + 0] = toHalfFloat(x); + this.array[index + 1] = toHalfFloat(y); + return this; + } + setXYZ(index, x, y, z) { + index *= this.itemSize; + if (this.normalized) { + x = normalize(x, this.array); + y = normalize(y, this.array); + z = normalize(z, this.array); + } + this.array[index + 0] = toHalfFloat(x); + this.array[index + 1] = toHalfFloat(y); + this.array[index + 2] = toHalfFloat(z); + return this; + } + setXYZW(index, x, y, z, w) { + index *= this.itemSize; + if (this.normalized) { + x = normalize(x, this.array); + y = normalize(y, this.array); + z = normalize(z, this.array); + w = normalize(w, this.array); + } + this.array[index + 0] = toHalfFloat(x); + this.array[index + 1] = toHalfFloat(y); + this.array[index + 2] = toHalfFloat(z); + this.array[index + 3] = toHalfFloat(w); + return this; + } + }; + var Float32BufferAttribute = class extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Float32Array(array), itemSize, normalized); + } + }; + var Float64BufferAttribute = class extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Float64Array(array), itemSize, normalized); + } + }; + var _id$2 = 0; + var _m1 = /* @__PURE__ */ new Matrix4(); + var _obj = /* @__PURE__ */ new Object3D(); + var _offset = /* @__PURE__ */ new Vector3(); + var _box$2 = /* @__PURE__ */ new Box3(); + var _boxMorphTargets = /* @__PURE__ */ new Box3(); + var _vector$8 = /* @__PURE__ */ new Vector3(); + var BufferGeometry = class _BufferGeometry extends EventDispatcher { + constructor() { + super(); + this.isBufferGeometry = true; + Object.defineProperty(this, "id", { value: _id$2++ }); + this.uuid = generateUUID(); + this.name = ""; + this.type = "BufferGeometry"; + this.index = null; + this.attributes = {}; + this.morphAttributes = {}; + this.morphTargetsRelative = false; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + this.drawRange = { start: 0, count: Infinity }; + this.userData = {}; + } + getIndex() { + return this.index; + } + setIndex(index) { + if (Array.isArray(index)) { + this.index = new (arrayNeedsUint32(index) ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1); + } else { + this.index = index; + } + return this; + } + getAttribute(name) { + return this.attributes[name]; + } + setAttribute(name, attribute) { + this.attributes[name] = attribute; + return this; + } + deleteAttribute(name) { + delete this.attributes[name]; + return this; + } + hasAttribute(name) { + return this.attributes[name] !== void 0; + } + addGroup(start, count, materialIndex = 0) { + this.groups.push({ + start, + count, + materialIndex + }); + } + clearGroups() { + this.groups = []; + } + setDrawRange(start, count) { + this.drawRange.start = start; + this.drawRange.count = count; + } + applyMatrix4(matrix) { + const position = this.attributes.position; + if (position !== void 0) { + position.applyMatrix4(matrix); + position.needsUpdate = true; + } + const normal = this.attributes.normal; + if (normal !== void 0) { + const normalMatrix = new Matrix3().getNormalMatrix(matrix); + normal.applyNormalMatrix(normalMatrix); + normal.needsUpdate = true; + } + const tangent = this.attributes.tangent; + if (tangent !== void 0) { + tangent.transformDirection(matrix); + tangent.needsUpdate = true; + } + if (this.boundingBox !== null) { + this.computeBoundingBox(); + } + if (this.boundingSphere !== null) { + this.computeBoundingSphere(); + } + return this; + } + applyQuaternion(q) { + _m1.makeRotationFromQuaternion(q); + this.applyMatrix4(_m1); + return this; + } + rotateX(angle) { + _m1.makeRotationX(angle); + this.applyMatrix4(_m1); + return this; + } + rotateY(angle) { + _m1.makeRotationY(angle); + this.applyMatrix4(_m1); + return this; + } + rotateZ(angle) { + _m1.makeRotationZ(angle); + this.applyMatrix4(_m1); + return this; + } + translate(x, y, z) { + _m1.makeTranslation(x, y, z); + this.applyMatrix4(_m1); + return this; + } + scale(x, y, z) { + _m1.makeScale(x, y, z); + this.applyMatrix4(_m1); + return this; + } + lookAt(vector) { + _obj.lookAt(vector); + _obj.updateMatrix(); + this.applyMatrix4(_obj.matrix); + return this; + } + center() { + this.computeBoundingBox(); + this.boundingBox.getCenter(_offset).negate(); + this.translate(_offset.x, _offset.y, _offset.z); + return this; + } + setFromPoints(points) { + const position = []; + for (let i = 0, l = points.length; i < l; i++) { + const point = points[i]; + position.push(point.x, point.y, point.z || 0); + } + this.setAttribute("position", new Float32BufferAttribute(position, 3)); + return this; + } + computeBoundingBox() { + if (this.boundingBox === null) { + this.boundingBox = new Box3(); + } + const position = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + if (position && position.isGLBufferAttribute) { + console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this); + this.boundingBox.set( + new Vector3(-Infinity, -Infinity, -Infinity), + new Vector3(Infinity, Infinity, Infinity) + ); + return; + } + if (position !== void 0) { + this.boundingBox.setFromBufferAttribute(position); + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length; i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + _box$2.setFromBufferAttribute(morphAttribute); + if (this.morphTargetsRelative) { + _vector$8.addVectors(this.boundingBox.min, _box$2.min); + this.boundingBox.expandByPoint(_vector$8); + _vector$8.addVectors(this.boundingBox.max, _box$2.max); + this.boundingBox.expandByPoint(_vector$8); + } else { + this.boundingBox.expandByPoint(_box$2.min); + this.boundingBox.expandByPoint(_box$2.max); + } + } + } + } else { + this.boundingBox.makeEmpty(); + } + if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) { + console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this); + } + } + computeBoundingSphere() { + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere(); + } + const position = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + if (position && position.isGLBufferAttribute) { + console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this); + this.boundingSphere.set(new Vector3(), Infinity); + return; + } + if (position) { + const center = this.boundingSphere.center; + _box$2.setFromBufferAttribute(position); + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length; i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + _boxMorphTargets.setFromBufferAttribute(morphAttribute); + if (this.morphTargetsRelative) { + _vector$8.addVectors(_box$2.min, _boxMorphTargets.min); + _box$2.expandByPoint(_vector$8); + _vector$8.addVectors(_box$2.max, _boxMorphTargets.max); + _box$2.expandByPoint(_vector$8); + } else { + _box$2.expandByPoint(_boxMorphTargets.min); + _box$2.expandByPoint(_boxMorphTargets.max); + } + } + } + _box$2.getCenter(center); + let maxRadiusSq = 0; + for (let i = 0, il = position.count; i < il; i++) { + _vector$8.fromBufferAttribute(position, i); + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8)); + } + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length; i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + const morphTargetsRelative = this.morphTargetsRelative; + for (let j = 0, jl = morphAttribute.count; j < jl; j++) { + _vector$8.fromBufferAttribute(morphAttribute, j); + if (morphTargetsRelative) { + _offset.fromBufferAttribute(position, j); + _vector$8.add(_offset); + } + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8)); + } + } + } + this.boundingSphere.radius = Math.sqrt(maxRadiusSq); + if (isNaN(this.boundingSphere.radius)) { + console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this); + } + } + } + computeTangents() { + const index = this.index; + const attributes = this.attributes; + if (index === null || attributes.position === void 0 || attributes.normal === void 0 || attributes.uv === void 0) { + console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)"); + return; + } + const indices = index.array; + const positions = attributes.position.array; + const normals = attributes.normal.array; + const uvs = attributes.uv.array; + const nVertices = positions.length / 3; + if (this.hasAttribute("tangent") === false) { + this.setAttribute("tangent", new BufferAttribute(new Float32Array(4 * nVertices), 4)); + } + const tangents = this.getAttribute("tangent").array; + const tan1 = [], tan2 = []; + for (let i = 0; i < nVertices; i++) { + tan1[i] = new Vector3(); + tan2[i] = new Vector3(); + } + const vA = new Vector3(), vB = new Vector3(), vC = new Vector3(), uvA = new Vector2(), uvB = new Vector2(), uvC = new Vector2(), sdir = new Vector3(), tdir = new Vector3(); + function handleTriangle(a, b, c) { + vA.fromArray(positions, a * 3); + vB.fromArray(positions, b * 3); + vC.fromArray(positions, c * 3); + uvA.fromArray(uvs, a * 2); + uvB.fromArray(uvs, b * 2); + uvC.fromArray(uvs, c * 2); + vB.sub(vA); + vC.sub(vA); + uvB.sub(uvA); + uvC.sub(uvA); + const r = 1 / (uvB.x * uvC.y - uvC.x * uvB.y); + if (!isFinite(r)) return; + sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r); + tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r); + tan1[a].add(sdir); + tan1[b].add(sdir); + tan1[c].add(sdir); + tan2[a].add(tdir); + tan2[b].add(tdir); + tan2[c].add(tdir); + } + let groups = this.groups; + if (groups.length === 0) { + groups = [{ + start: 0, + count: indices.length + }]; + } + for (let i = 0, il = groups.length; i < il; ++i) { + const group = groups[i]; + const start = group.start; + const count = group.count; + for (let j = start, jl = start + count; j < jl; j += 3) { + handleTriangle( + indices[j + 0], + indices[j + 1], + indices[j + 2] + ); + } + } + const tmp2 = new Vector3(), tmp22 = new Vector3(); + const n = new Vector3(), n2 = new Vector3(); + function handleVertex(v) { + n.fromArray(normals, v * 3); + n2.copy(n); + const t = tan1[v]; + tmp2.copy(t); + tmp2.sub(n.multiplyScalar(n.dot(t))).normalize(); + tmp22.crossVectors(n2, t); + const test = tmp22.dot(tan2[v]); + const w = test < 0 ? -1 : 1; + tangents[v * 4] = tmp2.x; + tangents[v * 4 + 1] = tmp2.y; + tangents[v * 4 + 2] = tmp2.z; + tangents[v * 4 + 3] = w; + } + for (let i = 0, il = groups.length; i < il; ++i) { + const group = groups[i]; + const start = group.start; + const count = group.count; + for (let j = start, jl = start + count; j < jl; j += 3) { + handleVertex(indices[j + 0]); + handleVertex(indices[j + 1]); + handleVertex(indices[j + 2]); + } + } + } + computeVertexNormals() { + const index = this.index; + const positionAttribute = this.getAttribute("position"); + if (positionAttribute !== void 0) { + let normalAttribute = this.getAttribute("normal"); + if (normalAttribute === void 0) { + normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3); + this.setAttribute("normal", normalAttribute); + } else { + for (let i = 0, il = normalAttribute.count; i < il; i++) { + normalAttribute.setXYZ(i, 0, 0, 0); + } + } + const pA = new Vector3(), pB = new Vector3(), pC = new Vector3(); + const nA = new Vector3(), nB = new Vector3(), nC = new Vector3(); + const cb = new Vector3(), ab = new Vector3(); + if (index) { + for (let i = 0, il = index.count; i < il; i += 3) { + const vA = index.getX(i + 0); + const vB = index.getX(i + 1); + const vC = index.getX(i + 2); + pA.fromBufferAttribute(positionAttribute, vA); + pB.fromBufferAttribute(positionAttribute, vB); + pC.fromBufferAttribute(positionAttribute, vC); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + nA.fromBufferAttribute(normalAttribute, vA); + nB.fromBufferAttribute(normalAttribute, vB); + nC.fromBufferAttribute(normalAttribute, vC); + nA.add(cb); + nB.add(cb); + nC.add(cb); + normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z); + normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z); + normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z); + } + } else { + for (let i = 0, il = positionAttribute.count; i < il; i += 3) { + pA.fromBufferAttribute(positionAttribute, i + 0); + pB.fromBufferAttribute(positionAttribute, i + 1); + pC.fromBufferAttribute(positionAttribute, i + 2); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z); + normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z); + normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z); + } + } + this.normalizeNormals(); + normalAttribute.needsUpdate = true; + } + } + normalizeNormals() { + const normals = this.attributes.normal; + for (let i = 0, il = normals.count; i < il; i++) { + _vector$8.fromBufferAttribute(normals, i); + _vector$8.normalize(); + normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z); + } + } + toNonIndexed() { + function convertBufferAttribute(attribute, indices2) { + const array = attribute.array; + const itemSize = attribute.itemSize; + const normalized = attribute.normalized; + const array2 = new array.constructor(indices2.length * itemSize); + let index = 0, index2 = 0; + for (let i = 0, l = indices2.length; i < l; i++) { + if (attribute.isInterleavedBufferAttribute) { + index = indices2[i] * attribute.data.stride + attribute.offset; + } else { + index = indices2[i] * itemSize; + } + for (let j = 0; j < itemSize; j++) { + array2[index2++] = array[index++]; + } + } + return new BufferAttribute(array2, itemSize, normalized); + } + if (this.index === null) { + console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."); + return this; + } + const geometry2 = new _BufferGeometry(); + const indices = this.index.array; + const attributes = this.attributes; + for (const name in attributes) { + const attribute = attributes[name]; + const newAttribute = convertBufferAttribute(attribute, indices); + geometry2.setAttribute(name, newAttribute); + } + const morphAttributes = this.morphAttributes; + for (const name in morphAttributes) { + const morphArray = []; + const morphAttribute = morphAttributes[name]; + for (let i = 0, il = morphAttribute.length; i < il; i++) { + const attribute = morphAttribute[i]; + const newAttribute = convertBufferAttribute(attribute, indices); + morphArray.push(newAttribute); + } + geometry2.morphAttributes[name] = morphArray; + } + geometry2.morphTargetsRelative = this.morphTargetsRelative; + const groups = this.groups; + for (let i = 0, l = groups.length; i < l; i++) { + const group = groups[i]; + geometry2.addGroup(group.start, group.count, group.materialIndex); + } + return geometry2; + } + toJSON() { + const data = { + metadata: { + version: 4.6, + type: "BufferGeometry", + generator: "BufferGeometry.toJSON" + } + }; + data.uuid = this.uuid; + data.type = this.type; + if (this.name !== "") data.name = this.name; + if (Object.keys(this.userData).length > 0) data.userData = this.userData; + if (this.parameters !== void 0) { + const parameters = this.parameters; + for (const key in parameters) { + if (parameters[key] !== void 0) data[key] = parameters[key]; + } + return data; + } + data.data = { attributes: {} }; + const index = this.index; + if (index !== null) { + data.data.index = { + type: index.array.constructor.name, + array: Array.prototype.slice.call(index.array) + }; + } + const attributes = this.attributes; + for (const key in attributes) { + const attribute = attributes[key]; + data.data.attributes[key] = attribute.toJSON(data.data); + } + const morphAttributes = {}; + let hasMorphAttributes = false; + for (const key in this.morphAttributes) { + const attributeArray = this.morphAttributes[key]; + const array = []; + for (let i = 0, il = attributeArray.length; i < il; i++) { + const attribute = attributeArray[i]; + array.push(attribute.toJSON(data.data)); + } + if (array.length > 0) { + morphAttributes[key] = array; + hasMorphAttributes = true; + } + } + if (hasMorphAttributes) { + data.data.morphAttributes = morphAttributes; + data.data.morphTargetsRelative = this.morphTargetsRelative; + } + const groups = this.groups; + if (groups.length > 0) { + data.data.groups = JSON.parse(JSON.stringify(groups)); + } + const boundingSphere = this.boundingSphere; + if (boundingSphere !== null) { + data.data.boundingSphere = { + center: boundingSphere.center.toArray(), + radius: boundingSphere.radius + }; + } + return data; + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.index = null; + this.attributes = {}; + this.morphAttributes = {}; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + const data = {}; + this.name = source.name; + const index = source.index; + if (index !== null) { + this.setIndex(index.clone(data)); + } + const attributes = source.attributes; + for (const name in attributes) { + const attribute = attributes[name]; + this.setAttribute(name, attribute.clone(data)); + } + const morphAttributes = source.morphAttributes; + for (const name in morphAttributes) { + const array = []; + const morphAttribute = morphAttributes[name]; + for (let i = 0, l = morphAttribute.length; i < l; i++) { + array.push(morphAttribute[i].clone(data)); + } + this.morphAttributes[name] = array; + } + this.morphTargetsRelative = source.morphTargetsRelative; + const groups = source.groups; + for (let i = 0, l = groups.length; i < l; i++) { + const group = groups[i]; + this.addGroup(group.start, group.count, group.materialIndex); + } + const boundingBox = source.boundingBox; + if (boundingBox !== null) { + this.boundingBox = boundingBox.clone(); + } + const boundingSphere = source.boundingSphere; + if (boundingSphere !== null) { + this.boundingSphere = boundingSphere.clone(); + } + this.drawRange.start = source.drawRange.start; + this.drawRange.count = source.drawRange.count; + this.userData = source.userData; + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + }; + var _inverseMatrix$3 = /* @__PURE__ */ new Matrix4(); + var _ray$3 = /* @__PURE__ */ new Ray(); + var _sphere$6 = /* @__PURE__ */ new Sphere(); + var _sphereHitAt = /* @__PURE__ */ new Vector3(); + var _vA$1 = /* @__PURE__ */ new Vector3(); + var _vB$1 = /* @__PURE__ */ new Vector3(); + var _vC$1 = /* @__PURE__ */ new Vector3(); + var _tempA = /* @__PURE__ */ new Vector3(); + var _morphA = /* @__PURE__ */ new Vector3(); + var _uvA$1 = /* @__PURE__ */ new Vector2(); + var _uvB$1 = /* @__PURE__ */ new Vector2(); + var _uvC$1 = /* @__PURE__ */ new Vector2(); + var _normalA = /* @__PURE__ */ new Vector3(); + var _normalB = /* @__PURE__ */ new Vector3(); + var _normalC = /* @__PURE__ */ new Vector3(); + var _intersectionPoint = /* @__PURE__ */ new Vector3(); + var _intersectionPointWorld = /* @__PURE__ */ new Vector3(); + var Mesh = class extends Object3D { + constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) { + super(); + this.isMesh = true; + this.type = "Mesh"; + this.geometry = geometry; + this.material = material; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.morphTargetInfluences !== void 0) { + this.morphTargetInfluences = source.morphTargetInfluences.slice(); + } + if (source.morphTargetDictionary !== void 0) { + this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary); + } + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys(morphAttributes); + if (keys.length > 0) { + const morphAttribute = morphAttributes[keys[0]]; + if (morphAttribute !== void 0) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length; m < ml; m++) { + const name = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name] = m; + } + } + } + } + getVertexPosition(index, target) { + const geometry = this.geometry; + const position = geometry.attributes.position; + const morphPosition = geometry.morphAttributes.position; + const morphTargetsRelative = geometry.morphTargetsRelative; + target.fromBufferAttribute(position, index); + const morphInfluences = this.morphTargetInfluences; + if (morphPosition && morphInfluences) { + _morphA.set(0, 0, 0); + for (let i = 0, il = morphPosition.length; i < il; i++) { + const influence = morphInfluences[i]; + const morphAttribute = morphPosition[i]; + if (influence === 0) continue; + _tempA.fromBufferAttribute(morphAttribute, index); + if (morphTargetsRelative) { + _morphA.addScaledVector(_tempA, influence); + } else { + _morphA.addScaledVector(_tempA.sub(target), influence); + } + } + target.add(_morphA); + } + return target; + } + raycast(raycaster, intersects2) { + const geometry = this.geometry; + const material = this.material; + const matrixWorld = this.matrixWorld; + if (material === void 0) return; + if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); + _sphere$6.copy(geometry.boundingSphere); + _sphere$6.applyMatrix4(matrixWorld); + _ray$3.copy(raycaster.ray).recast(raycaster.near); + if (_sphere$6.containsPoint(_ray$3.origin) === false) { + if (_ray$3.intersectSphere(_sphere$6, _sphereHitAt) === null) return; + if (_ray$3.origin.distanceToSquared(_sphereHitAt) > (raycaster.far - raycaster.near) ** 2) return; + } + _inverseMatrix$3.copy(matrixWorld).invert(); + _ray$3.copy(raycaster.ray).applyMatrix4(_inverseMatrix$3); + if (geometry.boundingBox !== null) { + if (_ray$3.intersectsBox(geometry.boundingBox) === false) return; + } + this._computeIntersections(raycaster, intersects2, _ray$3); + } + _computeIntersections(raycaster, intersects2, rayLocalSpace) { + let intersection; + const geometry = this.geometry; + const material = this.material; + const index = geometry.index; + const position = geometry.attributes.position; + const uv = geometry.attributes.uv; + const uv1 = geometry.attributes.uv1; + const normal = geometry.attributes.normal; + const groups = geometry.groups; + const drawRange = geometry.drawRange; + if (index !== null) { + if (Array.isArray(material)) { + for (let i = 0, il = groups.length; i < il; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + const start = Math.max(group.start, drawRange.start); + const end = Math.min(index.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); + for (let j = start, jl = end; j < jl; j += 3) { + const a = index.getX(j); + const b = index.getX(j + 1); + const c = index.getX(j + 2); + intersection = checkGeometryIntersection(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(j / 3); + intersection.face.materialIndex = group.materialIndex; + intersects2.push(intersection); + } + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(index.count, drawRange.start + drawRange.count); + for (let i = start, il = end; i < il; i += 3) { + const a = index.getX(i); + const b = index.getX(i + 1); + const c = index.getX(i + 2); + intersection = checkGeometryIntersection(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(i / 3); + intersects2.push(intersection); + } + } + } + } else if (position !== void 0) { + if (Array.isArray(material)) { + for (let i = 0, il = groups.length; i < il; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + const start = Math.max(group.start, drawRange.start); + const end = Math.min(position.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); + for (let j = start, jl = end; j < jl; j += 3) { + const a = j; + const b = j + 1; + const c = j + 2; + intersection = checkGeometryIntersection(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(j / 3); + intersection.face.materialIndex = group.materialIndex; + intersects2.push(intersection); + } + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(position.count, drawRange.start + drawRange.count); + for (let i = start, il = end; i < il; i += 3) { + const a = i; + const b = i + 1; + const c = i + 2; + intersection = checkGeometryIntersection(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(i / 3); + intersects2.push(intersection); + } + } + } + } + } + }; + function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) { + let intersect; + if (material.side === BackSide) { + intersect = ray.intersectTriangle(pC, pB, pA, true, point); + } else { + intersect = ray.intersectTriangle(pA, pB, pC, material.side === FrontSide, point); + } + if (intersect === null) return null; + _intersectionPointWorld.copy(point); + _intersectionPointWorld.applyMatrix4(object.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld); + if (distance < raycaster.near || distance > raycaster.far) return null; + return { + distance, + point: _intersectionPointWorld.clone(), + object + }; + } + function checkGeometryIntersection(object, material, raycaster, ray, uv, uv1, normal, a, b, c) { + object.getVertexPosition(a, _vA$1); + object.getVertexPosition(b, _vB$1); + object.getVertexPosition(c, _vC$1); + const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint); + if (intersection) { + if (uv) { + _uvA$1.fromBufferAttribute(uv, a); + _uvB$1.fromBufferAttribute(uv, b); + _uvC$1.fromBufferAttribute(uv, c); + intersection.uv = Triangle.getInterpolation(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()); + } + if (uv1) { + _uvA$1.fromBufferAttribute(uv1, a); + _uvB$1.fromBufferAttribute(uv1, b); + _uvC$1.fromBufferAttribute(uv1, c); + intersection.uv1 = Triangle.getInterpolation(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()); + intersection.uv2 = intersection.uv1; + } + if (normal) { + _normalA.fromBufferAttribute(normal, a); + _normalB.fromBufferAttribute(normal, b); + _normalC.fromBufferAttribute(normal, c); + intersection.normal = Triangle.getInterpolation(_intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3()); + if (intersection.normal.dot(ray.direction) > 0) { + intersection.normal.multiplyScalar(-1); + } + } + const face = { + a, + b, + c, + normal: new Vector3(), + materialIndex: 0 + }; + Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal); + intersection.face = face; + } + return intersection; + } + var BoxGeometry = class _BoxGeometry extends BufferGeometry { + constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) { + super(); + this.type = "BoxGeometry"; + this.parameters = { + width, + height, + depth, + widthSegments, + heightSegments, + depthSegments + }; + const scope = this; + widthSegments = Math.floor(widthSegments); + heightSegments = Math.floor(heightSegments); + depthSegments = Math.floor(depthSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let numberOfVertices = 0; + let groupStart = 0; + buildPlane("z", "y", "x", -1, -1, depth, height, width, depthSegments, heightSegments, 0); + buildPlane("z", "y", "x", 1, -1, depth, height, -width, depthSegments, heightSegments, 1); + buildPlane("x", "z", "y", 1, 1, width, depth, height, widthSegments, depthSegments, 2); + buildPlane("x", "z", "y", 1, -1, width, depth, -height, widthSegments, depthSegments, 3); + buildPlane("x", "y", "z", 1, -1, width, height, depth, widthSegments, heightSegments, 4); + buildPlane("x", "y", "z", -1, -1, width, height, -depth, widthSegments, heightSegments, 5); + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function buildPlane(u, v, w, udir, vdir, width2, height2, depth2, gridX, gridY, materialIndex) { + const segmentWidth = width2 / gridX; + const segmentHeight = height2 / gridY; + const widthHalf = width2 / 2; + const heightHalf = height2 / 2; + const depthHalf = depth2 / 2; + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + let vertexCounter = 0; + let groupCount = 0; + const vector = new Vector3(); + for (let iy = 0; iy < gridY1; iy++) { + const y = iy * segmentHeight - heightHalf; + for (let ix = 0; ix < gridX1; ix++) { + const x = ix * segmentWidth - widthHalf; + vector[u] = x * udir; + vector[v] = y * vdir; + vector[w] = depthHalf; + vertices.push(vector.x, vector.y, vector.z); + vector[u] = 0; + vector[v] = 0; + vector[w] = depth2 > 0 ? 1 : -1; + normals.push(vector.x, vector.y, vector.z); + uvs.push(ix / gridX); + uvs.push(1 - iy / gridY); + vertexCounter += 1; + } + } + for (let iy = 0; iy < gridY; iy++) { + for (let ix = 0; ix < gridX; ix++) { + const a = numberOfVertices + ix + gridX1 * iy; + const b = numberOfVertices + ix + gridX1 * (iy + 1); + const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1); + const d = numberOfVertices + (ix + 1) + gridX1 * iy; + indices.push(a, b, d); + indices.push(b, c, d); + groupCount += 6; + } + } + scope.addGroup(groupStart, groupCount, materialIndex); + groupStart += groupCount; + numberOfVertices += vertexCounter; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data) { + return new _BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments); + } + }; + function cloneUniforms(src) { + const dst = {}; + for (const u in src) { + dst[u] = {}; + for (const p in src[u]) { + const property = src[u][p]; + if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) { + if (property.isRenderTargetTexture) { + console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."); + dst[u][p] = null; + } else { + dst[u][p] = property.clone(); + } + } else if (Array.isArray(property)) { + dst[u][p] = property.slice(); + } else { + dst[u][p] = property; + } + } + } + return dst; + } + function mergeUniforms(uniforms) { + const merged = {}; + for (let u = 0; u < uniforms.length; u++) { + const tmp2 = cloneUniforms(uniforms[u]); + for (const p in tmp2) { + merged[p] = tmp2[p]; + } + } + return merged; + } + function cloneUniformsGroups(src) { + const dst = []; + for (let u = 0; u < src.length; u++) { + dst.push(src[u].clone()); + } + return dst; + } + function getUnlitUniformColorSpace(renderer) { + if (renderer.getRenderTarget() === null) { + return renderer.outputColorSpace; + } + return ColorManagement.workingColorSpace; + } + var UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms }; + var default_vertex = "void main() {\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}"; + var default_fragment = "void main() {\n gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}"; + var ShaderMaterial = class extends Material { + constructor(parameters) { + super(); + this.isShaderMaterial = true; + this.type = "ShaderMaterial"; + this.defines = {}; + this.uniforms = {}; + this.uniformsGroups = []; + this.vertexShader = default_vertex; + this.fragmentShader = default_fragment; + this.linewidth = 1; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.fog = false; + this.lights = false; + this.clipping = false; + this.forceSinglePass = true; + this.extensions = { + derivatives: false, + // set to use derivatives + fragDepth: false, + // set to use fragment depth values + drawBuffers: false, + // set to use draw buffers + shaderTextureLOD: false, + // set to use shader texture LOD + clipCullDistance: false + // set to use vertex shader clipping + }; + this.defaultAttributeValues = { + "color": [1, 1, 1], + "uv": [0, 0], + "uv1": [0, 0] + }; + this.index0AttributeName = void 0; + this.uniformsNeedUpdate = false; + this.glslVersion = null; + if (parameters !== void 0) { + this.setValues(parameters); + } + } + copy(source) { + super.copy(source); + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; + this.uniforms = cloneUniforms(source.uniforms); + this.uniformsGroups = cloneUniformsGroups(source.uniformsGroups); + this.defines = Object.assign({}, source.defines); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.fog = source.fog; + this.lights = source.lights; + this.clipping = source.clipping; + this.extensions = Object.assign({}, source.extensions); + this.glslVersion = source.glslVersion; + return this; + } + toJSON(meta) { + const data = super.toJSON(meta); + data.glslVersion = this.glslVersion; + data.uniforms = {}; + for (const name in this.uniforms) { + const uniform = this.uniforms[name]; + const value = uniform.value; + if (value && value.isTexture) { + data.uniforms[name] = { + type: "t", + value: value.toJSON(meta).uuid + }; + } else if (value && value.isColor) { + data.uniforms[name] = { + type: "c", + value: value.getHex() + }; + } else if (value && value.isVector2) { + data.uniforms[name] = { + type: "v2", + value: value.toArray() + }; + } else if (value && value.isVector3) { + data.uniforms[name] = { + type: "v3", + value: value.toArray() + }; + } else if (value && value.isVector4) { + data.uniforms[name] = { + type: "v4", + value: value.toArray() + }; + } else if (value && value.isMatrix3) { + data.uniforms[name] = { + type: "m3", + value: value.toArray() + }; + } else if (value && value.isMatrix4) { + data.uniforms[name] = { + type: "m4", + value: value.toArray() + }; + } else { + data.uniforms[name] = { + value + }; + } + } + if (Object.keys(this.defines).length > 0) data.defines = this.defines; + data.vertexShader = this.vertexShader; + data.fragmentShader = this.fragmentShader; + data.lights = this.lights; + data.clipping = this.clipping; + const extensions = {}; + for (const key in this.extensions) { + if (this.extensions[key] === true) extensions[key] = true; + } + if (Object.keys(extensions).length > 0) data.extensions = extensions; + return data; + } + }; + var Camera = class extends Object3D { + constructor() { + super(); + this.isCamera = true; + this.type = "Camera"; + this.matrixWorldInverse = new Matrix4(); + this.projectionMatrix = new Matrix4(); + this.projectionMatrixInverse = new Matrix4(); + this.coordinateSystem = WebGLCoordinateSystem; + } + copy(source, recursive) { + super.copy(source, recursive); + this.matrixWorldInverse.copy(source.matrixWorldInverse); + this.projectionMatrix.copy(source.projectionMatrix); + this.projectionMatrixInverse.copy(source.projectionMatrixInverse); + this.coordinateSystem = source.coordinateSystem; + return this; + } + getWorldDirection(target) { + return super.getWorldDirection(target).negate(); + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + this.matrixWorldInverse.copy(this.matrixWorld).invert(); + } + updateWorldMatrix(updateParents, updateChildren) { + super.updateWorldMatrix(updateParents, updateChildren); + this.matrixWorldInverse.copy(this.matrixWorld).invert(); + } + clone() { + return new this.constructor().copy(this); + } + }; + var PerspectiveCamera = class extends Camera { + constructor(fov2 = 50, aspect2 = 1, near = 0.1, far = 2e3) { + super(); + this.isPerspectiveCamera = true; + this.type = "PerspectiveCamera"; + this.fov = fov2; + this.zoom = 1; + this.near = near; + this.far = far; + this.focus = 10; + this.aspect = aspect2; + this.view = null; + this.filmGauge = 35; + this.filmOffset = 0; + this.updateProjectionMatrix(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.fov = source.fov; + this.zoom = source.zoom; + this.near = source.near; + this.far = source.far; + this.focus = source.focus; + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign({}, source.view); + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; + return this; + } + /** + * Sets the FOV by focal length in respect to the current .filmGauge. + * + * The default film gauge is 35, so that the focal length can be specified for + * a 35mm (full frame) camera. + * + * Values for focal length and film gauge must have the same unit. + */ + setFocalLength(focalLength) { + const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; + this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope); + this.updateProjectionMatrix(); + } + /** + * Calculates the focal length from the current .fov and .filmGauge. + */ + getFocalLength() { + const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov); + return 0.5 * this.getFilmHeight() / vExtentSlope; + } + getEffectiveFOV() { + return RAD2DEG * 2 * Math.atan( + Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom + ); + } + getFilmWidth() { + return this.filmGauge * Math.min(this.aspect, 1); + } + getFilmHeight() { + return this.filmGauge / Math.max(this.aspect, 1); + } + /** + * Sets an offset in a larger frustum. This is useful for multi-window or + * multi-monitor/multi-machine setups. + * + * For example, if you have 3x2 monitors and each monitor is 1920x1080 and + * the monitors are in grid like this + * + * +---+---+---+ + * | A | B | C | + * +---+---+---+ + * | D | E | F | + * +---+---+---+ + * + * then for each monitor you would call it like this + * + * const w = 1920; + * const h = 1080; + * const fullWidth = w * 3; + * const fullHeight = h * 2; + * + * --A-- + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); + * --B-- + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); + * --C-- + * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); + * --D-- + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); + * --E-- + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); + * --F-- + * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); + * + * Note there is no reason monitors have to be the same size or in a grid. + */ + setViewOffset(fullWidth, fullHeight, x, y, width, height) { + this.aspect = fullWidth / fullHeight; + if (this.view === null) { + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + } + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width; + this.view.height = height; + this.updateProjectionMatrix(); + } + clearViewOffset() { + if (this.view !== null) { + this.view.enabled = false; + } + this.updateProjectionMatrix(); + } + updateProjectionMatrix() { + const near = this.near; + let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom; + let height = 2 * top; + let width = this.aspect * height; + let left = -0.5 * width; + const view = this.view; + if (this.view !== null && this.view.enabled) { + const fullWidth = view.fullWidth, fullHeight = view.fullHeight; + left += view.offsetX * width / fullWidth; + top -= view.offsetY * height / fullHeight; + width *= view.width / fullWidth; + height *= view.height / fullHeight; + } + const skew = this.filmOffset; + if (skew !== 0) left += near * skew / this.getFilmWidth(); + this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far, this.coordinateSystem); + this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + } + toJSON(meta) { + const data = super.toJSON(meta); + data.object.fov = this.fov; + data.object.zoom = this.zoom; + data.object.near = this.near; + data.object.far = this.far; + data.object.focus = this.focus; + data.object.aspect = this.aspect; + if (this.view !== null) data.object.view = Object.assign({}, this.view); + data.object.filmGauge = this.filmGauge; + data.object.filmOffset = this.filmOffset; + return data; + } + }; + var fov = -90; + var aspect = 1; + var CubeCamera = class extends Object3D { + constructor(near, far, renderTarget) { + super(); + this.type = "CubeCamera"; + this.renderTarget = renderTarget; + this.coordinateSystem = null; + this.activeMipmapLevel = 0; + const cameraPX = new PerspectiveCamera(fov, aspect, near, far); + cameraPX.layers = this.layers; + this.add(cameraPX); + const cameraNX = new PerspectiveCamera(fov, aspect, near, far); + cameraNX.layers = this.layers; + this.add(cameraNX); + const cameraPY = new PerspectiveCamera(fov, aspect, near, far); + cameraPY.layers = this.layers; + this.add(cameraPY); + const cameraNY = new PerspectiveCamera(fov, aspect, near, far); + cameraNY.layers = this.layers; + this.add(cameraNY); + const cameraPZ = new PerspectiveCamera(fov, aspect, near, far); + cameraPZ.layers = this.layers; + this.add(cameraPZ); + const cameraNZ = new PerspectiveCamera(fov, aspect, near, far); + cameraNZ.layers = this.layers; + this.add(cameraNZ); + } + updateCoordinateSystem() { + const coordinateSystem = this.coordinateSystem; + const cameras = this.children.concat(); + const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = cameras; + for (const camera of cameras) this.remove(camera); + if (coordinateSystem === WebGLCoordinateSystem) { + cameraPX.up.set(0, 1, 0); + cameraPX.lookAt(1, 0, 0); + cameraNX.up.set(0, 1, 0); + cameraNX.lookAt(-1, 0, 0); + cameraPY.up.set(0, 0, -1); + cameraPY.lookAt(0, 1, 0); + cameraNY.up.set(0, 0, 1); + cameraNY.lookAt(0, -1, 0); + cameraPZ.up.set(0, 1, 0); + cameraPZ.lookAt(0, 0, 1); + cameraNZ.up.set(0, 1, 0); + cameraNZ.lookAt(0, 0, -1); + } else if (coordinateSystem === WebGPUCoordinateSystem) { + cameraPX.up.set(0, -1, 0); + cameraPX.lookAt(-1, 0, 0); + cameraNX.up.set(0, -1, 0); + cameraNX.lookAt(1, 0, 0); + cameraPY.up.set(0, 0, 1); + cameraPY.lookAt(0, 1, 0); + cameraNY.up.set(0, 0, -1); + cameraNY.lookAt(0, -1, 0); + cameraPZ.up.set(0, -1, 0); + cameraPZ.lookAt(0, 0, 1); + cameraNZ.up.set(0, -1, 0); + cameraNZ.lookAt(0, 0, -1); + } else { + throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: " + coordinateSystem); + } + for (const camera of cameras) { + this.add(camera); + camera.updateMatrixWorld(); + } + } + update(renderer, scene) { + if (this.parent === null) this.updateMatrixWorld(); + const { renderTarget, activeMipmapLevel } = this; + if (this.coordinateSystem !== renderer.coordinateSystem) { + this.coordinateSystem = renderer.coordinateSystem; + this.updateCoordinateSystem(); + } + const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children; + const currentRenderTarget = renderer.getRenderTarget(); + const currentActiveCubeFace = renderer.getActiveCubeFace(); + const currentActiveMipmapLevel = renderer.getActiveMipmapLevel(); + const currentXrEnabled = renderer.xr.enabled; + renderer.xr.enabled = false; + const generateMipmaps = renderTarget.texture.generateMipmaps; + renderTarget.texture.generateMipmaps = false; + renderer.setRenderTarget(renderTarget, 0, activeMipmapLevel); + renderer.render(scene, cameraPX); + renderer.setRenderTarget(renderTarget, 1, activeMipmapLevel); + renderer.render(scene, cameraNX); + renderer.setRenderTarget(renderTarget, 2, activeMipmapLevel); + renderer.render(scene, cameraPY); + renderer.setRenderTarget(renderTarget, 3, activeMipmapLevel); + renderer.render(scene, cameraNY); + renderer.setRenderTarget(renderTarget, 4, activeMipmapLevel); + renderer.render(scene, cameraPZ); + renderTarget.texture.generateMipmaps = generateMipmaps; + renderer.setRenderTarget(renderTarget, 5, activeMipmapLevel); + renderer.render(scene, cameraNZ); + renderer.setRenderTarget(currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel); + renderer.xr.enabled = currentXrEnabled; + renderTarget.texture.needsPMREMUpdate = true; + } + }; + var CubeTexture = class extends Texture { + constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace) { + images = images !== void 0 ? images : []; + mapping = mapping !== void 0 ? mapping : CubeReflectionMapping; + super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isCubeTexture = true; + this.flipY = false; + } + get images() { + return this.image; + } + set images(value) { + this.image = value; + } + }; + var WebGLCubeRenderTarget = class extends WebGLRenderTarget { + constructor(size = 1, options = {}) { + super(size, size, options); + this.isWebGLCubeRenderTarget = true; + const image = { width: size, height: size, depth: 1 }; + const images = [image, image, image, image, image, image]; + if (options.encoding !== void 0) { + warnOnce("THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace."); + options.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace; + } + this.texture = new CubeTexture(images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace); + this.texture.isRenderTargetTexture = true; + this.texture.generateMipmaps = options.generateMipmaps !== void 0 ? options.generateMipmaps : false; + this.texture.minFilter = options.minFilter !== void 0 ? options.minFilter : LinearFilter; + } + fromEquirectangularTexture(renderer, texture) { + this.texture.type = texture.type; + this.texture.colorSpace = texture.colorSpace; + this.texture.generateMipmaps = texture.generateMipmaps; + this.texture.minFilter = texture.minFilter; + this.texture.magFilter = texture.magFilter; + const shader = { + uniforms: { + tEquirect: { value: null } + }, + vertexShader: ( + /* glsl */ + ` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + ` + ), + fragmentShader: ( + /* glsl */ + ` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + ` + ) + }; + const geometry = new BoxGeometry(5, 5, 5); + const material = new ShaderMaterial({ + name: "CubemapFromEquirect", + uniforms: cloneUniforms(shader.uniforms), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + side: BackSide, + blending: NoBlending + }); + material.uniforms.tEquirect.value = texture; + const mesh = new Mesh(geometry, material); + const currentMinFilter = texture.minFilter; + if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter; + const camera = new CubeCamera(1, 10, this); + camera.update(renderer, mesh); + texture.minFilter = currentMinFilter; + mesh.geometry.dispose(); + mesh.material.dispose(); + return this; + } + clear(renderer, color, depth, stencil) { + const currentRenderTarget = renderer.getRenderTarget(); + for (let i = 0; i < 6; i++) { + renderer.setRenderTarget(this, i); + renderer.clear(color, depth, stencil); + } + renderer.setRenderTarget(currentRenderTarget); + } + }; + var _vector1 = /* @__PURE__ */ new Vector3(); + var _vector2 = /* @__PURE__ */ new Vector3(); + var _normalMatrix = /* @__PURE__ */ new Matrix3(); + var Plane = class { + constructor(normal = new Vector3(1, 0, 0), constant = 0) { + this.isPlane = true; + this.normal = normal; + this.constant = constant; + } + set(normal, constant) { + this.normal.copy(normal); + this.constant = constant; + return this; + } + setComponents(x, y, z, w) { + this.normal.set(x, y, z); + this.constant = w; + return this; + } + setFromNormalAndCoplanarPoint(normal, point) { + this.normal.copy(normal); + this.constant = -point.dot(this.normal); + return this; + } + setFromCoplanarPoints(a, b, c) { + const normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize(); + this.setFromNormalAndCoplanarPoint(normal, a); + return this; + } + copy(plane) { + this.normal.copy(plane.normal); + this.constant = plane.constant; + return this; + } + normalize() { + const inverseNormalLength = 1 / this.normal.length(); + this.normal.multiplyScalar(inverseNormalLength); + this.constant *= inverseNormalLength; + return this; + } + negate() { + this.constant *= -1; + this.normal.negate(); + return this; + } + distanceToPoint(point) { + return this.normal.dot(point) + this.constant; + } + distanceToSphere(sphere) { + return this.distanceToPoint(sphere.center) - sphere.radius; + } + projectPoint(point, target) { + return target.copy(point).addScaledVector(this.normal, -this.distanceToPoint(point)); + } + intersectLine(line, target) { + const direction = line.delta(_vector1); + const denominator = this.normal.dot(direction); + if (denominator === 0) { + if (this.distanceToPoint(line.start) === 0) { + return target.copy(line.start); + } + return null; + } + const t = -(line.start.dot(this.normal) + this.constant) / denominator; + if (t < 0 || t > 1) { + return null; + } + return target.copy(line.start).addScaledVector(direction, t); + } + intersectsLine(line) { + const startSign = this.distanceToPoint(line.start); + const endSign = this.distanceToPoint(line.end); + return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0; + } + intersectsBox(box) { + return box.intersectsPlane(this); + } + intersectsSphere(sphere) { + return sphere.intersectsPlane(this); + } + coplanarPoint(target) { + return target.copy(this.normal).multiplyScalar(-this.constant); + } + applyMatrix4(matrix, optionalNormalMatrix) { + const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix); + const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix); + const normal = this.normal.applyMatrix3(normalMatrix).normalize(); + this.constant = -referencePoint.dot(normal); + return this; + } + translate(offset) { + this.constant -= offset.dot(this.normal); + return this; + } + equals(plane) { + return plane.normal.equals(this.normal) && plane.constant === this.constant; + } + clone() { + return new this.constructor().copy(this); + } + }; + var _sphere$5 = /* @__PURE__ */ new Sphere(); + var _vector$7 = /* @__PURE__ */ new Vector3(); + var Frustum = class { + constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) { + this.planes = [p0, p1, p2, p3, p4, p5]; + } + set(p0, p1, p2, p3, p4, p5) { + const planes = this.planes; + planes[0].copy(p0); + planes[1].copy(p1); + planes[2].copy(p2); + planes[3].copy(p3); + planes[4].copy(p4); + planes[5].copy(p5); + return this; + } + copy(frustum) { + const planes = this.planes; + for (let i = 0; i < 6; i++) { + planes[i].copy(frustum.planes[i]); + } + return this; + } + setFromProjectionMatrix(m, coordinateSystem = WebGLCoordinateSystem) { + const planes = this.planes; + const me = m.elements; + const me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3]; + const me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7]; + const me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11]; + const me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15]; + planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize(); + planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize(); + planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize(); + planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize(); + planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize(); + if (coordinateSystem === WebGLCoordinateSystem) { + planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize(); + } else if (coordinateSystem === WebGPUCoordinateSystem) { + planes[5].setComponents(me2, me6, me10, me14).normalize(); + } else { + throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: " + coordinateSystem); + } + return this; + } + intersectsObject(object) { + if (object.boundingSphere !== void 0) { + if (object.boundingSphere === null) object.computeBoundingSphere(); + _sphere$5.copy(object.boundingSphere).applyMatrix4(object.matrixWorld); + } else { + const geometry = object.geometry; + if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); + _sphere$5.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld); + } + return this.intersectsSphere(_sphere$5); + } + intersectsSprite(sprite) { + _sphere$5.center.set(0, 0, 0); + _sphere$5.radius = 0.7071067811865476; + _sphere$5.applyMatrix4(sprite.matrixWorld); + return this.intersectsSphere(_sphere$5); + } + intersectsSphere(sphere) { + const planes = this.planes; + const center = sphere.center; + const negRadius = -sphere.radius; + for (let i = 0; i < 6; i++) { + const distance = planes[i].distanceToPoint(center); + if (distance < negRadius) { + return false; + } + } + return true; + } + intersectsBox(box) { + const planes = this.planes; + for (let i = 0; i < 6; i++) { + const plane = planes[i]; + _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x; + _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y; + _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z; + if (plane.distanceToPoint(_vector$7) < 0) { + return false; + } + } + return true; + } + containsPoint(point) { + const planes = this.planes; + for (let i = 0; i < 6; i++) { + if (planes[i].distanceToPoint(point) < 0) { + return false; + } + } + return true; + } + clone() { + return new this.constructor().copy(this); + } + }; + function WebGLAnimation() { + let context = null; + let isAnimating = false; + let animationLoop = null; + let requestId = null; + function onAnimationFrame(time, frame) { + animationLoop(time, frame); + requestId = context.requestAnimationFrame(onAnimationFrame); + } + return { + start: function() { + if (isAnimating === true) return; + if (animationLoop === null) return; + requestId = context.requestAnimationFrame(onAnimationFrame); + isAnimating = true; + }, + stop: function() { + context.cancelAnimationFrame(requestId); + isAnimating = false; + }, + setAnimationLoop: function(callback) { + animationLoop = callback; + }, + setContext: function(value) { + context = value; + } + }; + } + function WebGLAttributes(gl, capabilities) { + const isWebGL2 = capabilities.isWebGL2; + const buffers = /* @__PURE__ */ new WeakMap(); + function createBuffer(attribute, bufferType) { + const array = attribute.array; + const usage = attribute.usage; + const size = array.byteLength; + const buffer = gl.createBuffer(); + gl.bindBuffer(bufferType, buffer); + gl.bufferData(bufferType, array, usage); + attribute.onUploadCallback(); + let type; + if (array instanceof Float32Array) { + type = gl.FLOAT; + } else if (array instanceof Uint16Array) { + if (attribute.isFloat16BufferAttribute) { + if (isWebGL2) { + type = gl.HALF_FLOAT; + } else { + throw new Error("THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2."); + } + } else { + type = gl.UNSIGNED_SHORT; + } + } else if (array instanceof Int16Array) { + type = gl.SHORT; + } else if (array instanceof Uint32Array) { + type = gl.UNSIGNED_INT; + } else if (array instanceof Int32Array) { + type = gl.INT; + } else if (array instanceof Int8Array) { + type = gl.BYTE; + } else if (array instanceof Uint8Array) { + type = gl.UNSIGNED_BYTE; + } else if (array instanceof Uint8ClampedArray) { + type = gl.UNSIGNED_BYTE; + } else { + throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: " + array); + } + return { + buffer, + type, + bytesPerElement: array.BYTES_PER_ELEMENT, + version: attribute.version, + size + }; + } + function updateBuffer(buffer, attribute, bufferType) { + const array = attribute.array; + const updateRange = attribute._updateRange; + const updateRanges = attribute.updateRanges; + gl.bindBuffer(bufferType, buffer); + if (updateRange.count === -1 && updateRanges.length === 0) { + gl.bufferSubData(bufferType, 0, array); + } + if (updateRanges.length !== 0) { + for (let i = 0, l = updateRanges.length; i < l; i++) { + const range = updateRanges[i]; + if (isWebGL2) { + gl.bufferSubData( + bufferType, + range.start * array.BYTES_PER_ELEMENT, + array, + range.start, + range.count + ); + } else { + gl.bufferSubData( + bufferType, + range.start * array.BYTES_PER_ELEMENT, + array.subarray(range.start, range.start + range.count) + ); + } + } + attribute.clearUpdateRanges(); + } + if (updateRange.count !== -1) { + if (isWebGL2) { + gl.bufferSubData( + bufferType, + updateRange.offset * array.BYTES_PER_ELEMENT, + array, + updateRange.offset, + updateRange.count + ); + } else { + gl.bufferSubData( + bufferType, + updateRange.offset * array.BYTES_PER_ELEMENT, + array.subarray(updateRange.offset, updateRange.offset + updateRange.count) + ); + } + updateRange.count = -1; + } + attribute.onUploadCallback(); + } + function get(attribute) { + if (attribute.isInterleavedBufferAttribute) attribute = attribute.data; + return buffers.get(attribute); + } + function remove(attribute) { + if (attribute.isInterleavedBufferAttribute) attribute = attribute.data; + const data = buffers.get(attribute); + if (data) { + gl.deleteBuffer(data.buffer); + buffers.delete(attribute); + } + } + function update(attribute, bufferType) { + if (attribute.isGLBufferAttribute) { + const cached = buffers.get(attribute); + if (!cached || cached.version < attribute.version) { + buffers.set(attribute, { + buffer: attribute.buffer, + type: attribute.type, + bytesPerElement: attribute.elementSize, + version: attribute.version + }); + } + return; + } + if (attribute.isInterleavedBufferAttribute) attribute = attribute.data; + const data = buffers.get(attribute); + if (data === void 0) { + buffers.set(attribute, createBuffer(attribute, bufferType)); + } else if (data.version < attribute.version) { + if (data.size !== attribute.array.byteLength) { + throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported."); + } + updateBuffer(data.buffer, attribute, bufferType); + data.version = attribute.version; + } + } + return { + get, + remove, + update + }; + } + var PlaneGeometry = class _PlaneGeometry extends BufferGeometry { + constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) { + super(); + this.type = "PlaneGeometry"; + this.parameters = { + width, + height, + widthSegments, + heightSegments + }; + const width_half = width / 2; + const height_half = height / 2; + const gridX = Math.floor(widthSegments); + const gridY = Math.floor(heightSegments); + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + const segment_width = width / gridX; + const segment_height = height / gridY; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + for (let iy = 0; iy < gridY1; iy++) { + const y = iy * segment_height - height_half; + for (let ix = 0; ix < gridX1; ix++) { + const x = ix * segment_width - width_half; + vertices.push(x, -y, 0); + normals.push(0, 0, 1); + uvs.push(ix / gridX); + uvs.push(1 - iy / gridY); + } + } + for (let iy = 0; iy < gridY; iy++) { + for (let ix = 0; ix < gridX; ix++) { + const a = ix + gridX1 * iy; + const b = ix + gridX1 * (iy + 1); + const c = ix + 1 + gridX1 * (iy + 1); + const d = ix + 1 + gridX1 * iy; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data) { + return new _PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments); + } + }; + var alphahash_fragment = "#ifdef USE_ALPHAHASH\n if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif"; + var alphahash_pars_fragment = "#ifdef USE_ALPHAHASH\n const float ALPHA_HASH_SCALE = 0.05;\n float hash2D( vec2 value ) {\n return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n }\n float hash3D( vec3 value ) {\n return hash2D( vec2( hash2D( value.xy ), value.z ) );\n }\n float getAlphaHashThreshold( vec3 position ) {\n float maxDeriv = max(\n length( dFdx( position.xyz ) ),\n length( dFdy( position.xyz ) )\n );\n float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n vec2 pixScales = vec2(\n exp2( floor( log2( pixScale ) ) ),\n exp2( ceil( log2( pixScale ) ) )\n );\n vec2 alpha = vec2(\n hash3D( floor( pixScales.x * position.xyz ) ),\n hash3D( floor( pixScales.y * position.xyz ) )\n );\n float lerpFactor = fract( log2( pixScale ) );\n float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n float a = min( lerpFactor, 1.0 - lerpFactor );\n vec3 cases = vec3(\n x * x / ( 2.0 * a * ( 1.0 - a ) ),\n ( x - 0.5 * a ) / ( 1.0 - a ),\n 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n );\n float threshold = ( x < ( 1.0 - a ) )\n ? ( ( x < a ) ? cases.x : cases.y )\n : cases.z;\n return clamp( threshold , 1.0e-6, 1.0 );\n }\n#endif"; + var alphamap_fragment = "#ifdef USE_ALPHAMAP\n diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif"; + var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n uniform sampler2D alphaMap;\n#endif"; + var alphatest_fragment = "#ifdef USE_ALPHATEST\n if ( diffuseColor.a < alphaTest ) discard;\n#endif"; + var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n uniform float alphaTest;\n#endif"; + var aomap_fragment = "#ifdef USE_AOMAP\n float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n reflectedLight.indirectDiffuse *= ambientOcclusion;\n #if defined( USE_CLEARCOAT ) \n clearcoatSpecularIndirect *= ambientOcclusion;\n #endif\n #if defined( USE_SHEEN ) \n sheenSpecularIndirect *= ambientOcclusion;\n #endif\n #if defined( USE_ENVMAP ) && defined( STANDARD )\n float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n #endif\n#endif"; + var aomap_pars_fragment = "#ifdef USE_AOMAP\n uniform sampler2D aoMap;\n uniform float aoMapIntensity;\n#endif"; + var batching_pars_vertex = "#ifdef USE_BATCHING\n attribute float batchId;\n uniform highp sampler2D batchingTexture;\n mat4 getBatchingMatrix( const in float i ) {\n int size = textureSize( batchingTexture, 0 ).x;\n int j = int( i ) * 4;\n int x = j % size;\n int y = j / size;\n vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );\n vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n return mat4( v1, v2, v3, v4 );\n }\n#endif"; + var batching_vertex = "#ifdef USE_BATCHING\n mat4 batchingMatrix = getBatchingMatrix( batchId );\n#endif"; + var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n vPosition = vec3( position );\n#endif"; + var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n vec3 objectTangent = vec3( tangent.xyz );\n#endif"; + var bsdfs = "float G_BlinnPhong_Implicit( ) {\n return 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n vec3 halfDir = normalize( lightDir + viewDir );\n float dotNH = saturate( dot( normal, halfDir ) );\n float dotVH = saturate( dot( viewDir, halfDir ) );\n vec3 F = F_Schlick( specularColor, 1.0, dotVH );\n float G = G_BlinnPhong_Implicit( );\n float D = D_BlinnPhong( shininess, dotNH );\n return F * ( G * D );\n} // validated"; + var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n const mat3 XYZ_TO_REC709 = mat3(\n 3.2404542, -0.9692660, 0.0556434,\n -1.5371385, 1.8760108, -0.2040259,\n -0.4985314, 0.0415560, 1.0572252\n );\n vec3 Fresnel0ToIor( vec3 fresnel0 ) {\n vec3 sqrtF0 = sqrt( fresnel0 );\n return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n }\n vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n }\n float IorToFresnel0( float transmittedIor, float incidentIor ) {\n return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n }\n vec3 evalSensitivity( float OPD, vec3 shift ) {\n float phase = 2.0 * PI * OPD * 1.0e-9;\n vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n xyz /= 1.0685e-7;\n vec3 rgb = XYZ_TO_REC709 * xyz;\n return rgb;\n }\n vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n vec3 I;\n float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n float cosTheta2Sq = 1.0 - sinTheta2Sq;\n if ( cosTheta2Sq < 0.0 ) {\n return vec3( 1.0 );\n }\n float cosTheta2 = sqrt( cosTheta2Sq );\n float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n float R12 = F_Schlick( R0, 1.0, cosTheta1 );\n float T121 = 1.0 - R12;\n float phi12 = 0.0;\n if ( iridescenceIOR < outsideIOR ) phi12 = PI;\n float phi21 = PI - phi12;\n vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n vec3 phi23 = vec3( 0.0 );\n if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n vec3 phi = vec3( phi21 ) + phi23;\n vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n vec3 r123 = sqrt( R123 );\n vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n vec3 C0 = R12 + Rs;\n I = C0;\n vec3 Cm = Rs - T121;\n for ( int m = 1; m <= 2; ++ m ) {\n Cm *= r123;\n vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n I += Cm * Sm;\n }\n return max( I, vec3( 0.0 ) );\n }\n#endif"; + var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n uniform sampler2D bumpMap;\n uniform float bumpScale;\n vec2 dHdxy_fwd() {\n vec2 dSTdx = dFdx( vBumpMapUv );\n vec2 dSTdy = dFdy( vBumpMapUv );\n float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n return vec2( dBx, dBy );\n }\n vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );\n vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\n vec3 vN = surf_norm;\n vec3 R1 = cross( vSigmaY, vN );\n vec3 R2 = cross( vN, vSigmaX );\n float fDet = dot( vSigmaX, R1 ) * faceDirection;\n vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n return normalize( abs( fDet ) * surf_norm - vGrad );\n }\n#endif"; + var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n vec4 plane;\n #pragma unroll_loop_start\n for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n plane = clippingPlanes[ i ];\n if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n }\n #pragma unroll_loop_end\n #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n bool clipped = true;\n #pragma unroll_loop_start\n for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n plane = clippingPlanes[ i ];\n clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n }\n #pragma unroll_loop_end\n if ( clipped ) discard;\n #endif\n#endif"; + var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif"; + var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n#endif"; + var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n vClipPosition = - mvPosition.xyz;\n#endif"; + var color_fragment = "#if defined( USE_COLOR_ALPHA )\n diffuseColor *= vColor;\n#elif defined( USE_COLOR )\n diffuseColor.rgb *= vColor;\n#endif"; + var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n varying vec4 vColor;\n#elif defined( USE_COLOR )\n varying vec3 vColor;\n#endif"; + var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n varying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n varying vec3 vColor;\n#endif"; + var color_vertex = "#if defined( USE_COLOR_ALPHA )\n vColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n vColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n vColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n vColor.xyz *= instanceColor.xyz;\n#endif"; + var 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 const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n float precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n float precisionSafeLength( vec3 v ) {\n float maxComponent = max3( abs( v ) );\n return length( v / maxComponent ) * maxComponent;\n }\n#endif\nstruct IncidentLight {\n vec3 color;\n vec3 direction;\n bool visible;\n};\nstruct ReflectedLight {\n vec3 directDiffuse;\n vec3 directSpecular;\n vec3 indirectDiffuse;\n vec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n varying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n mat3 tmp;\n tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n return tmp;\n}\nfloat luminance( const in vec3 rgb ) {\n const vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n return dot( weights, rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n return m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n return vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n return RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated"; + var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n #define cubeUV_minMipLevel 4.0\n #define cubeUV_minTileSize 16.0\n float getFace( vec3 direction ) {\n vec3 absDirection = abs( direction );\n float face = - 1.0;\n if ( absDirection.x > absDirection.z ) {\n if ( absDirection.x > absDirection.y )\n face = direction.x > 0.0 ? 0.0 : 3.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n } else {\n if ( absDirection.z > absDirection.y )\n face = direction.z > 0.0 ? 2.0 : 5.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n }\n return face;\n }\n vec2 getUV( vec3 direction, float face ) {\n vec2 uv;\n if ( face == 0.0 ) {\n uv = vec2( direction.z, direction.y ) / abs( direction.x );\n } else if ( face == 1.0 ) {\n uv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n } else if ( face == 2.0 ) {\n uv = vec2( - direction.x, direction.y ) / abs( direction.z );\n } else if ( face == 3.0 ) {\n uv = vec2( - direction.z, direction.y ) / abs( direction.x );\n } else if ( face == 4.0 ) {\n uv = vec2( - direction.x, direction.z ) / abs( direction.y );\n } else {\n uv = vec2( direction.x, direction.y ) / abs( direction.z );\n }\n return 0.5 * ( uv + 1.0 );\n }\n vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n float face = getFace( direction );\n float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n mipInt = max( mipInt, cubeUV_minMipLevel );\n float faceSize = exp2( mipInt );\n highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n if ( face > 2.0 ) {\n uv.y += faceSize;\n face -= 3.0;\n }\n uv.x += face * faceSize;\n uv.x += filterInt * 3.0 * cubeUV_minTileSize;\n uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n uv.x *= CUBEUV_TEXEL_WIDTH;\n uv.y *= CUBEUV_TEXEL_HEIGHT;\n #ifdef texture2DGradEXT\n return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n #else\n return texture2D( envMap, uv ).rgb;\n #endif\n }\n #define cubeUV_r0 1.0\n #define cubeUV_m0 - 2.0\n #define cubeUV_r1 0.8\n #define cubeUV_m1 - 1.0\n #define cubeUV_r4 0.4\n #define cubeUV_m4 2.0\n #define cubeUV_r5 0.305\n #define cubeUV_m5 3.0\n #define cubeUV_r6 0.21\n #define cubeUV_m6 4.0\n float roughnessToMip( float roughness ) {\n float mip = 0.0;\n if ( roughness >= cubeUV_r1 ) {\n mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n } else if ( roughness >= cubeUV_r4 ) {\n mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n } else if ( roughness >= cubeUV_r5 ) {\n mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n } else if ( roughness >= cubeUV_r6 ) {\n mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n } else {\n mip = - 2.0 * log2( 1.16 * roughness ); }\n return mip;\n }\n vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n float mipF = fract( mip );\n float mipInt = floor( mip );\n vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n if ( mipF == 0.0 ) {\n return vec4( color0, 1.0 );\n } else {\n vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n return vec4( mix( color0, color1, mipF ), 1.0 );\n }\n }\n#endif"; + var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n vec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n mat3 bm = mat3( batchingMatrix );\n transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n transformedNormal = bm * transformedNormal;\n #ifdef USE_TANGENT\n transformedTangent = bm * transformedTangent;\n #endif\n#endif\n#ifdef USE_INSTANCING\n mat3 im = mat3( instanceMatrix );\n transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n transformedNormal = im * transformedNormal;\n #ifdef USE_TANGENT\n transformedTangent = im * transformedTangent;\n #endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n transformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n #ifdef FLIP_SIDED\n transformedTangent = - transformedTangent;\n #endif\n#endif"; + var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n uniform sampler2D displacementMap;\n uniform float displacementScale;\n uniform float displacementBias;\n#endif"; + var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif"; + var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n totalEmissiveRadiance *= emissiveColor.rgb;\n#endif"; + var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n uniform sampler2D emissiveMap;\n#endif"; + var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; + var colorspace_pars_fragment = "\nconst mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(\n vec3( 0.8224621, 0.177538, 0.0 ),\n vec3( 0.0331941, 0.9668058, 0.0 ),\n vec3( 0.0170827, 0.0723974, 0.9105199 )\n);\nconst mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(\n vec3( 1.2249401, - 0.2249404, 0.0 ),\n vec3( - 0.0420569, 1.0420571, 0.0 ),\n vec3( - 0.0196376, - 0.0786361, 1.0982735 )\n);\nvec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {\n return vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );\n}\nvec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {\n return vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );\n}\nvec4 LinearTransferOETF( in vec4 value ) {\n return value;\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 LinearToLinear( in vec4 value ) {\n return value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n return sRGBTransferOETF( value );\n}"; + var envmap_fragment = "#ifdef USE_ENVMAP\n #ifdef ENV_WORLDPOS\n vec3 cameraToFrag;\n if ( isOrthographic ) {\n cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n } else {\n cameraToFrag = normalize( vWorldPosition - cameraPosition );\n }\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vec3 reflectVec = reflect( cameraToFrag, worldNormal );\n #else\n vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n #endif\n #else\n vec3 reflectVec = vReflect;\n #endif\n #ifdef ENVMAP_TYPE_CUBE\n vec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n #else\n vec4 envColor = vec4( 0.0 );\n #endif\n #ifdef ENVMAP_BLENDING_MULTIPLY\n outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_MIX )\n outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_ADD )\n outgoingLight += envColor.xyz * specularStrength * reflectivity;\n #endif\n#endif"; + var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n uniform float envMapIntensity;\n uniform float flipEnvMap;\n #ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n #else\n uniform sampler2D envMap;\n #endif\n \n#endif"; + var envmap_pars_fragment = "#ifdef USE_ENVMAP\n uniform float reflectivity;\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n #define ENV_WORLDPOS\n #endif\n #ifdef ENV_WORLDPOS\n varying vec3 vWorldPosition;\n uniform float refractionRatio;\n #else\n varying vec3 vReflect;\n #endif\n#endif"; + var envmap_pars_vertex = "#ifdef USE_ENVMAP\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n #define ENV_WORLDPOS\n #endif\n #ifdef ENV_WORLDPOS\n \n varying vec3 vWorldPosition;\n #else\n varying vec3 vReflect;\n uniform float refractionRatio;\n #endif\n#endif"; + var envmap_vertex = "#ifdef USE_ENVMAP\n #ifdef ENV_WORLDPOS\n vWorldPosition = worldPosition.xyz;\n #else\n vec3 cameraToVertex;\n if ( isOrthographic ) {\n cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n } else {\n cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n }\n vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vReflect = reflect( cameraToVertex, worldNormal );\n #else\n vReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n #endif\n #endif\n#endif"; + var fog_vertex = "#ifdef USE_FOG\n vFogDepth = - mvPosition.z;\n#endif"; + var fog_pars_vertex = "#ifdef USE_FOG\n varying float vFogDepth;\n#endif"; + var fog_fragment = "#ifdef USE_FOG\n #ifdef FOG_EXP2\n float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n #else\n float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n #endif\n gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif"; + var fog_pars_fragment = "#ifdef USE_FOG\n uniform vec3 fogColor;\n varying float vFogDepth;\n #ifdef FOG_EXP2\n uniform float fogDensity;\n #else\n uniform float fogNear;\n uniform float fogFar;\n #endif\n#endif"; + var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n uniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n float dotNL = dot( normal, lightDirection );\n vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n #ifdef USE_GRADIENTMAP\n return vec3( texture2D( gradientMap, coord ).r );\n #else\n vec2 fw = fwidth( coord ) * 0.5;\n return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n #endif\n}"; + var lightmap_fragment = "#ifdef USE_LIGHTMAP\n vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n reflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif"; + var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n uniform sampler2D lightMap;\n uniform float lightMapIntensity;\n#endif"; + var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;"; + var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n vec3 diffuseColor;\n float 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 float dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n vec3 irradiance = dotNL * directLight.color;\n reflectedLight.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 reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct RE_Direct_Lambert\n#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert"; + var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n uniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n float x = normal.x, y = normal.y, z = normal.z;\n vec3 result = shCoefficients[ 0 ] * 0.886227;\n result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n return result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n return irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n vec3 irradiance = ambientLightColor;\n return irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n #if defined ( LEGACY_LIGHTS )\n if ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n return pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n }\n return 1.0;\n #else\n float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n if ( cutoffDistance > 0.0 ) {\n distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n }\n return distanceFalloff;\n #endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n return smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n struct DirectionalLight {\n vec3 direction;\n vec3 color;\n };\n uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n light.color = directionalLight.color;\n light.direction = directionalLight.direction;\n light.visible = true;\n }\n#endif\n#if NUM_POINT_LIGHTS > 0\n struct PointLight {\n vec3 position;\n vec3 color;\n float distance;\n float decay;\n };\n uniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n vec3 lVector = pointLight.position - geometryPosition;\n light.direction = normalize( lVector );\n float lightDistance = length( lVector );\n light.color = pointLight.color;\n light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n light.visible = ( light.color != vec3( 0.0 ) );\n }\n#endif\n#if NUM_SPOT_LIGHTS > 0\n struct SpotLight {\n vec3 position;\n vec3 direction;\n vec3 color;\n float distance;\n float decay;\n float coneCos;\n float penumbraCos;\n };\n uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n vec3 lVector = spotLight.position - geometryPosition;\n light.direction = normalize( lVector );\n float angleCos = dot( light.direction, spotLight.direction );\n float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n if ( spotAttenuation > 0.0 ) {\n float lightDistance = length( lVector );\n light.color = spotLight.color * spotAttenuation;\n light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n light.visible = ( light.color != vec3( 0.0 ) );\n } else {\n light.color = vec3( 0.0 );\n light.visible = false;\n }\n }\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n struct RectAreaLight {\n vec3 color;\n vec3 position;\n vec3 halfWidth;\n vec3 halfHeight;\n };\n uniform sampler2D ltc_1; uniform sampler2D ltc_2;\n uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n struct HemisphereLight {\n vec3 direction;\n vec3 skyColor;\n vec3 groundColor;\n };\n uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n float dotNL = dot( normal, hemiLight.direction );\n float hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n return irradiance;\n }\n#endif"; + var envmap_physical_pars_fragment = "#ifdef USE_ENVMAP\n vec3 getIBLIrradiance( const in vec3 normal ) {\n #ifdef ENVMAP_TYPE_CUBE_UV\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n vec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n return PI * envMapColor.rgb * envMapIntensity;\n #else\n return vec3( 0.0 );\n #endif\n }\n vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n #ifdef ENVMAP_TYPE_CUBE_UV\n vec3 reflectVec = reflect( - viewDir, normal );\n reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n reflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n vec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n return envMapColor.rgb * envMapIntensity;\n #else\n return vec3( 0.0 );\n #endif\n }\n #ifdef USE_ANISOTROPY\n vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n #ifdef ENVMAP_TYPE_CUBE_UV\n vec3 bentNormal = cross( bitangent, viewDir );\n bentNormal = normalize( cross( bentNormal, bitangent ) );\n bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n return getIBLRadiance( viewDir, bentNormal, roughness );\n #else\n return vec3( 0.0 );\n #endif\n }\n #endif\n#endif"; + var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;"; + var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n vec3 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 vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n reflectedLight.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 reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct RE_Direct_Toon\n#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon"; + var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;"; + var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n vec3 diffuseColor;\n vec3 specularColor;\n float specularShininess;\n float 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 float dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n vec3 irradiance = dotNL * directLight.color;\n reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n reflectedLight.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 reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct RE_Direct_BlinnPhong\n#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong"; + var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - 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 material.ior = ior;\n #ifdef USE_SPECULAR\n float specularIntensityFactor = specularIntensity;\n vec3 specularColorFactor = specularColor;\n #ifdef USE_SPECULAR_COLORMAP\n specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n #endif\n #ifdef USE_SPECULAR_INTENSITYMAP\n specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n #endif\n material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n #else\n float specularIntensityFactor = 1.0;\n vec3 specularColorFactor = vec3( 1.0 );\n material.specularF90 = 1.0;\n #endif\n material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n material.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n material.clearcoat = clearcoat;\n material.clearcoatRoughness = clearcoatRoughness;\n material.clearcoatF0 = vec3( 0.04 );\n material.clearcoatF90 = 1.0;\n #ifdef USE_CLEARCOATMAP\n material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n #endif\n #ifdef USE_CLEARCOAT_ROUGHNESSMAP\n material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n #endif\n material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n material.clearcoatRoughness += geometryRoughness;\n material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_IRIDESCENCE\n material.iridescence = iridescence;\n material.iridescenceIOR = iridescenceIOR;\n #ifdef USE_IRIDESCENCEMAP\n material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n #endif\n #ifdef USE_IRIDESCENCE_THICKNESSMAP\n material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n #else\n material.iridescenceThickness = iridescenceThicknessMaximum;\n #endif\n#endif\n#ifdef USE_SHEEN\n material.sheenColor = sheenColor;\n #ifdef USE_SHEEN_COLORMAP\n material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n #endif\n material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n #ifdef USE_SHEEN_ROUGHNESSMAP\n material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n #endif\n#endif\n#ifdef USE_ANISOTROPY\n #ifdef USE_ANISOTROPYMAP\n mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n #else\n vec2 anisotropyV = anisotropyVector;\n #endif\n material.anisotropy = length( anisotropyV );\n if( material.anisotropy == 0.0 ) {\n anisotropyV = vec2( 1.0, 0.0 );\n } else {\n anisotropyV /= material.anisotropy;\n material.anisotropy = saturate( material.anisotropy );\n }\n material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif"; + var lights_physical_pars_fragment = "struct PhysicalMaterial {\n vec3 diffuseColor;\n float roughness;\n vec3 specularColor;\n float specularF90;\n #ifdef USE_CLEARCOAT\n float clearcoat;\n float clearcoatRoughness;\n vec3 clearcoatF0;\n float clearcoatF90;\n #endif\n #ifdef USE_IRIDESCENCE\n float iridescence;\n float iridescenceIOR;\n float iridescenceThickness;\n vec3 iridescenceFresnel;\n vec3 iridescenceF0;\n #endif\n #ifdef USE_SHEEN\n vec3 sheenColor;\n float sheenRoughness;\n #endif\n #ifdef IOR\n float ior;\n #endif\n #ifdef USE_TRANSMISSION\n float transmission;\n float transmissionAlpha;\n float thickness;\n float attenuationDistance;\n vec3 attenuationColor;\n #endif\n #ifdef USE_ANISOTROPY\n float anisotropy;\n float alphaT;\n vec3 anisotropyT;\n vec3 anisotropyB;\n #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 float a2 = pow2( alpha );\n float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n return 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n float a2 = pow2( alpha );\n float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n return RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n float v = 0.5 / ( gv + gl );\n return saturate(v);\n }\n float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n float a2 = alphaT * alphaB;\n highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n highp float v2 = dot( v, v );\n float w2 = a2 / v2;\n return RECIPROCAL_PI * a2 * pow2 ( w2 );\n }\n#endif\n#ifdef USE_CLEARCOAT\n vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n vec3 f0 = material.clearcoatF0;\n float f90 = material.clearcoatF90;\n float roughness = material.clearcoatRoughness;\n float alpha = pow2( roughness );\n vec3 halfDir = normalize( lightDir + viewDir );\n float dotNL = saturate( dot( normal, lightDir ) );\n float dotNV = saturate( dot( normal, viewDir ) );\n float dotNH = saturate( dot( normal, halfDir ) );\n float dotVH = saturate( dot( viewDir, halfDir ) );\n vec3 F = F_Schlick( f0, f90, dotVH );\n float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n float D = D_GGX( alpha, dotNH );\n return F * ( V * D );\n }\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n vec3 f0 = material.specularColor;\n float f90 = material.specularF90;\n float roughness = material.roughness;\n float alpha = pow2( roughness );\n vec3 halfDir = normalize( lightDir + viewDir );\n float dotNL = saturate( dot( normal, lightDir ) );\n float dotNV = saturate( dot( normal, viewDir ) );\n float dotNH = saturate( dot( normal, halfDir ) );\n float dotVH = saturate( dot( viewDir, halfDir ) );\n vec3 F = F_Schlick( f0, f90, dotVH );\n #ifdef USE_IRIDESCENCE\n F = mix( F, material.iridescenceFresnel, material.iridescence );\n #endif\n #ifdef USE_ANISOTROPY\n float dotTL = dot( material.anisotropyT, lightDir );\n float dotTV = dot( material.anisotropyT, viewDir );\n float dotTH = dot( material.anisotropyT, halfDir );\n float dotBL = dot( material.anisotropyB, lightDir );\n float dotBV = dot( material.anisotropyB, viewDir );\n float dotBH = dot( material.anisotropyB, halfDir );\n float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n #else\n float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n float D = D_GGX( alpha, dotNH );\n #endif\n return F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n const float LUT_SIZE = 64.0;\n const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n const float LUT_BIAS = 0.5 / LUT_SIZE;\n float dotNV = saturate( dot( N, V ) );\n vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n uv = uv * LUT_SCALE + LUT_BIAS;\n return uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n float l = length( f );\n return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n float x = dot( v1, v2 );\n float y = abs( x );\n float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n float b = 3.4175940 + ( 4.1616724 + y ) * y;\n float v = a / b;\n float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n return 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 vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n vec3 lightNormal = cross( v1, v2 );\n if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n vec3 T1, T2;\n T1 = normalize( V - N * dot( V, N ) );\n T2 = - cross( N, T1 );\n mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n vec3 coords[ 4 ];\n coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n coords[ 0 ] = normalize( coords[ 0 ] );\n coords[ 1 ] = normalize( coords[ 1 ] );\n coords[ 2 ] = normalize( coords[ 2 ] );\n coords[ 3 ] = normalize( coords[ 3 ] );\n vec3 vectorFormFactor = vec3( 0.0 );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n float result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n return vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n float alpha = pow2( roughness );\n float invAlpha = 1.0 / alpha;\n float cos2h = dotNH * dotNH;\n float sin2h = max( 1.0 - cos2h, 0.0078125 );\n return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n return 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 vec3 halfDir = normalize( lightDir + viewDir );\n float dotNL = saturate( dot( normal, lightDir ) );\n float dotNV = saturate( dot( normal, viewDir ) );\n float dotNH = saturate( dot( normal, halfDir ) );\n float D = D_Charlie( sheenRoughness, dotNH );\n float V = V_Neubelt( dotNV, dotNL );\n return sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n float dotNV = saturate( dot( normal, viewDir ) );\n float r2 = roughness * roughness;\n float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n return saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n float dotNV = saturate( dot( normal, viewDir ) );\n const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n return fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n vec2 fab = DFGApprox( normal, viewDir, roughness );\n return 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 vec2 fab = DFGApprox( normal, viewDir, roughness );\n #ifdef USE_IRIDESCENCE\n vec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n #else\n vec3 Fr = specularColor;\n #endif\n vec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n float Ess = fab.x + fab.y;\n float Ems = 1.0 - Ess;\n vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n singleScatter += FssEss;\n multiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n vec3 normal = geometryNormal;\n vec3 viewDir = geometryViewDir;\n vec3 position = geometryPosition;\n vec3 lightPos = rectAreaLight.position;\n vec3 halfWidth = rectAreaLight.halfWidth;\n vec3 halfHeight = rectAreaLight.halfHeight;\n vec3 lightColor = rectAreaLight.color;\n float roughness = material.roughness;\n vec3 rectCoords[ 4 ];\n rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n vec2 uv = LTC_Uv( normal, viewDir, roughness );\n vec4 t1 = texture2D( ltc_1, uv );\n vec4 t2 = texture2D( ltc_2, uv );\n mat3 mInv = mat3(\n vec3( t1.x, 0, t1.y ),\n vec3( 0, 1, 0 ),\n vec3( t1.z, 0, t1.w )\n );\n vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n }\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 float dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n vec3 irradiance = dotNL * directLight.color;\n #ifdef USE_CLEARCOAT\n float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n vec3 ccIrradiance = dotNLcc * directLight.color;\n clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n #endif\n #ifdef USE_SHEEN\n sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n #endif\n reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\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 reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\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 #ifdef USE_CLEARCOAT\n clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n #endif\n #ifdef USE_SHEEN\n sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n #endif\n vec3 singleScattering = vec3( 0.0 );\n vec3 multiScattering = vec3( 0.0 );\n vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n #ifdef USE_IRIDESCENCE\n computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n #else\n computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n #endif\n vec3 totalScattering = singleScattering + multiScattering;\n vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n reflectedLight.indirectSpecular += radiance * singleScattering;\n reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct RE_Direct_Physical\n#define RE_Direct_RectArea RE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular RE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; + var 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 geometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n float dotNVi = saturate( dot( normal, geometryViewDir ) );\n if ( material.iridescenceThickness == 0.0 ) {\n material.iridescence = 0.0;\n } else {\n material.iridescence = saturate( material.iridescence );\n }\n if ( material.iridescence > 0.0 ) {\n material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n }\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n PointLight pointLight;\n #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n PointLightShadow pointLightShadow;\n #endif\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n pointLight = pointLights[ i ];\n getPointLightInfo( pointLight, geometryPosition, directLight );\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n pointLightShadow = pointLightShadows[ i ];\n directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n #endif\n RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n }\n #pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n SpotLight spotLight;\n vec4 spotColor;\n vec3 spotLightCoord;\n bool inSpotLightMap;\n #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n SpotLightShadow spotLightShadow;\n #endif\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n spotLight = spotLights[ i ];\n getSpotLightInfo( spotLight, geometryPosition, directLight );\n #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n #else\n #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n #endif\n #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n #endif\n #undef SPOT_LIGHT_MAP_INDEX\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n spotLightShadow = spotLightShadows[ i ];\n directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n #endif\n RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n }\n #pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n DirectionalLight directionalLight;\n #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n DirectionalLightShadow directionalLightShadow;\n #endif\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n directionalLight = directionalLights[ i ];\n getDirectionalLightInfo( directionalLight, directLight );\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n directionalLightShadow = directionalLightShadows[ i ];\n directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n #endif\n RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n }\n #pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n RectAreaLight rectAreaLight;\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n rectAreaLight = rectAreaLights[ i ];\n RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n }\n #pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n vec3 iblIrradiance = vec3( 0.0 );\n vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n #if defined( USE_LIGHT_PROBES )\n irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n #endif\n #if ( NUM_HEMI_LIGHTS > 0 )\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n }\n #pragma unroll_loop_end\n #endif\n#endif\n#if defined( RE_IndirectSpecular )\n vec3 radiance = vec3( 0.0 );\n vec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; + var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n #ifdef USE_LIGHTMAP\n vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n irradiance += lightMapIrradiance;\n #endif\n #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n iblIrradiance += getIBLIrradiance( geometryNormal );\n #endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n #ifdef USE_ANISOTROPY\n radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n #else\n radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n #endif\n #ifdef USE_CLEARCOAT\n clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n #endif\n#endif"; + var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif"; + var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n gl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif"; + var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n uniform float logDepthBufFC;\n varying float vFragDepth;\n varying float vIsPerspective;\n#endif"; + var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n #ifdef USE_LOGDEPTHBUF_EXT\n varying float vFragDepth;\n varying float vIsPerspective;\n #else\n uniform float logDepthBufFC;\n #endif\n#endif"; + var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n #ifdef USE_LOGDEPTHBUF_EXT\n vFragDepth = 1.0 + gl_Position.w;\n vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n #else\n if ( isPerspectiveMatrix( projectionMatrix ) ) {\n gl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n gl_Position.z *= gl_Position.w;\n }\n #endif\n#endif"; + var map_fragment = "#ifdef USE_MAP\n vec4 sampledDiffuseColor = texture2D( map, vMapUv );\n #ifdef DECODE_VIDEO_TEXTURE\n sampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n \n #endif\n diffuseColor *= sampledDiffuseColor;\n#endif"; + var map_pars_fragment = "#ifdef USE_MAP\n uniform sampler2D map;\n#endif"; + var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n #if defined( USE_POINTS_UV )\n vec2 uv = vUv;\n #else\n vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n #endif\n#endif\n#ifdef USE_MAP\n diffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n diffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif"; + var map_particle_pars_fragment = "#if defined( USE_POINTS_UV )\n varying vec2 vUv;\n#else\n #if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n uniform mat3 uvTransform;\n #endif\n#endif\n#ifdef USE_MAP\n uniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n uniform sampler2D alphaMap;\n#endif"; + var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n metalnessFactor *= texelMetalness.b;\n#endif"; + var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n uniform sampler2D metalnessMap;\n#endif"; + var morphcolor_vertex = "#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\n vColor *= morphTargetBaseInfluence;\n for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n #if defined( USE_COLOR_ALPHA )\n if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n #elif defined( USE_COLOR )\n if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n #endif\n }\n#endif"; + var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n objectNormal *= morphTargetBaseInfluence;\n #ifdef MORPHTARGETS_TEXTURE\n for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n }\n #else\n objectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n objectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n objectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n objectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n #endif\n#endif"; + var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n uniform float morphTargetBaseInfluence;\n #ifdef MORPHTARGETS_TEXTURE\n uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n uniform sampler2DArray morphTargetsTexture;\n uniform ivec2 morphTargetsTextureSize;\n vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n int y = texelIndex / morphTargetsTextureSize.x;\n int x = texelIndex - y * morphTargetsTextureSize.x;\n ivec3 morphUV = ivec3( x, y, morphTargetIndex );\n return texelFetch( morphTargetsTexture, morphUV, 0 );\n }\n #else\n #ifndef USE_MORPHNORMALS\n uniform float morphTargetInfluences[ 8 ];\n #else\n uniform float morphTargetInfluences[ 4 ];\n #endif\n #endif\n#endif"; + var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n transformed *= morphTargetBaseInfluence;\n #ifdef MORPHTARGETS_TEXTURE\n for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n }\n #else\n transformed += morphTarget0 * morphTargetInfluences[ 0 ];\n transformed += morphTarget1 * morphTargetInfluences[ 1 ];\n transformed += morphTarget2 * morphTargetInfluences[ 2 ];\n transformed += morphTarget3 * morphTargetInfluences[ 3 ];\n #ifndef USE_MORPHNORMALS\n transformed += morphTarget4 * morphTargetInfluences[ 4 ];\n transformed += morphTarget5 * morphTargetInfluences[ 5 ];\n transformed += morphTarget6 * morphTargetInfluences[ 6 ];\n transformed += morphTarget7 * morphTargetInfluences[ 7 ];\n #endif\n #endif\n#endif"; + var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n vec3 fdx = dFdx( vViewPosition );\n vec3 fdy = dFdy( vViewPosition );\n vec3 normal = normalize( cross( fdx, fdy ) );\n#else\n vec3 normal = normalize( vNormal );\n #ifdef DOUBLE_SIDED\n normal *= faceDirection;\n #endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n #ifdef USE_TANGENT\n mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n #else\n mat3 tbn = getTangentFrame( - vViewPosition, normal,\n #if defined( USE_NORMALMAP )\n vNormalMapUv\n #elif defined( USE_CLEARCOAT_NORMALMAP )\n vClearcoatNormalMapUv\n #else\n vUv\n #endif\n );\n #endif\n #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n tbn[0] *= faceDirection;\n tbn[1] *= faceDirection;\n #endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n #ifdef USE_TANGENT\n mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n #else\n mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n #endif\n #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n tbn2[0] *= faceDirection;\n tbn2[1] *= faceDirection;\n #endif\n#endif\nvec3 nonPerturbedNormal = normal;"; + var normal_fragment_maps = "#ifdef USE_NORMALMAP_OBJECTSPACE\n normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n #ifdef FLIP_SIDED\n normal = - normal;\n #endif\n #ifdef DOUBLE_SIDED\n normal = normal * faceDirection;\n #endif\n normal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n mapN.xy *= normalScale;\n normal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif"; + var normal_pars_fragment = "#ifndef FLAT_SHADED\n varying vec3 vNormal;\n #ifdef USE_TANGENT\n varying vec3 vTangent;\n varying vec3 vBitangent;\n #endif\n#endif"; + var normal_pars_vertex = "#ifndef FLAT_SHADED\n varying vec3 vNormal;\n #ifdef USE_TANGENT\n varying vec3 vTangent;\n varying vec3 vBitangent;\n #endif\n#endif"; + var normal_vertex = "#ifndef FLAT_SHADED\n vNormal = normalize( transformedNormal );\n #ifdef USE_TANGENT\n vTangent = normalize( transformedTangent );\n vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n #endif\n#endif"; + var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n uniform sampler2D normalMap;\n uniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n uniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n vec3 q0 = dFdx( eye_pos.xyz );\n vec3 q1 = dFdy( eye_pos.xyz );\n vec2 st0 = dFdx( uv.st );\n vec2 st1 = dFdy( uv.st );\n vec3 N = surf_norm;\n vec3 q1perp = cross( q1, N );\n vec3 q0perp = cross( N, q0 );\n vec3 T = q1perp * st0.x + q0perp * st1.x;\n vec3 B = q1perp * st0.y + q0perp * st1.y;\n float det = max( dot( T, T ), dot( B, B ) );\n float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n return mat3( T * scale, B * scale, N );\n }\n#endif"; + var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n vec3 clearcoatNormal = nonPerturbedNormal;\n#endif"; + var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n clearcoatMapN.xy *= clearcoatNormalScale;\n clearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif"; + var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n uniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n uniform sampler2D clearcoatNormalMap;\n uniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n uniform sampler2D clearcoatRoughnessMap;\n#endif"; + var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n uniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n uniform sampler2D iridescenceThicknessMap;\n#endif"; + var 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 );"; + var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * PackFactors ), v );\n r.yzw -= r.xyz * ShiftRight8; return r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n return dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n return packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n return unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n return 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 return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n return depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * depth - far );\n}"; + var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n gl_FragColor.rgb *= gl_FragColor.a;\n#endif"; + var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n mvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n mvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;"; + var dithering_fragment = "#ifdef DITHERING\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif"; + var dithering_pars_fragment = "#ifdef DITHERING\n vec3 dithering( vec3 color ) {\n float grid_position = rand( gl_FragCoord.xy );\n vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n return color + dither_shift_RGB;\n }\n#endif"; + var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n roughnessFactor *= texelRoughness.g;\n#endif"; + var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n uniform sampler2D roughnessMap;\n#endif"; + var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHT_SHADOWS > 0\n uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n struct DirectionalLightShadow {\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n #endif\n #if NUM_SPOT_LIGHT_SHADOWS > 0\n uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n struct SpotLightShadow {\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n #endif\n #if NUM_POINT_LIGHT_SHADOWS > 0\n uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n struct PointLightShadow {\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n float shadowCameraNear;\n float shadowCameraFar;\n };\n uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n #endif\n float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n }\n vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n return unpackRGBATo2Half( texture2D( shadow, uv ) );\n }\n float VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n float occlusion = 1.0;\n vec2 distribution = texture2DDistribution( shadow, uv );\n float hard_shadow = step( compare , distribution.x );\n if (hard_shadow != 1.0 ) {\n float distance = compare - distribution.x ;\n float variance = max( 0.00000, distribution.y * distribution.y );\n float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n }\n return occlusion;\n }\n float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n float shadow = 1.0;\n shadowCoord.xyz /= shadowCoord.w;\n shadowCoord.z += shadowBias;\n bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n bool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n if ( frustumTest ) {\n #if defined( SHADOWMAP_TYPE_PCF )\n vec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n float dx0 = - texelSize.x * shadowRadius;\n float dy0 = - texelSize.y * shadowRadius;\n float dx1 = + texelSize.x * shadowRadius;\n float dy1 = + texelSize.y * shadowRadius;\n float dx2 = dx0 / 2.0;\n float dy2 = dy0 / 2.0;\n float dx3 = dx1 / 2.0;\n float dy3 = dy1 / 2.0;\n shadow = (\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n ) * ( 1.0 / 17.0 );\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n vec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n float dx = texelSize.x;\n float dy = texelSize.y;\n vec2 uv = shadowCoord.xy;\n vec2 f = fract( uv * shadowMapSize + 0.5 );\n uv -= f * texelSize;\n shadow = (\n texture2DCompare( shadowMap, uv, shadowCoord.z ) +\n texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n f.x ) +\n mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n f.x ) +\n mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n f.y ) +\n mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n f.y ) +\n mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n f.x ),\n mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n f.x ),\n f.y )\n ) * ( 1.0 / 9.0 );\n #elif defined( SHADOWMAP_TYPE_VSM )\n shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n #else\n shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n #endif\n }\n return shadow;\n }\n vec2 cubeToUV( vec3 v, float texelSizeY ) {\n vec3 absV = abs( v );\n float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n absV *= scaleToCube;\n v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n vec2 planar = v.xy;\n float almostATexel = 1.5 * texelSizeY;\n float almostOne = 1.0 - almostATexel;\n if ( absV.z >= almostOne ) {\n if ( v.z > 0.0 )\n planar.x = 4.0 - v.x;\n } else if ( absV.x >= almostOne ) {\n float signX = sign( v.x );\n planar.x = v.z * signX + 2.0 * signX;\n } else if ( absV.y >= almostOne ) {\n float signY = sign( v.y );\n planar.x = v.x + 2.0 * signY + 2.0;\n planar.y = v.z * signY - 2.0;\n }\n return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n }\n float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n vec3 lightToPosition = shadowCoord.xyz;\n float dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias;\n vec3 bd3D = normalize( lightToPosition );\n #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n return (\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n ) * ( 1.0 / 9.0 );\n #else\n return texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n #endif\n }\n#endif"; + var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHT_SHADOWS > 0\n uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n struct DirectionalLightShadow {\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n #endif\n #if NUM_SPOT_LIGHT_SHADOWS > 0\n struct SpotLightShadow {\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n #endif\n #if NUM_POINT_LIGHT_SHADOWS > 0\n uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n struct PointLightShadow {\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n float shadowCameraNear;\n float shadowCameraFar;\n };\n uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n #endif\n#endif"; + var shadowmap_vertex = "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n vec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n #if NUM_DIR_LIGHT_SHADOWS > 0\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n }\n #pragma unroll_loop_end\n #endif\n #if NUM_POINT_LIGHT_SHADOWS > 0\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n }\n #pragma unroll_loop_end\n #endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n shadowWorldPosition = worldPosition;\n #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n #endif\n vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n }\n #pragma unroll_loop_end\n#endif"; + var shadowmask_pars_fragment = "float getShadowMask() {\n float shadow = 1.0;\n #ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHT_SHADOWS > 0\n DirectionalLightShadow directionalLight;\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n directionalLight = directionalLightShadows[ i ];\n shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n }\n #pragma unroll_loop_end\n #endif\n #if NUM_SPOT_LIGHT_SHADOWS > 0\n SpotLightShadow spotLight;\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n spotLight = spotLightShadows[ i ];\n shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n }\n #pragma unroll_loop_end\n #endif\n #if NUM_POINT_LIGHT_SHADOWS > 0\n PointLightShadow pointLight;\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n pointLight = pointLightShadows[ i ];\n shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n }\n #pragma unroll_loop_end\n #endif\n #endif\n return shadow;\n}"; + var skinbase_vertex = "#ifdef USE_SKINNING\n mat4 boneMatX = getBoneMatrix( skinIndex.x );\n mat4 boneMatY = getBoneMatrix( skinIndex.y );\n mat4 boneMatZ = getBoneMatrix( skinIndex.z );\n mat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif"; + var skinning_pars_vertex = "#ifdef USE_SKINNING\n uniform mat4 bindMatrix;\n uniform mat4 bindMatrixInverse;\n uniform highp sampler2D boneTexture;\n mat4 getBoneMatrix( const in float i ) {\n int size = textureSize( boneTexture, 0 ).x;\n int j = int( i ) * 4;\n int x = j % size;\n int y = j / size;\n vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n return mat4( v1, v2, v3, v4 );\n }\n#endif"; + var skinning_vertex = "#ifdef USE_SKINNING\n vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n vec4 skinned = vec4( 0.0 );\n skinned += boneMatX * skinVertex * skinWeight.x;\n skinned += boneMatY * skinVertex * skinWeight.y;\n skinned += boneMatZ * skinVertex * skinWeight.z;\n skinned += boneMatW * skinVertex * skinWeight.w;\n transformed = ( bindMatrixInverse * skinned ).xyz;\n#endif"; + var skinnormal_vertex = "#ifdef USE_SKINNING\n mat4 skinMatrix = mat4( 0.0 );\n skinMatrix += skinWeight.x * boneMatX;\n skinMatrix += skinWeight.y * boneMatY;\n skinMatrix += skinWeight.z * boneMatZ;\n skinMatrix += skinWeight.w * boneMatW;\n skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n #ifdef USE_TANGENT\n objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n #endif\n#endif"; + var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n specularStrength = texelSpecular.r;\n#else\n specularStrength = 1.0;\n#endif"; + var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n uniform sampler2D specularMap;\n#endif"; + var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif"; + var 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 return saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n vec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n return a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n const mat3 ACESInputMat = mat3(\n vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ),\n vec3( 0.04823, 0.01566, 0.83777 )\n );\n const mat3 ACESOutputMat = mat3(\n vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ),\n vec3( -0.07367, -0.00605, 1.07602 )\n );\n color *= toneMappingExposure / 0.6;\n color = ACESInputMat * color;\n color = RRTAndODTFit( color );\n color = ACESOutputMat * color;\n return saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n vec3( 1.6605, - 0.1246, - 0.0182 ),\n vec3( - 0.5876, 1.1329, - 0.1006 ),\n vec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n vec3( 0.6274, 0.0691, 0.0164 ),\n vec3( 0.3293, 0.9195, 0.0880 ),\n vec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n vec3 x2 = x * x;\n vec3 x4 = x2 * x2;\n return + 15.5 * x4 * x2\n - 40.14 * x4 * x\n + 31.96 * x4\n - 6.868 * x2 * x\n + 0.4298 * x2\n + 0.1191 * x\n - 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n const mat3 AgXInsetMatrix = mat3(\n vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n );\n const mat3 AgXOutsetMatrix = mat3(\n vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n );\n const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069;\n color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n color *= toneMappingExposure;\n color = AgXInsetMatrix * color;\n color = max( color, 1e-10 ); color = log2( color );\n color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n color = clamp( color, 0.0, 1.0 );\n color = agxDefaultContrastApprox( color );\n color = AgXOutsetMatrix * color;\n color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n color = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n return color;\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }"; + var transmission_fragment = "#ifdef USE_TRANSMISSION\n material.transmission = transmission;\n material.transmissionAlpha = 1.0;\n material.thickness = thickness;\n material.attenuationDistance = attenuationDistance;\n material.attenuationColor = attenuationColor;\n #ifdef USE_TRANSMISSIONMAP\n material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n #endif\n #ifdef USE_THICKNESSMAP\n material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n #endif\n vec3 pos = vWorldPosition;\n vec3 v = normalize( cameraPosition - pos );\n vec3 n = inverseTransformDirection( normal, viewMatrix );\n vec4 transmitted = getIBLVolumeRefraction(\n n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n pos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n material.attenuationColor, material.attenuationDistance );\n material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif"; + var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n uniform float transmission;\n uniform float thickness;\n uniform float attenuationDistance;\n uniform vec3 attenuationColor;\n #ifdef USE_TRANSMISSIONMAP\n uniform sampler2D transmissionMap;\n #endif\n #ifdef USE_THICKNESSMAP\n uniform sampler2D thicknessMap;\n #endif\n uniform vec2 transmissionSamplerSize;\n uniform sampler2D transmissionSamplerMap;\n uniform mat4 modelMatrix;\n uniform mat4 projectionMatrix;\n varying vec3 vWorldPosition;\n float w0( float a ) {\n return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n }\n float w1( float a ) {\n return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n }\n float w2( float a ){\n return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n }\n float w3( float a ) {\n return ( 1.0 / 6.0 ) * ( a * a * a );\n }\n float g0( float a ) {\n return w0( a ) + w1( a );\n }\n float g1( float a ) {\n return w2( a ) + w3( a );\n }\n float h0( float a ) {\n return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n }\n float h1( float a ) {\n return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n }\n vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n uv = uv * texelSize.zw + 0.5;\n vec2 iuv = floor( uv );\n vec2 fuv = fract( uv );\n float g0x = g0( fuv.x );\n float g1x = g1( fuv.x );\n float h0x = h0( fuv.x );\n float h1x = h1( fuv.x );\n float h0y = h0( fuv.y );\n float h1y = h1( fuv.y );\n vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n }\n vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n vec2 fLodSizeInv = 1.0 / fLodSize;\n vec2 cLodSizeInv = 1.0 / cLodSize;\n vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n return mix( fSample, cSample, fract( lod ) );\n }\n vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n vec3 modelScale;\n modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n return normalize( refractionVector ) * thickness * modelScale;\n }\n float applyIorToRoughness( const in float roughness, const in float ior ) {\n return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n }\n vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n }\n vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n if ( isinf( attenuationDistance ) ) {\n return vec3( 1.0 );\n } else {\n vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance;\n }\n }\n vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n const in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n const in vec3 attenuationColor, const in float attenuationDistance ) {\n vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n vec3 refractedRayExit = position + transmissionRay;\n vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n vec2 refractionCoords = ndcPos.xy / ndcPos.w;\n refractionCoords += 1.0;\n refractionCoords /= 2.0;\n vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n vec3 transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n vec3 attenuatedColor = transmittance * transmittedLight.rgb;\n vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n }\n#endif"; + var uv_pars_fragment = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n varying vec2 vUv;\n#endif\n#ifdef USE_MAP\n varying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n varying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n varying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n varying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n varying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n varying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n varying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n varying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n varying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n varying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n varying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n varying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n varying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n varying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n varying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n varying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n varying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n varying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n varying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n varying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n uniform mat3 transmissionMapTransform;\n varying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n uniform mat3 thicknessMapTransform;\n varying vec2 vThicknessMapUv;\n#endif"; + var uv_pars_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n varying vec2 vUv;\n#endif\n#ifdef USE_MAP\n uniform mat3 mapTransform;\n varying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n uniform mat3 alphaMapTransform;\n varying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n uniform mat3 lightMapTransform;\n varying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n uniform mat3 aoMapTransform;\n varying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n uniform mat3 bumpMapTransform;\n varying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n uniform mat3 normalMapTransform;\n varying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n uniform mat3 displacementMapTransform;\n varying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n uniform mat3 emissiveMapTransform;\n varying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n uniform mat3 metalnessMapTransform;\n varying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n uniform mat3 roughnessMapTransform;\n varying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n uniform mat3 anisotropyMapTransform;\n varying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n uniform mat3 clearcoatMapTransform;\n varying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n uniform mat3 clearcoatNormalMapTransform;\n varying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n uniform mat3 clearcoatRoughnessMapTransform;\n varying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n uniform mat3 sheenColorMapTransform;\n varying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n uniform mat3 sheenRoughnessMapTransform;\n varying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n uniform mat3 iridescenceMapTransform;\n varying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n uniform mat3 iridescenceThicknessMapTransform;\n varying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n uniform mat3 specularMapTransform;\n varying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n uniform mat3 specularColorMapTransform;\n varying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n uniform mat3 specularIntensityMapTransform;\n varying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n uniform mat3 transmissionMapTransform;\n varying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n uniform mat3 thicknessMapTransform;\n varying vec2 vThicknessMapUv;\n#endif"; + var uv_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n vUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif"; + var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n vec4 worldPosition = vec4( transformed, 1.0 );\n #ifdef USE_BATCHING\n worldPosition = batchingMatrix * worldPosition;\n #endif\n #ifdef USE_INSTANCING\n worldPosition = instanceMatrix * worldPosition;\n #endif\n worldPosition = modelMatrix * worldPosition;\n#endif"; + var vertex$h = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n vUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n gl_Position = vec4( position.xy, 1.0, 1.0 );\n}"; + var fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n vec4 texColor = texture2D( t2D, vUv );\n #ifdef DECODE_VIDEO_TEXTURE\n texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n #endif\n texColor.rgb *= backgroundIntensity;\n gl_FragColor = texColor;\n #include \n #include \n}"; + var vertex$g = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n vWorldDirection = transformDirection( position, modelMatrix );\n #include \n #include \n gl_Position.z = gl_Position.w;\n}"; + var fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n uniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n #ifdef ENVMAP_TYPE_CUBE\n vec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n #elif defined( ENVMAP_TYPE_CUBE_UV )\n vec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );\n #else\n vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n #endif\n texColor.rgb *= backgroundIntensity;\n gl_FragColor = texColor;\n #include \n #include \n}"; + var vertex$f = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n vWorldDirection = transformDirection( position, modelMatrix );\n #include \n #include \n gl_Position.z = gl_Position.w;\n}"; + var fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n gl_FragColor = texColor;\n gl_FragColor.a *= opacity;\n #include \n #include \n}"; + var vertex$e = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n #include \n #include \n #include \n #ifdef USE_DISPLACEMENTMAP\n #include \n #include \n #include \n #endif\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vHighPrecisionZW = gl_Position.zw;\n}"; + var fragment$e = "#if DEPTH_PACKING == 3200\n uniform 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 #include \n vec4 diffuseColor = vec4( 1.0 );\n #if DEPTH_PACKING == 3200\n diffuseColor.a = opacity;\n #endif\n #include \n #include \n #include \n #include \n #include \n float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n #if DEPTH_PACKING == 3200\n gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n #elif DEPTH_PACKING == 3201\n gl_FragColor = packDepthToRGBA( fragCoordZ );\n #endif\n}"; + var vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #ifdef USE_DISPLACEMENTMAP\n #include \n #include \n #include \n #endif\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vWorldPosition = worldPosition.xyz;\n}"; + var fragment$d = "#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 \n#include \nvoid main () {\n #include \n vec4 diffuseColor = vec4( 1.0 );\n #include \n #include \n #include \n #include \n float dist = length( vWorldPosition - referencePosition );\n dist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n dist = saturate( dist );\n gl_FragColor = packDepthToRGBA( dist );\n}"; + var vertex$c = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n vWorldDirection = transformDirection( position, modelMatrix );\n #include \n #include \n}"; + var fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n vec3 direction = normalize( vWorldDirection );\n vec2 sampleUV = equirectUv( direction );\n gl_FragColor = texture2D( tEquirect, sampleUV );\n #include \n #include \n}"; + var vertex$b = "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 vLineDistance = scale * lineDistance;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; + var fragment$b = "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 #include \n if ( mod( vLineDistance, totalSize ) > dashSize ) {\n discard;\n }\n vec3 outgoingLight = vec3( 0.0 );\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n #include \n #include \n outgoingLight = diffuseColor.rgb;\n #include \n #include \n #include \n #include \n #include \n}"; + var vertex$a = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n #include \n #include \n #include \n #include \n #include \n #endif\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; + var fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n varying 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 #include \n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n #ifdef USE_LIGHTMAP\n vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n #else\n reflectedLight.indirectDiffuse += vec3( 1.0 );\n #endif\n #include \n reflectedLight.indirectDiffuse *= diffuseColor.rgb;\n vec3 outgoingLight = reflectedLight.indirectDiffuse;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; + var vertex$9 = "#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 #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 vViewPosition = - mvPosition.xyz;\n #include \n #include \n #include \n #include \n}"; + var fragment$9 = "#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 \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 diffuseColor = vec4( diffuse, opacity );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\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 vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; + var vertex$8 = "#define MATCAP\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 \nvoid main() {\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 vViewPosition = - mvPosition.xyz;\n}"; + var fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\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 \n#include \nvoid main() {\n #include \n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vec3 viewDir = normalize( vViewPosition );\n vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n vec3 y = cross( viewDir, x );\n vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n #ifdef USE_MATCAP\n vec4 matcapColor = texture2D( matcap, uv );\n #else\n vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n #endif\n vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n #include \n #include \n #include \n #include \n #include \n #include \n}"; + var vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n varying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\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#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n vViewPosition = - mvPosition.xyz;\n#endif\n}"; + var fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n varying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n gl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n #ifdef OPAQUE\n gl_FragColor.a = 1.0;\n #endif\n}"; + var vertex$6 = "#define PHONG\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 #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 vViewPosition = - mvPosition.xyz;\n #include \n #include \n #include \n #include \n}"; + var fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\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 \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 diffuseColor = vec4( diffuse, opacity );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\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 vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; + var vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n varying vec3 vWorldPosition;\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 \nvoid main() {\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 vViewPosition = - mvPosition.xyz;\n #include \n #include \n #include \n#ifdef USE_TRANSMISSION\n vWorldPosition = worldPosition.xyz;\n#endif\n}"; + var fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n #define IOR\n #define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n uniform float ior;\n#endif\n#ifdef USE_SPECULAR\n uniform float specularIntensity;\n uniform vec3 specularColor;\n #ifdef USE_SPECULAR_COLORMAP\n uniform sampler2D specularColorMap;\n #endif\n #ifdef USE_SPECULAR_INTENSITYMAP\n uniform sampler2D specularIntensityMap;\n #endif\n#endif\n#ifdef USE_CLEARCOAT\n uniform float clearcoat;\n uniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n uniform float iridescence;\n uniform float iridescenceIOR;\n uniform float iridescenceThicknessMinimum;\n uniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n uniform vec3 sheenColor;\n uniform float sheenRoughness;\n #ifdef USE_SHEEN_COLORMAP\n uniform sampler2D sheenColorMap;\n #endif\n #ifdef USE_SHEEN_ROUGHNESSMAP\n uniform sampler2D sheenRoughnessMap;\n #endif\n#endif\n#ifdef USE_ANISOTROPY\n uniform vec2 anisotropyVector;\n #ifdef USE_ANISOTROPYMAP\n uniform sampler2D anisotropyMap;\n #endif\n#endif\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 \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 \nvoid main() {\n #include \n vec4 diffuseColor = vec4( diffuse, opacity );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\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 vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n #include \n vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n #ifdef USE_SHEEN\n float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;\n #endif\n #ifdef USE_CLEARCOAT\n float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n #endif\n #include \n #include \n #include \n #include \n #include \n #include \n}"; + var vertex$4 = "#define TOON\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 \nvoid main() {\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 vViewPosition = - mvPosition.xyz;\n #include \n #include \n #include \n}"; + var fragment$4 = "#define TOON\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 \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 diffuseColor = vec4( diffuse, opacity );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\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 vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n #include \n #include \n #include \n #include \n #include \n #include \n}"; + var vertex$3 = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef USE_POINTS_UV\n varying vec2 vUv;\n uniform mat3 uvTransform;\n#endif\nvoid main() {\n #ifdef USE_POINTS_UV\n vUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n #endif\n #include \n #include \n #include \n #include \n #include \n gl_PointSize = size;\n #ifdef USE_SIZEATTENUATION\n bool isPerspective = isPerspectiveMatrix( projectionMatrix );\n if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n #endif\n #include \n #include \n #include \n #include \n}"; + var fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec3 outgoingLight = vec3( 0.0 );\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n #include \n #include \n #include \n #include \n outgoingLight = diffuseColor.rgb;\n #include \n #include \n #include \n #include \n #include \n}"; + var vertex$2 = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\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}"; + var fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n #include \n #include \n #include \n}"; + var vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n vec2 scale;\n scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n #ifndef USE_SIZEATTENUATION\n bool isPerspective = isPerspectiveMatrix( projectionMatrix );\n if ( isPerspective ) scale *= - mvPosition.z;\n #endif\n vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n vec2 rotatedPosition;\n rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n mvPosition.xy += rotatedPosition;\n gl_Position = projectionMatrix * mvPosition;\n #include \n #include \n #include \n}"; + var fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec3 outgoingLight = vec3( 0.0 );\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n #include \n #include \n #include \n #include \n outgoingLight = diffuseColor.rgb;\n #include \n #include \n #include \n #include \n}"; + var ShaderChunk = { + alphahash_fragment, + alphahash_pars_fragment, + alphamap_fragment, + alphamap_pars_fragment, + alphatest_fragment, + alphatest_pars_fragment, + aomap_fragment, + aomap_pars_fragment, + batching_pars_vertex, + batching_vertex, + begin_vertex, + beginnormal_vertex, + bsdfs, + iridescence_fragment, + bumpmap_pars_fragment, + clipping_planes_fragment, + clipping_planes_pars_fragment, + clipping_planes_pars_vertex, + clipping_planes_vertex, + color_fragment, + color_pars_fragment, + color_pars_vertex, + color_vertex, + common, + cube_uv_reflection_fragment, + defaultnormal_vertex, + displacementmap_pars_vertex, + displacementmap_vertex, + emissivemap_fragment, + emissivemap_pars_fragment, + colorspace_fragment, + colorspace_pars_fragment, + envmap_fragment, + envmap_common_pars_fragment, + envmap_pars_fragment, + envmap_pars_vertex, + envmap_physical_pars_fragment, + envmap_vertex, + fog_vertex, + fog_pars_vertex, + fog_fragment, + fog_pars_fragment, + gradientmap_pars_fragment, + lightmap_fragment, + lightmap_pars_fragment, + lights_lambert_fragment, + lights_lambert_pars_fragment, + lights_pars_begin, + lights_toon_fragment, + lights_toon_pars_fragment, + lights_phong_fragment, + lights_phong_pars_fragment, + lights_physical_fragment, + lights_physical_pars_fragment, + lights_fragment_begin, + lights_fragment_maps, + lights_fragment_end, + logdepthbuf_fragment, + logdepthbuf_pars_fragment, + logdepthbuf_pars_vertex, + logdepthbuf_vertex, + map_fragment, + map_pars_fragment, + map_particle_fragment, + map_particle_pars_fragment, + metalnessmap_fragment, + metalnessmap_pars_fragment, + morphcolor_vertex, + morphnormal_vertex, + morphtarget_pars_vertex, + morphtarget_vertex, + normal_fragment_begin, + normal_fragment_maps, + normal_pars_fragment, + normal_pars_vertex, + normal_vertex, + normalmap_pars_fragment, + clearcoat_normal_fragment_begin, + clearcoat_normal_fragment_maps, + clearcoat_pars_fragment, + iridescence_pars_fragment, + opaque_fragment, + packing, + premultiplied_alpha_fragment, + project_vertex, + dithering_fragment, + dithering_pars_fragment, + roughnessmap_fragment, + roughnessmap_pars_fragment, + shadowmap_pars_fragment, + shadowmap_pars_vertex, + shadowmap_vertex, + shadowmask_pars_fragment, + skinbase_vertex, + skinning_pars_vertex, + skinning_vertex, + skinnormal_vertex, + specularmap_fragment, + specularmap_pars_fragment, + tonemapping_fragment, + tonemapping_pars_fragment, + transmission_fragment, + transmission_pars_fragment, + uv_pars_fragment, + uv_pars_vertex, + uv_vertex, + worldpos_vertex, + background_vert: vertex$h, + background_frag: fragment$h, + backgroundCube_vert: vertex$g, + backgroundCube_frag: fragment$g, + cube_vert: vertex$f, + cube_frag: fragment$f, + depth_vert: vertex$e, + depth_frag: fragment$e, + distanceRGBA_vert: vertex$d, + distanceRGBA_frag: fragment$d, + equirect_vert: vertex$c, + equirect_frag: fragment$c, + linedashed_vert: vertex$b, + linedashed_frag: fragment$b, + meshbasic_vert: vertex$a, + meshbasic_frag: fragment$a, + meshlambert_vert: vertex$9, + meshlambert_frag: fragment$9, + meshmatcap_vert: vertex$8, + meshmatcap_frag: fragment$8, + meshnormal_vert: vertex$7, + meshnormal_frag: fragment$7, + meshphong_vert: vertex$6, + meshphong_frag: fragment$6, + meshphysical_vert: vertex$5, + meshphysical_frag: fragment$5, + meshtoon_vert: vertex$4, + meshtoon_frag: fragment$4, + points_vert: vertex$3, + points_frag: fragment$3, + shadow_vert: vertex$2, + shadow_frag: fragment$2, + sprite_vert: vertex$1, + sprite_frag: fragment$1 + }; + var UniformsLib = { + common: { + diffuse: { value: /* @__PURE__ */ new Color(16777215) }, + opacity: { value: 1 }, + map: { value: null }, + mapTransform: { value: /* @__PURE__ */ new Matrix3() }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + alphaTest: { value: 0 } + }, + specularmap: { + specularMap: { value: null }, + specularMapTransform: { value: /* @__PURE__ */ new Matrix3() } + }, + envmap: { + envMap: { value: null }, + flipEnvMap: { value: -1 }, + reflectivity: { value: 1 }, + // basic, lambert, phong + ior: { value: 1.5 }, + // physical + refractionRatio: { value: 0.98 } + // basic, lambert, phong + }, + aomap: { + aoMap: { value: null }, + aoMapIntensity: { value: 1 }, + aoMapTransform: { value: /* @__PURE__ */ new Matrix3() } + }, + lightmap: { + lightMap: { value: null }, + lightMapIntensity: { value: 1 }, + lightMapTransform: { value: /* @__PURE__ */ new Matrix3() } + }, + bumpmap: { + bumpMap: { value: null }, + bumpMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + bumpScale: { value: 1 } + }, + normalmap: { + normalMap: { value: null }, + normalMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + normalScale: { value: /* @__PURE__ */ new Vector2(1, 1) } + }, + displacementmap: { + displacementMap: { value: null }, + displacementMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + displacementScale: { value: 1 }, + displacementBias: { value: 0 } + }, + emissivemap: { + emissiveMap: { value: null }, + emissiveMapTransform: { value: /* @__PURE__ */ new Matrix3() } + }, + metalnessmap: { + metalnessMap: { value: null }, + metalnessMapTransform: { value: /* @__PURE__ */ new Matrix3() } + }, + roughnessmap: { + roughnessMap: { value: null }, + roughnessMapTransform: { value: /* @__PURE__ */ new Matrix3() } + }, + gradientmap: { + gradientMap: { value: null } + }, + fog: { + fogDensity: { value: 25e-5 }, + fogNear: { value: 1 }, + fogFar: { value: 2e3 }, + fogColor: { value: /* @__PURE__ */ new Color(16777215) } + }, + lights: { + ambientLightColor: { value: [] }, + lightProbe: { value: [] }, + directionalLights: { value: [], properties: { + direction: {}, + color: {} + } }, + directionalLightShadows: { value: [], properties: { + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + directionalShadowMap: { value: [] }, + directionalShadowMatrix: { value: [] }, + spotLights: { value: [], properties: { + color: {}, + position: {}, + direction: {}, + distance: {}, + coneCos: {}, + penumbraCos: {}, + decay: {} + } }, + spotLightShadows: { value: [], properties: { + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + spotLightMap: { value: [] }, + spotShadowMap: { value: [] }, + spotLightMatrix: { value: [] }, + pointLights: { value: [], properties: { + color: {}, + position: {}, + decay: {}, + distance: {} + } }, + pointLightShadows: { value: [], properties: { + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {}, + shadowCameraNear: {}, + shadowCameraFar: {} + } }, + pointShadowMap: { value: [] }, + pointShadowMatrix: { value: [] }, + hemisphereLights: { value: [], properties: { + direction: {}, + skyColor: {}, + groundColor: {} + } }, + // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src + rectAreaLights: { value: [], properties: { + color: {}, + position: {}, + width: {}, + height: {} + } }, + ltc_1: { value: null }, + ltc_2: { value: null } + }, + points: { + diffuse: { value: /* @__PURE__ */ new Color(16777215) }, + opacity: { value: 1 }, + size: { value: 1 }, + scale: { value: 1 }, + map: { value: null }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + alphaTest: { value: 0 }, + uvTransform: { value: /* @__PURE__ */ new Matrix3() } + }, + sprite: { + diffuse: { value: /* @__PURE__ */ new Color(16777215) }, + opacity: { value: 1 }, + center: { value: /* @__PURE__ */ new Vector2(0.5, 0.5) }, + rotation: { value: 0 }, + map: { value: null }, + mapTransform: { value: /* @__PURE__ */ new Matrix3() }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + alphaTest: { value: 0 } + } + }; + var ShaderLib = { + basic: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.fog + ]), + vertexShader: ShaderChunk.meshbasic_vert, + fragmentShader: ShaderChunk.meshbasic_frag + }, + lambert: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) } + } + ]), + vertexShader: ShaderChunk.meshlambert_vert, + fragmentShader: ShaderChunk.meshlambert_frag + }, + phong: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) }, + specular: { value: /* @__PURE__ */ new Color(1118481) }, + shininess: { value: 30 } + } + ]), + vertexShader: ShaderChunk.meshphong_vert, + fragmentShader: ShaderChunk.meshphong_frag + }, + standard: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.roughnessmap, + UniformsLib.metalnessmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) }, + roughness: { value: 1 }, + metalness: { value: 0 }, + envMapIntensity: { value: 1 } + // temporary + } + ]), + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag + }, + toon: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.gradientmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) } + } + ]), + vertexShader: ShaderChunk.meshtoon_vert, + fragmentShader: ShaderChunk.meshtoon_frag + }, + matcap: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + { + matcap: { value: null } + } + ]), + vertexShader: ShaderChunk.meshmatcap_vert, + fragmentShader: ShaderChunk.meshmatcap_frag + }, + points: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.points, + UniformsLib.fog + ]), + vertexShader: ShaderChunk.points_vert, + fragmentShader: ShaderChunk.points_frag + }, + dashed: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.fog, + { + scale: { value: 1 }, + dashSize: { value: 1 }, + totalSize: { value: 2 } + } + ]), + vertexShader: ShaderChunk.linedashed_vert, + fragmentShader: ShaderChunk.linedashed_frag + }, + depth: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.displacementmap + ]), + vertexShader: ShaderChunk.depth_vert, + fragmentShader: ShaderChunk.depth_frag + }, + normal: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + { + opacity: { value: 1 } + } + ]), + vertexShader: ShaderChunk.meshnormal_vert, + fragmentShader: ShaderChunk.meshnormal_frag + }, + sprite: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.sprite, + UniformsLib.fog + ]), + vertexShader: ShaderChunk.sprite_vert, + fragmentShader: ShaderChunk.sprite_frag + }, + background: { + uniforms: { + uvTransform: { value: /* @__PURE__ */ new Matrix3() }, + t2D: { value: null }, + backgroundIntensity: { value: 1 } + }, + vertexShader: ShaderChunk.background_vert, + fragmentShader: ShaderChunk.background_frag + }, + backgroundCube: { + uniforms: { + envMap: { value: null }, + flipEnvMap: { value: -1 }, + backgroundBlurriness: { value: 0 }, + backgroundIntensity: { value: 1 } + }, + vertexShader: ShaderChunk.backgroundCube_vert, + fragmentShader: ShaderChunk.backgroundCube_frag + }, + cube: { + uniforms: { + tCube: { value: null }, + tFlip: { value: -1 }, + opacity: { value: 1 } + }, + vertexShader: ShaderChunk.cube_vert, + fragmentShader: ShaderChunk.cube_frag + }, + equirect: { + uniforms: { + tEquirect: { value: null } + }, + vertexShader: ShaderChunk.equirect_vert, + fragmentShader: ShaderChunk.equirect_frag + }, + distanceRGBA: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.displacementmap, + { + referencePosition: { value: /* @__PURE__ */ new Vector3() }, + nearDistance: { value: 1 }, + farDistance: { value: 1e3 } + } + ]), + vertexShader: ShaderChunk.distanceRGBA_vert, + fragmentShader: ShaderChunk.distanceRGBA_frag + }, + shadow: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.lights, + UniformsLib.fog, + { + color: { value: /* @__PURE__ */ new Color(0) }, + opacity: { value: 1 } + } + ]), + vertexShader: ShaderChunk.shadow_vert, + fragmentShader: ShaderChunk.shadow_frag + } + }; + ShaderLib.physical = { + uniforms: /* @__PURE__ */ mergeUniforms([ + ShaderLib.standard.uniforms, + { + clearcoat: { value: 0 }, + clearcoatMap: { value: null }, + clearcoatMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + clearcoatNormalMap: { value: null }, + clearcoatNormalMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + clearcoatNormalScale: { value: /* @__PURE__ */ new Vector2(1, 1) }, + clearcoatRoughness: { value: 0 }, + clearcoatRoughnessMap: { value: null }, + clearcoatRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + iridescence: { value: 0 }, + iridescenceMap: { value: null }, + iridescenceMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + iridescenceIOR: { value: 1.3 }, + iridescenceThicknessMinimum: { value: 100 }, + iridescenceThicknessMaximum: { value: 400 }, + iridescenceThicknessMap: { value: null }, + iridescenceThicknessMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + sheen: { value: 0 }, + sheenColor: { value: /* @__PURE__ */ new Color(0) }, + sheenColorMap: { value: null }, + sheenColorMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + sheenRoughness: { value: 1 }, + sheenRoughnessMap: { value: null }, + sheenRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + transmission: { value: 0 }, + transmissionMap: { value: null }, + transmissionMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + transmissionSamplerSize: { value: /* @__PURE__ */ new Vector2() }, + transmissionSamplerMap: { value: null }, + thickness: { value: 0 }, + thicknessMap: { value: null }, + thicknessMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + attenuationDistance: { value: 0 }, + attenuationColor: { value: /* @__PURE__ */ new Color(0) }, + specularColor: { value: /* @__PURE__ */ new Color(1, 1, 1) }, + specularColorMap: { value: null }, + specularColorMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + specularIntensity: { value: 1 }, + specularIntensityMap: { value: null }, + specularIntensityMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + anisotropyVector: { value: /* @__PURE__ */ new Vector2() }, + anisotropyMap: { value: null }, + anisotropyMapTransform: { value: /* @__PURE__ */ new Matrix3() } + } + ]), + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag + }; + var _rgb = { r: 0, b: 0, g: 0 }; + function WebGLBackground(renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha) { + const clearColor = new Color(0); + let clearAlpha = alpha === true ? 0 : 1; + let planeMesh; + let boxMesh; + let currentBackground = null; + let currentBackgroundVersion = 0; + let currentTonemapping = null; + function render(renderList, scene) { + let forceClear = false; + let background = scene.isScene === true ? scene.background : null; + if (background && background.isTexture) { + const usePMREM = scene.backgroundBlurriness > 0; + background = (usePMREM ? cubeuvmaps : cubemaps).get(background); + } + if (background === null) { + setClear(clearColor, clearAlpha); + } else if (background && background.isColor) { + setClear(background, 1); + forceClear = true; + } + const environmentBlendMode = renderer.xr.getEnvironmentBlendMode(); + if (environmentBlendMode === "additive") { + state.buffers.color.setClear(0, 0, 0, 1, premultipliedAlpha); + } else if (environmentBlendMode === "alpha-blend") { + state.buffers.color.setClear(0, 0, 0, 0, premultipliedAlpha); + } + if (renderer.autoClear || forceClear) { + renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil); + } + if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) { + if (boxMesh === void 0) { + boxMesh = new Mesh( + new BoxGeometry(1, 1, 1), + new ShaderMaterial({ + name: "BackgroundCubeMaterial", + uniforms: cloneUniforms(ShaderLib.backgroundCube.uniforms), + vertexShader: ShaderLib.backgroundCube.vertexShader, + fragmentShader: ShaderLib.backgroundCube.fragmentShader, + side: BackSide, + depthTest: false, + depthWrite: false, + fog: false + }) + ); + boxMesh.geometry.deleteAttribute("normal"); + boxMesh.geometry.deleteAttribute("uv"); + boxMesh.onBeforeRender = function(renderer2, scene2, camera) { + this.matrixWorld.copyPosition(camera.matrixWorld); + }; + Object.defineProperty(boxMesh.material, "envMap", { + get: function() { + return this.uniforms.envMap.value; + } + }); + objects.update(boxMesh); + } + boxMesh.material.uniforms.envMap.value = background; + boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1; + boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness; + boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + boxMesh.material.toneMapped = ColorManagement.getTransfer(background.colorSpace) !== SRGBTransfer; + if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) { + boxMesh.material.needsUpdate = true; + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer.toneMapping; + } + boxMesh.layers.enableAll(); + renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null); + } else if (background && background.isTexture) { + if (planeMesh === void 0) { + planeMesh = new Mesh( + new PlaneGeometry(2, 2), + new ShaderMaterial({ + name: "BackgroundMaterial", + uniforms: cloneUniforms(ShaderLib.background.uniforms), + vertexShader: ShaderLib.background.vertexShader, + fragmentShader: ShaderLib.background.fragmentShader, + side: FrontSide, + depthTest: false, + depthWrite: false, + fog: false + }) + ); + planeMesh.geometry.deleteAttribute("normal"); + Object.defineProperty(planeMesh.material, "map", { + get: function() { + return this.uniforms.t2D.value; + } + }); + objects.update(planeMesh); + } + planeMesh.material.uniforms.t2D.value = background; + planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + planeMesh.material.toneMapped = ColorManagement.getTransfer(background.colorSpace) !== SRGBTransfer; + if (background.matrixAutoUpdate === true) { + background.updateMatrix(); + } + planeMesh.material.uniforms.uvTransform.value.copy(background.matrix); + if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) { + planeMesh.material.needsUpdate = true; + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer.toneMapping; + } + planeMesh.layers.enableAll(); + renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null); + } + } + function setClear(color, alpha2) { + color.getRGB(_rgb, getUnlitUniformColorSpace(renderer)); + state.buffers.color.setClear(_rgb.r, _rgb.g, _rgb.b, alpha2, premultipliedAlpha); + } + return { + getClearColor: function() { + return clearColor; + }, + setClearColor: function(color, alpha2 = 1) { + clearColor.set(color); + clearAlpha = alpha2; + setClear(clearColor, clearAlpha); + }, + getClearAlpha: function() { + return clearAlpha; + }, + setClearAlpha: function(alpha2) { + clearAlpha = alpha2; + setClear(clearColor, clearAlpha); + }, + render + }; + } + function WebGLBindingStates(gl, extensions, attributes, capabilities) { + const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + const extension = capabilities.isWebGL2 ? null : extensions.get("OES_vertex_array_object"); + const vaoAvailable = capabilities.isWebGL2 || extension !== null; + const bindingStates = {}; + const defaultState = createBindingState(null); + let currentState = defaultState; + let forceUpdate = false; + function setup(object, material, program, geometry, index) { + let updateBuffers = false; + if (vaoAvailable) { + const state = getBindingState(geometry, program, material); + if (currentState !== state) { + currentState = state; + bindVertexArrayObject(currentState.object); + } + updateBuffers = needsUpdate(object, geometry, program, index); + if (updateBuffers) saveCache(object, geometry, program, index); + } else { + const wireframe = material.wireframe === true; + if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) { + currentState.geometry = geometry.id; + currentState.program = program.id; + currentState.wireframe = wireframe; + updateBuffers = true; + } + } + if (index !== null) { + attributes.update(index, gl.ELEMENT_ARRAY_BUFFER); + } + if (updateBuffers || forceUpdate) { + forceUpdate = false; + setupVertexAttributes(object, material, program, geometry); + if (index !== null) { + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer); + } + } + } + function createVertexArrayObject() { + if (capabilities.isWebGL2) return gl.createVertexArray(); + return extension.createVertexArrayOES(); + } + function bindVertexArrayObject(vao) { + if (capabilities.isWebGL2) return gl.bindVertexArray(vao); + return extension.bindVertexArrayOES(vao); + } + function deleteVertexArrayObject(vao) { + if (capabilities.isWebGL2) return gl.deleteVertexArray(vao); + return extension.deleteVertexArrayOES(vao); + } + function getBindingState(geometry, program, material) { + const wireframe = material.wireframe === true; + let programMap = bindingStates[geometry.id]; + if (programMap === void 0) { + programMap = {}; + bindingStates[geometry.id] = programMap; + } + let stateMap = programMap[program.id]; + if (stateMap === void 0) { + stateMap = {}; + programMap[program.id] = stateMap; + } + let state = stateMap[wireframe]; + if (state === void 0) { + state = createBindingState(createVertexArrayObject()); + stateMap[wireframe] = state; + } + return state; + } + function createBindingState(vao) { + const newAttributes = []; + const enabledAttributes = []; + const attributeDivisors = []; + for (let i = 0; i < maxVertexAttributes; i++) { + newAttributes[i] = 0; + enabledAttributes[i] = 0; + attributeDivisors[i] = 0; + } + return { + // for backward compatibility on non-VAO support browser + geometry: null, + program: null, + wireframe: false, + newAttributes, + enabledAttributes, + attributeDivisors, + object: vao, + attributes: {}, + index: null + }; + } + function needsUpdate(object, geometry, program, index) { + const cachedAttributes = currentState.attributes; + const geometryAttributes = geometry.attributes; + let attributesNum = 0; + const programAttributes = program.getAttributes(); + for (const name in programAttributes) { + const programAttribute = programAttributes[name]; + if (programAttribute.location >= 0) { + const cachedAttribute = cachedAttributes[name]; + let geometryAttribute = geometryAttributes[name]; + if (geometryAttribute === void 0) { + if (name === "instanceMatrix" && object.instanceMatrix) geometryAttribute = object.instanceMatrix; + if (name === "instanceColor" && object.instanceColor) geometryAttribute = object.instanceColor; + } + if (cachedAttribute === void 0) return true; + if (cachedAttribute.attribute !== geometryAttribute) return true; + if (geometryAttribute && cachedAttribute.data !== geometryAttribute.data) return true; + attributesNum++; + } + } + if (currentState.attributesNum !== attributesNum) return true; + if (currentState.index !== index) return true; + return false; + } + function saveCache(object, geometry, program, index) { + const cache = {}; + const attributes2 = geometry.attributes; + let attributesNum = 0; + const programAttributes = program.getAttributes(); + for (const name in programAttributes) { + const programAttribute = programAttributes[name]; + if (programAttribute.location >= 0) { + let attribute = attributes2[name]; + if (attribute === void 0) { + if (name === "instanceMatrix" && object.instanceMatrix) attribute = object.instanceMatrix; + if (name === "instanceColor" && object.instanceColor) attribute = object.instanceColor; + } + const data = {}; + data.attribute = attribute; + if (attribute && attribute.data) { + data.data = attribute.data; + } + cache[name] = data; + attributesNum++; + } + } + currentState.attributes = cache; + currentState.attributesNum = attributesNum; + currentState.index = index; + } + function initAttributes() { + const newAttributes = currentState.newAttributes; + for (let i = 0, il = newAttributes.length; i < il; i++) { + newAttributes[i] = 0; + } + } + function enableAttribute(attribute) { + enableAttributeAndDivisor(attribute, 0); + } + function enableAttributeAndDivisor(attribute, meshPerAttribute) { + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + const attributeDivisors = currentState.attributeDivisors; + newAttributes[attribute] = 1; + if (enabledAttributes[attribute] === 0) { + gl.enableVertexAttribArray(attribute); + enabledAttributes[attribute] = 1; + } + if (attributeDivisors[attribute] !== meshPerAttribute) { + const extension2 = capabilities.isWebGL2 ? gl : extensions.get("ANGLE_instanced_arrays"); + extension2[capabilities.isWebGL2 ? "vertexAttribDivisor" : "vertexAttribDivisorANGLE"](attribute, meshPerAttribute); + attributeDivisors[attribute] = meshPerAttribute; + } + } + function disableUnusedAttributes() { + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + for (let i = 0, il = enabledAttributes.length; i < il; i++) { + if (enabledAttributes[i] !== newAttributes[i]) { + gl.disableVertexAttribArray(i); + enabledAttributes[i] = 0; + } + } + } + function vertexAttribPointer(index, size, type, normalized, stride, offset, integer) { + if (integer === true) { + gl.vertexAttribIPointer(index, size, type, stride, offset); + } else { + gl.vertexAttribPointer(index, size, type, normalized, stride, offset); + } + } + function setupVertexAttributes(object, material, program, geometry) { + if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) { + if (extensions.get("ANGLE_instanced_arrays") === null) return; + } + initAttributes(); + const geometryAttributes = geometry.attributes; + const programAttributes = program.getAttributes(); + const materialDefaultAttributeValues = material.defaultAttributeValues; + for (const name in programAttributes) { + const programAttribute = programAttributes[name]; + if (programAttribute.location >= 0) { + let geometryAttribute = geometryAttributes[name]; + if (geometryAttribute === void 0) { + if (name === "instanceMatrix" && object.instanceMatrix) geometryAttribute = object.instanceMatrix; + if (name === "instanceColor" && object.instanceColor) geometryAttribute = object.instanceColor; + } + if (geometryAttribute !== void 0) { + const normalized = geometryAttribute.normalized; + const size = geometryAttribute.itemSize; + const attribute = attributes.get(geometryAttribute); + if (attribute === void 0) continue; + const buffer = attribute.buffer; + const type = attribute.type; + const bytesPerElement = attribute.bytesPerElement; + const integer = capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType); + if (geometryAttribute.isInterleavedBufferAttribute) { + const data = geometryAttribute.data; + const stride = data.stride; + const offset = geometryAttribute.offset; + if (data.isInstancedInterleavedBuffer) { + for (let i = 0; i < programAttribute.locationSize; i++) { + enableAttributeAndDivisor(programAttribute.location + i, data.meshPerAttribute); + } + if (object.isInstancedMesh !== true && geometry._maxInstanceCount === void 0) { + geometry._maxInstanceCount = data.meshPerAttribute * data.count; + } + } else { + for (let i = 0; i < programAttribute.locationSize; i++) { + enableAttribute(programAttribute.location + i); + } + } + gl.bindBuffer(gl.ARRAY_BUFFER, buffer); + for (let i = 0; i < programAttribute.locationSize; i++) { + vertexAttribPointer( + programAttribute.location + i, + size / programAttribute.locationSize, + type, + normalized, + stride * bytesPerElement, + (offset + size / programAttribute.locationSize * i) * bytesPerElement, + integer + ); + } + } else { + if (geometryAttribute.isInstancedBufferAttribute) { + for (let i = 0; i < programAttribute.locationSize; i++) { + enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute); + } + if (object.isInstancedMesh !== true && geometry._maxInstanceCount === void 0) { + geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + } + } else { + for (let i = 0; i < programAttribute.locationSize; i++) { + enableAttribute(programAttribute.location + i); + } + } + gl.bindBuffer(gl.ARRAY_BUFFER, buffer); + for (let i = 0; i < programAttribute.locationSize; i++) { + vertexAttribPointer( + programAttribute.location + i, + size / programAttribute.locationSize, + type, + normalized, + size * bytesPerElement, + size / programAttribute.locationSize * i * bytesPerElement, + integer + ); + } + } + } else if (materialDefaultAttributeValues !== void 0) { + const value = materialDefaultAttributeValues[name]; + if (value !== void 0) { + switch (value.length) { + case 2: + gl.vertexAttrib2fv(programAttribute.location, value); + break; + case 3: + gl.vertexAttrib3fv(programAttribute.location, value); + break; + case 4: + gl.vertexAttrib4fv(programAttribute.location, value); + break; + default: + gl.vertexAttrib1fv(programAttribute.location, value); + } + } + } + } + } + disableUnusedAttributes(); + } + function dispose() { + reset(); + for (const geometryId in bindingStates) { + const programMap = bindingStates[geometryId]; + for (const programId in programMap) { + const stateMap = programMap[programId]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[programId]; + } + delete bindingStates[geometryId]; + } + } + function releaseStatesOfGeometry(geometry) { + if (bindingStates[geometry.id] === void 0) return; + const programMap = bindingStates[geometry.id]; + for (const programId in programMap) { + const stateMap = programMap[programId]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[programId]; + } + delete bindingStates[geometry.id]; + } + function releaseStatesOfProgram(program) { + for (const geometryId in bindingStates) { + const programMap = bindingStates[geometryId]; + if (programMap[program.id] === void 0) continue; + const stateMap = programMap[program.id]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[program.id]; + } + } + function reset() { + resetDefaultState(); + forceUpdate = true; + if (currentState === defaultState) return; + currentState = defaultState; + bindVertexArrayObject(currentState.object); + } + function resetDefaultState() { + defaultState.geometry = null; + defaultState.program = null; + defaultState.wireframe = false; + } + return { + setup, + reset, + resetDefaultState, + dispose, + releaseStatesOfGeometry, + releaseStatesOfProgram, + initAttributes, + enableAttribute, + disableUnusedAttributes + }; + } + function WebGLBufferRenderer(gl, extensions, info, capabilities) { + const isWebGL2 = capabilities.isWebGL2; + let mode; + function setMode(value) { + mode = value; + } + function render(start, count) { + gl.drawArrays(mode, start, count); + info.update(count, mode, 1); + } + function renderInstances(start, count, primcount) { + if (primcount === 0) return; + let extension, methodName; + if (isWebGL2) { + extension = gl; + methodName = "drawArraysInstanced"; + } else { + extension = extensions.get("ANGLE_instanced_arrays"); + methodName = "drawArraysInstancedANGLE"; + if (extension === null) { + console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."); + return; + } + } + extension[methodName](mode, start, count, primcount); + info.update(count, mode, primcount); + } + function renderMultiDraw(starts, counts, drawCount) { + if (drawCount === 0) return; + const extension = extensions.get("WEBGL_multi_draw"); + if (extension === null) { + for (let i = 0; i < drawCount; i++) { + this.render(starts[i], counts[i]); + } + } else { + extension.multiDrawArraysWEBGL(mode, starts, 0, counts, 0, drawCount); + let elementCount = 0; + for (let i = 0; i < drawCount; i++) { + elementCount += counts[i]; + } + info.update(elementCount, mode, 1); + } + } + this.setMode = setMode; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + } + function WebGLCapabilities(gl, extensions, parameters) { + let maxAnisotropy; + function getMaxAnisotropy() { + if (maxAnisotropy !== void 0) return maxAnisotropy; + if (extensions.has("EXT_texture_filter_anisotropic") === true) { + const extension = extensions.get("EXT_texture_filter_anisotropic"); + maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT); + } else { + maxAnisotropy = 0; + } + return maxAnisotropy; + } + function getMaxPrecision(precision2) { + if (precision2 === "highp") { + if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) { + return "highp"; + } + precision2 = "mediump"; + } + if (precision2 === "mediump") { + if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) { + return "mediump"; + } + } + return "lowp"; + } + const isWebGL2 = typeof WebGL2RenderingContext !== "undefined" && gl.constructor.name === "WebGL2RenderingContext"; + let precision = parameters.precision !== void 0 ? parameters.precision : "highp"; + const maxPrecision = getMaxPrecision(precision); + if (maxPrecision !== precision) { + console.warn("THREE.WebGLRenderer:", precision, "not supported, using", maxPrecision, "instead."); + precision = maxPrecision; + } + const drawBuffers = isWebGL2 || extensions.has("WEBGL_draw_buffers"); + const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; + const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); + const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE); + const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS); + const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS); + const vertexTextures = maxVertexTextures > 0; + const floatFragmentTextures = isWebGL2 || extensions.has("OES_texture_float"); + const floatVertexTextures = vertexTextures && floatFragmentTextures; + const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0; + return { + isWebGL2, + drawBuffers, + getMaxAnisotropy, + getMaxPrecision, + precision, + logarithmicDepthBuffer, + maxTextures, + maxVertexTextures, + maxTextureSize, + maxCubemapSize, + maxAttributes, + maxVertexUniforms, + maxVaryings, + maxFragmentUniforms, + vertexTextures, + floatFragmentTextures, + floatVertexTextures, + maxSamples + }; + } + function WebGLClipping(properties) { + const scope = this; + let globalState = null, numGlobalPlanes = 0, localClippingEnabled = false, renderingShadows = false; + const plane = new Plane(), viewNormalMatrix = new Matrix3(), uniform = { value: null, needsUpdate: false }; + this.uniform = uniform; + this.numPlanes = 0; + this.numIntersection = 0; + this.init = function(planes, enableLocalClipping) { + const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to + // run another frame in order to reset the state: + numGlobalPlanes !== 0 || localClippingEnabled; + localClippingEnabled = enableLocalClipping; + numGlobalPlanes = planes.length; + return enabled; + }; + this.beginShadows = function() { + renderingShadows = true; + projectPlanes(null); + }; + this.endShadows = function() { + renderingShadows = false; + }; + this.setGlobalState = function(planes, camera) { + globalState = projectPlanes(planes, camera, 0); + }; + this.setState = function(material, camera, useCache) { + const planes = material.clippingPlanes, clipIntersection = material.clipIntersection, clipShadows = material.clipShadows; + const materialProperties = properties.get(material); + if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) { + if (renderingShadows) { + projectPlanes(null); + } else { + resetGlobalState(); + } + } else { + const nGlobal = renderingShadows ? 0 : numGlobalPlanes, lGlobal = nGlobal * 4; + let dstArray = materialProperties.clippingState || null; + uniform.value = dstArray; + dstArray = projectPlanes(planes, camera, lGlobal, useCache); + for (let i = 0; i !== lGlobal; ++i) { + dstArray[i] = globalState[i]; + } + materialProperties.clippingState = dstArray; + this.numIntersection = clipIntersection ? this.numPlanes : 0; + this.numPlanes += nGlobal; + } + }; + function resetGlobalState() { + if (uniform.value !== globalState) { + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; + } + scope.numPlanes = numGlobalPlanes; + scope.numIntersection = 0; + } + function projectPlanes(planes, camera, dstOffset, skipTransform) { + const nPlanes = planes !== null ? planes.length : 0; + let dstArray = null; + if (nPlanes !== 0) { + dstArray = uniform.value; + if (skipTransform !== true || dstArray === null) { + const flatSize = dstOffset + nPlanes * 4, viewMatrix = camera.matrixWorldInverse; + viewNormalMatrix.getNormalMatrix(viewMatrix); + if (dstArray === null || dstArray.length < flatSize) { + dstArray = new Float32Array(flatSize); + } + for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) { + plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix); + plane.normal.toArray(dstArray, i4); + dstArray[i4 + 3] = plane.constant; + } + } + uniform.value = dstArray; + uniform.needsUpdate = true; + } + scope.numPlanes = nPlanes; + scope.numIntersection = 0; + return dstArray; + } + } + function WebGLCubeMaps(renderer) { + let cubemaps = /* @__PURE__ */ new WeakMap(); + function mapTextureMapping(texture, mapping) { + if (mapping === EquirectangularReflectionMapping) { + texture.mapping = CubeReflectionMapping; + } else if (mapping === EquirectangularRefractionMapping) { + texture.mapping = CubeRefractionMapping; + } + return texture; + } + function get(texture) { + if (texture && texture.isTexture) { + const mapping = texture.mapping; + if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) { + if (cubemaps.has(texture)) { + const cubemap = cubemaps.get(texture).texture; + return mapTextureMapping(cubemap, texture.mapping); + } else { + const image = texture.image; + if (image && image.height > 0) { + const renderTarget = new WebGLCubeRenderTarget(image.height / 2); + renderTarget.fromEquirectangularTexture(renderer, texture); + cubemaps.set(texture, renderTarget); + texture.addEventListener("dispose", onTextureDispose); + return mapTextureMapping(renderTarget.texture, texture.mapping); + } else { + return null; + } + } + } + } + return texture; + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + const cubemap = cubemaps.get(texture); + if (cubemap !== void 0) { + cubemaps.delete(texture); + cubemap.dispose(); + } + } + function dispose() { + cubemaps = /* @__PURE__ */ new WeakMap(); + } + return { + get, + dispose + }; + } + var OrthographicCamera = class extends Camera { + constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2e3) { + super(); + this.isOrthographicCamera = true; + this.type = "OrthographicCamera"; + this.zoom = 1; + this.view = null; + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; + this.near = near; + this.far = far; + this.updateProjectionMatrix(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign({}, source.view); + return this; + } + setViewOffset(fullWidth, fullHeight, x, y, width, height) { + if (this.view === null) { + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + } + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width; + this.view.height = height; + this.updateProjectionMatrix(); + } + clearViewOffset() { + if (this.view !== null) { + this.view.enabled = false; + } + this.updateProjectionMatrix(); + } + updateProjectionMatrix() { + const dx = (this.right - this.left) / (2 * this.zoom); + const dy = (this.top - this.bottom) / (2 * this.zoom); + const cx = (this.right + this.left) / 2; + const cy = (this.top + this.bottom) / 2; + let left = cx - dx; + let right = cx + dx; + let top = cy + dy; + let bottom = cy - dy; + if (this.view !== null && this.view.enabled) { + const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom; + const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom; + left += scaleW * this.view.offsetX; + right = left + scaleW * this.view.width; + top -= scaleH * this.view.offsetY; + bottom = top - scaleH * this.view.height; + } + this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far, this.coordinateSystem); + this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + } + toJSON(meta) { + const data = super.toJSON(meta); + data.object.zoom = this.zoom; + data.object.left = this.left; + data.object.right = this.right; + data.object.top = this.top; + data.object.bottom = this.bottom; + data.object.near = this.near; + data.object.far = this.far; + if (this.view !== null) data.object.view = Object.assign({}, this.view); + return data; + } + }; + var LOD_MIN = 4; + var EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582]; + var MAX_SAMPLES = 20; + var _flatCamera = /* @__PURE__ */ new OrthographicCamera(); + var _clearColor = /* @__PURE__ */ new Color(); + var _oldTarget = null; + var _oldActiveCubeFace = 0; + var _oldActiveMipmapLevel = 0; + var PHI = (1 + Math.sqrt(5)) / 2; + var INV_PHI = 1 / PHI; + var _axisDirections = [ + /* @__PURE__ */ new Vector3(1, 1, 1), + /* @__PURE__ */ new Vector3(-1, 1, 1), + /* @__PURE__ */ new Vector3(1, 1, -1), + /* @__PURE__ */ new Vector3(-1, 1, -1), + /* @__PURE__ */ new Vector3(0, PHI, INV_PHI), + /* @__PURE__ */ new Vector3(0, PHI, -INV_PHI), + /* @__PURE__ */ new Vector3(INV_PHI, 0, PHI), + /* @__PURE__ */ new Vector3(-INV_PHI, 0, PHI), + /* @__PURE__ */ new Vector3(PHI, INV_PHI, 0), + /* @__PURE__ */ new Vector3(-PHI, INV_PHI, 0) + ]; + var PMREMGenerator = class { + constructor(renderer) { + this._renderer = renderer; + this._pingPongRenderTarget = null; + this._lodMax = 0; + this._cubeSize = 0; + this._lodPlanes = []; + this._sizeLods = []; + this._sigmas = []; + this._blurMaterial = null; + this._cubemapMaterial = null; + this._equirectMaterial = null; + this._compileMaterial(this._blurMaterial); + } + /** + * Generates a PMREM from a supplied Scene, which can be faster than using an + * image if networking bandwidth is low. Optional sigma specifies a blur radius + * in radians to be applied to the scene before PMREM generation. Optional near + * and far planes ensure the scene is rendered in its entirety (the cubeCamera + * is placed at the origin). + */ + fromScene(scene, sigma = 0, near = 0.1, far = 100) { + _oldTarget = this._renderer.getRenderTarget(); + _oldActiveCubeFace = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); + this._setSize(256); + const cubeUVRenderTarget = this._allocateTargets(); + cubeUVRenderTarget.depthBuffer = true; + this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget); + if (sigma > 0) { + this._blur(cubeUVRenderTarget, 0, 0, sigma); + } + this._applyPMREM(cubeUVRenderTarget); + this._cleanup(cubeUVRenderTarget); + return cubeUVRenderTarget; + } + /** + * Generates a PMREM from an equirectangular texture, which can be either LDR + * or HDR. The ideal input image size is 1k (1024 x 512), + * as this matches best with the 256 x 256 cubemap output. + */ + fromEquirectangular(equirectangular, renderTarget = null) { + return this._fromTexture(equirectangular, renderTarget); + } + /** + * Generates a PMREM from an cubemap texture, which can be either LDR + * or HDR. The ideal input cube size is 256 x 256, + * as this matches best with the 256 x 256 cubemap output. + */ + fromCubemap(cubemap, renderTarget = null) { + return this._fromTexture(cubemap, renderTarget); + } + /** + * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileCubemapShader() { + if (this._cubemapMaterial === null) { + this._cubemapMaterial = _getCubemapMaterial(); + this._compileMaterial(this._cubemapMaterial); + } + } + /** + * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileEquirectangularShader() { + if (this._equirectMaterial === null) { + this._equirectMaterial = _getEquirectMaterial(); + this._compileMaterial(this._equirectMaterial); + } + } + /** + * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, + * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on + * one of them will cause any others to also become unusable. + */ + dispose() { + this._dispose(); + if (this._cubemapMaterial !== null) this._cubemapMaterial.dispose(); + if (this._equirectMaterial !== null) this._equirectMaterial.dispose(); + } + // private interface + _setSize(cubeSize) { + this._lodMax = Math.floor(Math.log2(cubeSize)); + this._cubeSize = Math.pow(2, this._lodMax); + } + _dispose() { + if (this._blurMaterial !== null) this._blurMaterial.dispose(); + if (this._pingPongRenderTarget !== null) this._pingPongRenderTarget.dispose(); + for (let i = 0; i < this._lodPlanes.length; i++) { + this._lodPlanes[i].dispose(); + } + } + _cleanup(outputTarget) { + this._renderer.setRenderTarget(_oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel); + outputTarget.scissorTest = false; + _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height); + } + _fromTexture(texture, renderTarget) { + if (texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping) { + this._setSize(texture.image.length === 0 ? 16 : texture.image[0].width || texture.image[0].image.width); + } else { + this._setSize(texture.image.width / 4); + } + _oldTarget = this._renderer.getRenderTarget(); + _oldActiveCubeFace = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); + const cubeUVRenderTarget = renderTarget || this._allocateTargets(); + this._textureToCubeUV(texture, cubeUVRenderTarget); + this._applyPMREM(cubeUVRenderTarget); + this._cleanup(cubeUVRenderTarget); + return cubeUVRenderTarget; + } + _allocateTargets() { + const width = 3 * Math.max(this._cubeSize, 16 * 7); + const height = 4 * this._cubeSize; + const params = { + magFilter: LinearFilter, + minFilter: LinearFilter, + generateMipmaps: false, + type: HalfFloatType, + format: RGBAFormat, + colorSpace: LinearSRGBColorSpace, + depthBuffer: false + }; + const cubeUVRenderTarget = _createRenderTarget(width, height, params); + if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height) { + if (this._pingPongRenderTarget !== null) { + this._dispose(); + } + this._pingPongRenderTarget = _createRenderTarget(width, height, params); + const { _lodMax } = this; + ({ sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes(_lodMax)); + this._blurMaterial = _getBlurShader(_lodMax, width, height); + } + return cubeUVRenderTarget; + } + _compileMaterial(material) { + const tmpMesh = new Mesh(this._lodPlanes[0], material); + this._renderer.compile(tmpMesh, _flatCamera); + } + _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) { + const fov2 = 90; + const aspect2 = 1; + const cubeCamera = new PerspectiveCamera(fov2, aspect2, near, far); + const upSign = [1, -1, 1, 1, 1, 1]; + const forwardSign = [1, 1, 1, -1, -1, -1]; + const renderer = this._renderer; + const originalAutoClear = renderer.autoClear; + const toneMapping = renderer.toneMapping; + renderer.getClearColor(_clearColor); + renderer.toneMapping = NoToneMapping; + renderer.autoClear = false; + const backgroundMaterial = new MeshBasicMaterial({ + name: "PMREM.Background", + side: BackSide, + depthWrite: false, + depthTest: false + }); + const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial); + let useSolidColor = false; + const background = scene.background; + if (background) { + if (background.isColor) { + backgroundMaterial.color.copy(background); + scene.background = null; + useSolidColor = true; + } + } else { + backgroundMaterial.color.copy(_clearColor); + useSolidColor = true; + } + for (let i = 0; i < 6; i++) { + const col = i % 3; + if (col === 0) { + cubeCamera.up.set(0, upSign[i], 0); + cubeCamera.lookAt(forwardSign[i], 0, 0); + } else if (col === 1) { + cubeCamera.up.set(0, 0, upSign[i]); + cubeCamera.lookAt(0, forwardSign[i], 0); + } else { + cubeCamera.up.set(0, upSign[i], 0); + cubeCamera.lookAt(0, 0, forwardSign[i]); + } + const size = this._cubeSize; + _setViewport(cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size); + renderer.setRenderTarget(cubeUVRenderTarget); + if (useSolidColor) { + renderer.render(backgroundBox, cubeCamera); + } + renderer.render(scene, cubeCamera); + } + backgroundBox.geometry.dispose(); + backgroundBox.material.dispose(); + renderer.toneMapping = toneMapping; + renderer.autoClear = originalAutoClear; + scene.background = background; + } + _textureToCubeUV(texture, cubeUVRenderTarget) { + const renderer = this._renderer; + const isCubeTexture = texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping; + if (isCubeTexture) { + if (this._cubemapMaterial === null) { + this._cubemapMaterial = _getCubemapMaterial(); + } + this._cubemapMaterial.uniforms.flipEnvMap.value = texture.isRenderTargetTexture === false ? -1 : 1; + } else { + if (this._equirectMaterial === null) { + this._equirectMaterial = _getEquirectMaterial(); + } + } + const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; + const mesh = new Mesh(this._lodPlanes[0], material); + const uniforms = material.uniforms; + uniforms["envMap"].value = texture; + const size = this._cubeSize; + _setViewport(cubeUVRenderTarget, 0, 0, 3 * size, 2 * size); + renderer.setRenderTarget(cubeUVRenderTarget); + renderer.render(mesh, _flatCamera); + } + _applyPMREM(cubeUVRenderTarget) { + const renderer = this._renderer; + const autoClear = renderer.autoClear; + renderer.autoClear = false; + for (let i = 1; i < this._lodPlanes.length; i++) { + const sigma = Math.sqrt(this._sigmas[i] * this._sigmas[i] - this._sigmas[i - 1] * this._sigmas[i - 1]); + const poleAxis = _axisDirections[(i - 1) % _axisDirections.length]; + this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis); + } + renderer.autoClear = autoClear; + } + /** + * This is a two-pass Gaussian blur for a cubemap. Normally this is done + * vertically and horizontally, but this breaks down on a cube. Here we apply + * the blur latitudinally (around the poles), and then longitudinally (towards + * the poles) to approximate the orthogonally-separable blur. It is least + * accurate at the poles, but still does a decent job. + */ + _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) { + const pingPongRenderTarget = this._pingPongRenderTarget; + this._halfBlur( + cubeUVRenderTarget, + pingPongRenderTarget, + lodIn, + lodOut, + sigma, + "latitudinal", + poleAxis + ); + this._halfBlur( + pingPongRenderTarget, + cubeUVRenderTarget, + lodOut, + lodOut, + sigma, + "longitudinal", + poleAxis + ); + } + _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) { + const renderer = this._renderer; + const blurMaterial = this._blurMaterial; + if (direction !== "latitudinal" && direction !== "longitudinal") { + console.error( + "blur direction must be either latitudinal or longitudinal!" + ); + } + const STANDARD_DEVIATIONS = 3; + const blurMesh = new Mesh(this._lodPlanes[lodOut], blurMaterial); + const blurUniforms = blurMaterial.uniforms; + const pixels = this._sizeLods[lodIn] - 1; + const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1); + const sigmaPixels = sigmaRadians / radiansPerPixel; + const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES; + if (samples > MAX_SAMPLES) { + console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`); + } + const weights = []; + let sum = 0; + for (let i = 0; i < MAX_SAMPLES; ++i) { + const x2 = i / sigmaPixels; + const weight = Math.exp(-x2 * x2 / 2); + weights.push(weight); + if (i === 0) { + sum += weight; + } else if (i < samples) { + sum += 2 * weight; + } + } + for (let i = 0; i < weights.length; i++) { + weights[i] = weights[i] / sum; + } + blurUniforms["envMap"].value = targetIn.texture; + blurUniforms["samples"].value = samples; + blurUniforms["weights"].value = weights; + blurUniforms["latitudinal"].value = direction === "latitudinal"; + if (poleAxis) { + blurUniforms["poleAxis"].value = poleAxis; + } + const { _lodMax } = this; + blurUniforms["dTheta"].value = radiansPerPixel; + blurUniforms["mipInt"].value = _lodMax - lodIn; + const outputSize = this._sizeLods[lodOut]; + const x = 3 * outputSize * (lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0); + const y = 4 * (this._cubeSize - outputSize); + _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize); + renderer.setRenderTarget(targetOut); + renderer.render(blurMesh, _flatCamera); + } + }; + function _createPlanes(lodMax) { + const lodPlanes = []; + const sizeLods = []; + const sigmas = []; + let lod = lodMax; + const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; + for (let i = 0; i < totalLods; i++) { + const sizeLod = Math.pow(2, lod); + sizeLods.push(sizeLod); + let sigma = 1 / sizeLod; + if (i > lodMax - LOD_MIN) { + sigma = EXTRA_LOD_SIGMA[i - lodMax + LOD_MIN - 1]; + } else if (i === 0) { + sigma = 0; + } + sigmas.push(sigma); + const texelSize = 1 / (sizeLod - 2); + const min = -texelSize; + const max2 = 1 + texelSize; + const uv1 = [min, min, max2, min, max2, max2, min, min, max2, max2, min, max2]; + const cubeFaces = 6; + const vertices = 6; + const positionSize = 3; + const uvSize = 2; + const faceIndexSize = 1; + const position = new Float32Array(positionSize * vertices * cubeFaces); + const uv = new Float32Array(uvSize * vertices * cubeFaces); + const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces); + for (let face = 0; face < cubeFaces; face++) { + const x = face % 3 * 2 / 3 - 1; + const y = face > 2 ? 0 : -1; + const coordinates = [ + x, + y, + 0, + x + 2 / 3, + y, + 0, + x + 2 / 3, + y + 1, + 0, + x, + y, + 0, + x + 2 / 3, + y + 1, + 0, + x, + y + 1, + 0 + ]; + position.set(coordinates, positionSize * vertices * face); + uv.set(uv1, uvSize * vertices * face); + const fill = [face, face, face, face, face, face]; + faceIndex.set(fill, faceIndexSize * vertices * face); + } + const planes = new BufferGeometry(); + planes.setAttribute("position", new BufferAttribute(position, positionSize)); + planes.setAttribute("uv", new BufferAttribute(uv, uvSize)); + planes.setAttribute("faceIndex", new BufferAttribute(faceIndex, faceIndexSize)); + lodPlanes.push(planes); + if (lod > LOD_MIN) { + lod--; + } + } + return { lodPlanes, sizeLods, sigmas }; + } + function _createRenderTarget(width, height, params) { + const cubeUVRenderTarget = new WebGLRenderTarget(width, height, params); + cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; + cubeUVRenderTarget.texture.name = "PMREM.cubeUv"; + cubeUVRenderTarget.scissorTest = true; + return cubeUVRenderTarget; + } + function _setViewport(target, x, y, width, height) { + target.viewport.set(x, y, width, height); + target.scissor.set(x, y, width, height); + } + function _getBlurShader(lodMax, width, height) { + const weights = new Float32Array(MAX_SAMPLES); + const poleAxis = new Vector3(0, 1, 0); + const shaderMaterial = new ShaderMaterial({ + name: "SphericalGaussianBlur", + defines: { + "n": MAX_SAMPLES, + "CUBEUV_TEXEL_WIDTH": 1 / width, + "CUBEUV_TEXEL_HEIGHT": 1 / height, + "CUBEUV_MAX_MIP": `${lodMax}.0` + }, + uniforms: { + "envMap": { value: null }, + "samples": { value: 1 }, + "weights": { value: weights }, + "latitudinal": { value: false }, + "dTheta": { value: 0 }, + "mipInt": { value: 0 }, + "poleAxis": { value: poleAxis } + }, + vertexShader: _getCommonVertexShader(), + fragmentShader: ( + /* glsl */ + ` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + ` + ), + blending: NoBlending, + depthTest: false, + depthWrite: false + }); + return shaderMaterial; + } + function _getEquirectMaterial() { + return new ShaderMaterial({ + name: "EquirectangularToCubeUV", + uniforms: { + "envMap": { value: null } + }, + vertexShader: _getCommonVertexShader(), + fragmentShader: ( + /* glsl */ + ` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + ` + ), + blending: NoBlending, + depthTest: false, + depthWrite: false + }); + } + function _getCubemapMaterial() { + return new ShaderMaterial({ + name: "CubemapToCubeUV", + uniforms: { + "envMap": { value: null }, + "flipEnvMap": { value: -1 } + }, + vertexShader: _getCommonVertexShader(), + fragmentShader: ( + /* glsl */ + ` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + ` + ), + blending: NoBlending, + depthTest: false, + depthWrite: false + }); + } + function _getCommonVertexShader() { + return ( + /* glsl */ + ` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + ` + ); + } + function WebGLCubeUVMaps(renderer) { + let cubeUVmaps = /* @__PURE__ */ new WeakMap(); + let pmremGenerator = null; + function get(texture) { + if (texture && texture.isTexture) { + const mapping = texture.mapping; + const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping; + const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping; + if (isEquirectMap || isCubeMap) { + if (texture.isRenderTargetTexture && texture.needsPMREMUpdate === true) { + texture.needsPMREMUpdate = false; + let renderTarget = cubeUVmaps.get(texture); + if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer); + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget); + cubeUVmaps.set(texture, renderTarget); + return renderTarget.texture; + } else { + if (cubeUVmaps.has(texture)) { + return cubeUVmaps.get(texture).texture; + } else { + const image = texture.image; + if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) { + if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer); + const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture); + cubeUVmaps.set(texture, renderTarget); + texture.addEventListener("dispose", onTextureDispose); + return renderTarget.texture; + } else { + return null; + } + } + } + } + } + return texture; + } + function isCubeTextureComplete(image) { + let count = 0; + const length = 6; + for (let i = 0; i < length; i++) { + if (image[i] !== void 0) count++; + } + return count === length; + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + const cubemapUV = cubeUVmaps.get(texture); + if (cubemapUV !== void 0) { + cubeUVmaps.delete(texture); + cubemapUV.dispose(); + } + } + function dispose() { + cubeUVmaps = /* @__PURE__ */ new WeakMap(); + if (pmremGenerator !== null) { + pmremGenerator.dispose(); + pmremGenerator = null; + } + } + return { + get, + dispose + }; + } + function WebGLExtensions(gl) { + const extensions = {}; + function getExtension(name) { + if (extensions[name] !== void 0) { + return extensions[name]; + } + let extension; + switch (name) { + case "WEBGL_depth_texture": + extension = gl.getExtension("WEBGL_depth_texture") || gl.getExtension("MOZ_WEBGL_depth_texture") || gl.getExtension("WEBKIT_WEBGL_depth_texture"); + break; + case "EXT_texture_filter_anisotropic": + extension = gl.getExtension("EXT_texture_filter_anisotropic") || gl.getExtension("MOZ_EXT_texture_filter_anisotropic") || gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic"); + break; + case "WEBGL_compressed_texture_s3tc": + extension = gl.getExtension("WEBGL_compressed_texture_s3tc") || gl.getExtension("MOZ_WEBGL_compressed_texture_s3tc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"); + break; + case "WEBGL_compressed_texture_pvrtc": + extension = gl.getExtension("WEBGL_compressed_texture_pvrtc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"); + break; + default: + extension = gl.getExtension(name); + } + extensions[name] = extension; + return extension; + } + return { + has: function(name) { + return getExtension(name) !== null; + }, + init: function(capabilities) { + if (capabilities.isWebGL2) { + getExtension("EXT_color_buffer_float"); + getExtension("WEBGL_clip_cull_distance"); + } else { + getExtension("WEBGL_depth_texture"); + getExtension("OES_texture_float"); + getExtension("OES_texture_half_float"); + getExtension("OES_texture_half_float_linear"); + getExtension("OES_standard_derivatives"); + getExtension("OES_element_index_uint"); + getExtension("OES_vertex_array_object"); + getExtension("ANGLE_instanced_arrays"); + } + getExtension("OES_texture_float_linear"); + getExtension("EXT_color_buffer_half_float"); + getExtension("WEBGL_multisampled_render_to_texture"); + }, + get: function(name) { + const extension = getExtension(name); + if (extension === null) { + console.warn("THREE.WebGLRenderer: " + name + " extension not supported."); + } + return extension; + } + }; + } + function WebGLGeometries(gl, attributes, info, bindingStates) { + const geometries = {}; + const wireframeAttributes = /* @__PURE__ */ new WeakMap(); + function onGeometryDispose(event) { + const geometry = event.target; + if (geometry.index !== null) { + attributes.remove(geometry.index); + } + for (const name in geometry.attributes) { + attributes.remove(geometry.attributes[name]); + } + for (const name in geometry.morphAttributes) { + const array = geometry.morphAttributes[name]; + for (let i = 0, l = array.length; i < l; i++) { + attributes.remove(array[i]); + } + } + geometry.removeEventListener("dispose", onGeometryDispose); + delete geometries[geometry.id]; + const attribute = wireframeAttributes.get(geometry); + if (attribute) { + attributes.remove(attribute); + wireframeAttributes.delete(geometry); + } + bindingStates.releaseStatesOfGeometry(geometry); + if (geometry.isInstancedBufferGeometry === true) { + delete geometry._maxInstanceCount; + } + info.memory.geometries--; + } + function get(object, geometry) { + if (geometries[geometry.id] === true) return geometry; + geometry.addEventListener("dispose", onGeometryDispose); + geometries[geometry.id] = true; + info.memory.geometries++; + return geometry; + } + function update(geometry) { + const geometryAttributes = geometry.attributes; + for (const name in geometryAttributes) { + attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER); + } + const morphAttributes = geometry.morphAttributes; + for (const name in morphAttributes) { + const array = morphAttributes[name]; + for (let i = 0, l = array.length; i < l; i++) { + attributes.update(array[i], gl.ARRAY_BUFFER); + } + } + } + function updateWireframeAttribute(geometry) { + const indices = []; + const geometryIndex = geometry.index; + const geometryPosition = geometry.attributes.position; + let version = 0; + if (geometryIndex !== null) { + const array = geometryIndex.array; + version = geometryIndex.version; + for (let i = 0, l = array.length; i < l; i += 3) { + const a = array[i + 0]; + const b = array[i + 1]; + const c = array[i + 2]; + indices.push(a, b, b, c, c, a); + } + } else if (geometryPosition !== void 0) { + const array = geometryPosition.array; + version = geometryPosition.version; + for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) { + const a = i + 0; + const b = i + 1; + const c = i + 2; + indices.push(a, b, b, c, c, a); + } + } else { + return; + } + const attribute = new (arrayNeedsUint32(indices) ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1); + attribute.version = version; + const previousAttribute = wireframeAttributes.get(geometry); + if (previousAttribute) attributes.remove(previousAttribute); + wireframeAttributes.set(geometry, attribute); + } + function getWireframeAttribute(geometry) { + const currentAttribute = wireframeAttributes.get(geometry); + if (currentAttribute) { + const geometryIndex = geometry.index; + if (geometryIndex !== null) { + if (currentAttribute.version < geometryIndex.version) { + updateWireframeAttribute(geometry); + } + } + } else { + updateWireframeAttribute(geometry); + } + return wireframeAttributes.get(geometry); + } + return { + get, + update, + getWireframeAttribute + }; + } + function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) { + const isWebGL2 = capabilities.isWebGL2; + let mode; + function setMode(value) { + mode = value; + } + let type, bytesPerElement; + function setIndex(value) { + type = value.type; + bytesPerElement = value.bytesPerElement; + } + function render(start, count) { + gl.drawElements(mode, count, type, start * bytesPerElement); + info.update(count, mode, 1); + } + function renderInstances(start, count, primcount) { + if (primcount === 0) return; + let extension, methodName; + if (isWebGL2) { + extension = gl; + methodName = "drawElementsInstanced"; + } else { + extension = extensions.get("ANGLE_instanced_arrays"); + methodName = "drawElementsInstancedANGLE"; + if (extension === null) { + console.error("THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."); + return; + } + } + extension[methodName](mode, count, type, start * bytesPerElement, primcount); + info.update(count, mode, primcount); + } + function renderMultiDraw(starts, counts, drawCount) { + if (drawCount === 0) return; + const extension = extensions.get("WEBGL_multi_draw"); + if (extension === null) { + for (let i = 0; i < drawCount; i++) { + this.render(starts[i] / bytesPerElement, counts[i]); + } + } else { + extension.multiDrawElementsWEBGL(mode, counts, 0, type, starts, 0, drawCount); + let elementCount = 0; + for (let i = 0; i < drawCount; i++) { + elementCount += counts[i]; + } + info.update(elementCount, mode, 1); + } + } + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + } + function WebGLInfo(gl) { + const memory = { + geometries: 0, + textures: 0 + }; + const render = { + frame: 0, + calls: 0, + triangles: 0, + points: 0, + lines: 0 + }; + function update(count, mode, instanceCount) { + render.calls++; + switch (mode) { + case gl.TRIANGLES: + render.triangles += instanceCount * (count / 3); + break; + case gl.LINES: + render.lines += instanceCount * (count / 2); + break; + case gl.LINE_STRIP: + render.lines += instanceCount * (count - 1); + break; + case gl.LINE_LOOP: + render.lines += instanceCount * count; + break; + case gl.POINTS: + render.points += instanceCount * count; + break; + default: + console.error("THREE.WebGLInfo: Unknown draw mode:", mode); + break; + } + } + function reset() { + render.calls = 0; + render.triangles = 0; + render.points = 0; + render.lines = 0; + } + return { + memory, + render, + programs: null, + autoReset: true, + reset, + update + }; + } + function numericalSort(a, b) { + return a[0] - b[0]; + } + function absNumericalSort(a, b) { + return Math.abs(b[1]) - Math.abs(a[1]); + } + function WebGLMorphtargets(gl, capabilities, textures) { + const influencesList = {}; + const morphInfluences = new Float32Array(8); + const morphTextures = /* @__PURE__ */ new WeakMap(); + const morph = new Vector4(); + const workInfluences = []; + for (let i = 0; i < 8; i++) { + workInfluences[i] = [i, 0]; + } + function update(object, geometry, program) { + const objectInfluences = object.morphTargetInfluences; + if (capabilities.isWebGL2 === true) { + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== void 0 ? morphAttribute.length : 0; + let entry = morphTextures.get(geometry); + if (entry === void 0 || entry.count !== morphTargetsCount) { + let disposeTexture = function() { + texture.dispose(); + morphTextures.delete(geometry); + geometry.removeEventListener("dispose", disposeTexture); + }; + if (entry !== void 0) entry.texture.dispose(); + const hasMorphPosition = geometry.morphAttributes.position !== void 0; + const hasMorphNormals = geometry.morphAttributes.normal !== void 0; + const hasMorphColors = geometry.morphAttributes.color !== void 0; + const morphTargets = geometry.morphAttributes.position || []; + const morphNormals = geometry.morphAttributes.normal || []; + const morphColors = geometry.morphAttributes.color || []; + let vertexDataCount = 0; + if (hasMorphPosition === true) vertexDataCount = 1; + if (hasMorphNormals === true) vertexDataCount = 2; + if (hasMorphColors === true) vertexDataCount = 3; + let width = geometry.attributes.position.count * vertexDataCount; + let height = 1; + if (width > capabilities.maxTextureSize) { + height = Math.ceil(width / capabilities.maxTextureSize); + width = capabilities.maxTextureSize; + } + const buffer = new Float32Array(width * height * 4 * morphTargetsCount); + const texture = new DataArrayTexture(buffer, width, height, morphTargetsCount); + texture.type = FloatType; + texture.needsUpdate = true; + const vertexDataStride = vertexDataCount * 4; + for (let i = 0; i < morphTargetsCount; i++) { + const morphTarget = morphTargets[i]; + const morphNormal = morphNormals[i]; + const morphColor = morphColors[i]; + const offset = width * height * 4 * i; + for (let j = 0; j < morphTarget.count; j++) { + const stride = j * vertexDataStride; + if (hasMorphPosition === true) { + morph.fromBufferAttribute(morphTarget, j); + buffer[offset + stride + 0] = morph.x; + buffer[offset + stride + 1] = morph.y; + buffer[offset + stride + 2] = morph.z; + buffer[offset + stride + 3] = 0; + } + if (hasMorphNormals === true) { + morph.fromBufferAttribute(morphNormal, j); + buffer[offset + stride + 4] = morph.x; + buffer[offset + stride + 5] = morph.y; + buffer[offset + stride + 6] = morph.z; + buffer[offset + stride + 7] = 0; + } + if (hasMorphColors === true) { + morph.fromBufferAttribute(morphColor, j); + buffer[offset + stride + 8] = morph.x; + buffer[offset + stride + 9] = morph.y; + buffer[offset + stride + 10] = morph.z; + buffer[offset + stride + 11] = morphColor.itemSize === 4 ? morph.w : 1; + } + } + } + entry = { + count: morphTargetsCount, + texture, + size: new Vector2(width, height) + }; + morphTextures.set(geometry, entry); + geometry.addEventListener("dispose", disposeTexture); + } + let morphInfluencesSum = 0; + for (let i = 0; i < objectInfluences.length; i++) { + morphInfluencesSum += objectInfluences[i]; + } + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + program.getUniforms().setValue(gl, "morphTargetBaseInfluence", morphBaseInfluence); + program.getUniforms().setValue(gl, "morphTargetInfluences", objectInfluences); + program.getUniforms().setValue(gl, "morphTargetsTexture", entry.texture, textures); + program.getUniforms().setValue(gl, "morphTargetsTextureSize", entry.size); + } else { + const length = objectInfluences === void 0 ? 0 : objectInfluences.length; + let influences = influencesList[geometry.id]; + if (influences === void 0 || influences.length !== length) { + influences = []; + for (let i = 0; i < length; i++) { + influences[i] = [i, 0]; + } + influencesList[geometry.id] = influences; + } + for (let i = 0; i < length; i++) { + const influence = influences[i]; + influence[0] = i; + influence[1] = objectInfluences[i]; + } + influences.sort(absNumericalSort); + for (let i = 0; i < 8; i++) { + if (i < length && influences[i][1]) { + workInfluences[i][0] = influences[i][0]; + workInfluences[i][1] = influences[i][1]; + } else { + workInfluences[i][0] = Number.MAX_SAFE_INTEGER; + workInfluences[i][1] = 0; + } + } + workInfluences.sort(numericalSort); + const morphTargets = geometry.morphAttributes.position; + const morphNormals = geometry.morphAttributes.normal; + let morphInfluencesSum = 0; + for (let i = 0; i < 8; i++) { + const influence = workInfluences[i]; + const index = influence[0]; + const value = influence[1]; + if (index !== Number.MAX_SAFE_INTEGER && value) { + if (morphTargets && geometry.getAttribute("morphTarget" + i) !== morphTargets[index]) { + geometry.setAttribute("morphTarget" + i, morphTargets[index]); + } + if (morphNormals && geometry.getAttribute("morphNormal" + i) !== morphNormals[index]) { + geometry.setAttribute("morphNormal" + i, morphNormals[index]); + } + morphInfluences[i] = value; + morphInfluencesSum += value; + } else { + if (morphTargets && geometry.hasAttribute("morphTarget" + i) === true) { + geometry.deleteAttribute("morphTarget" + i); + } + if (morphNormals && geometry.hasAttribute("morphNormal" + i) === true) { + geometry.deleteAttribute("morphNormal" + i); + } + morphInfluences[i] = 0; + } + } + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + program.getUniforms().setValue(gl, "morphTargetBaseInfluence", morphBaseInfluence); + program.getUniforms().setValue(gl, "morphTargetInfluences", morphInfluences); + } + } + return { + update + }; + } + function WebGLObjects(gl, geometries, attributes, info) { + let updateMap = /* @__PURE__ */ new WeakMap(); + function update(object) { + const frame = info.render.frame; + const geometry = object.geometry; + const buffergeometry = geometries.get(object, geometry); + if (updateMap.get(buffergeometry) !== frame) { + geometries.update(buffergeometry); + updateMap.set(buffergeometry, frame); + } + if (object.isInstancedMesh) { + if (object.hasEventListener("dispose", onInstancedMeshDispose) === false) { + object.addEventListener("dispose", onInstancedMeshDispose); + } + if (updateMap.get(object) !== frame) { + attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER); + if (object.instanceColor !== null) { + attributes.update(object.instanceColor, gl.ARRAY_BUFFER); + } + updateMap.set(object, frame); + } + } + if (object.isSkinnedMesh) { + const skeleton = object.skeleton; + if (updateMap.get(skeleton) !== frame) { + skeleton.update(); + updateMap.set(skeleton, frame); + } + } + return buffergeometry; + } + function dispose() { + updateMap = /* @__PURE__ */ new WeakMap(); + } + function onInstancedMeshDispose(event) { + const instancedMesh = event.target; + instancedMesh.removeEventListener("dispose", onInstancedMeshDispose); + attributes.remove(instancedMesh.instanceMatrix); + if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor); + } + return { + update, + dispose + }; + } + var DepthTexture = class extends Texture { + constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) { + format = format !== void 0 ? format : DepthFormat; + if (format !== DepthFormat && format !== DepthStencilFormat) { + throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat"); + } + if (type === void 0 && format === DepthFormat) type = UnsignedIntType; + if (type === void 0 && format === DepthStencilFormat) type = UnsignedInt248Type; + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isDepthTexture = true; + this.image = { width, height }; + this.magFilter = magFilter !== void 0 ? magFilter : NearestFilter; + this.minFilter = minFilter !== void 0 ? minFilter : NearestFilter; + this.flipY = false; + this.generateMipmaps = false; + this.compareFunction = null; + } + copy(source) { + super.copy(source); + this.compareFunction = source.compareFunction; + return this; + } + toJSON(meta) { + const data = super.toJSON(meta); + if (this.compareFunction !== null) data.compareFunction = this.compareFunction; + return data; + } + }; + var emptyTexture = /* @__PURE__ */ new Texture(); + var emptyShadowTexture = /* @__PURE__ */ new DepthTexture(1, 1); + emptyShadowTexture.compareFunction = LessEqualCompare; + var emptyArrayTexture = /* @__PURE__ */ new DataArrayTexture(); + var empty3dTexture = /* @__PURE__ */ new Data3DTexture(); + var emptyCubeTexture = /* @__PURE__ */ new CubeTexture(); + var arrayCacheF32 = []; + var arrayCacheI32 = []; + var mat4array = new Float32Array(16); + var mat3array = new Float32Array(9); + var mat2array = new Float32Array(4); + function flatten(array, nBlocks, blockSize) { + const firstElem = array[0]; + if (firstElem <= 0 || firstElem > 0) return array; + const n = nBlocks * blockSize; + let r = arrayCacheF32[n]; + if (r === void 0) { + r = new Float32Array(n); + arrayCacheF32[n] = r; + } + if (nBlocks !== 0) { + firstElem.toArray(r, 0); + for (let i = 1, offset = 0; i !== nBlocks; ++i) { + offset += blockSize; + array[i].toArray(r, offset); + } + } + return r; + } + function arraysEqual(a, b) { + if (a.length !== b.length) return false; + for (let i = 0, l = a.length; i < l; i++) { + if (a[i] !== b[i]) return false; + } + return true; + } + function copyArray(a, b) { + for (let i = 0, l = b.length; i < l; i++) { + a[i] = b[i]; + } + } + function allocTexUnits(textures, n) { + let r = arrayCacheI32[n]; + if (r === void 0) { + r = new Int32Array(n); + arrayCacheI32[n] = r; + } + for (let i = 0; i !== n; ++i) { + r[i] = textures.allocateTextureUnit(); + } + return r; + } + function setValueV1f(gl, v) { + const cache = this.cache; + if (cache[0] === v) return; + gl.uniform1f(this.addr, v); + cache[0] = v; + } + function setValueV2f(gl, v) { + const cache = this.cache; + if (v.x !== void 0) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2f(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual(cache, v)) return; + gl.uniform2fv(this.addr, v); + copyArray(cache, v); + } + } + function setValueV3f(gl, v) { + const cache = this.cache; + if (v.x !== void 0) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3f(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else if (v.r !== void 0) { + if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) { + gl.uniform3f(this.addr, v.r, v.g, v.b); + cache[0] = v.r; + cache[1] = v.g; + cache[2] = v.b; + } + } else { + if (arraysEqual(cache, v)) return; + gl.uniform3fv(this.addr, v); + copyArray(cache, v); + } + } + function setValueV4f(gl, v) { + const cache = this.cache; + if (v.x !== void 0) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4f(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual(cache, v)) return; + gl.uniform4fv(this.addr, v); + copyArray(cache, v); + } + } + function setValueM2(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === void 0) { + if (arraysEqual(cache, v)) return; + gl.uniformMatrix2fv(this.addr, false, v); + copyArray(cache, v); + } else { + if (arraysEqual(cache, elements)) return; + mat2array.set(elements); + gl.uniformMatrix2fv(this.addr, false, mat2array); + copyArray(cache, elements); + } + } + function setValueM3(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === void 0) { + if (arraysEqual(cache, v)) return; + gl.uniformMatrix3fv(this.addr, false, v); + copyArray(cache, v); + } else { + if (arraysEqual(cache, elements)) return; + mat3array.set(elements); + gl.uniformMatrix3fv(this.addr, false, mat3array); + copyArray(cache, elements); + } + } + function setValueM4(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === void 0) { + if (arraysEqual(cache, v)) return; + gl.uniformMatrix4fv(this.addr, false, v); + copyArray(cache, v); + } else { + if (arraysEqual(cache, elements)) return; + mat4array.set(elements); + gl.uniformMatrix4fv(this.addr, false, mat4array); + copyArray(cache, elements); + } + } + function setValueV1i(gl, v) { + const cache = this.cache; + if (cache[0] === v) return; + gl.uniform1i(this.addr, v); + cache[0] = v; + } + function setValueV2i(gl, v) { + const cache = this.cache; + if (v.x !== void 0) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2i(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual(cache, v)) return; + gl.uniform2iv(this.addr, v); + copyArray(cache, v); + } + } + function setValueV3i(gl, v) { + const cache = this.cache; + if (v.x !== void 0) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3i(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else { + if (arraysEqual(cache, v)) return; + gl.uniform3iv(this.addr, v); + copyArray(cache, v); + } + } + function setValueV4i(gl, v) { + const cache = this.cache; + if (v.x !== void 0) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4i(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual(cache, v)) return; + gl.uniform4iv(this.addr, v); + copyArray(cache, v); + } + } + function setValueV1ui(gl, v) { + const cache = this.cache; + if (cache[0] === v) return; + gl.uniform1ui(this.addr, v); + cache[0] = v; + } + function setValueV2ui(gl, v) { + const cache = this.cache; + if (v.x !== void 0) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2ui(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual(cache, v)) return; + gl.uniform2uiv(this.addr, v); + copyArray(cache, v); + } + } + function setValueV3ui(gl, v) { + const cache = this.cache; + if (v.x !== void 0) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3ui(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else { + if (arraysEqual(cache, v)) return; + gl.uniform3uiv(this.addr, v); + copyArray(cache, v); + } + } + function setValueV4ui(gl, v) { + const cache = this.cache; + if (v.x !== void 0) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4ui(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual(cache, v)) return; + gl.uniform4uiv(this.addr, v); + copyArray(cache, v); + } + } + function setValueT1(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + const emptyTexture2D = this.type === gl.SAMPLER_2D_SHADOW ? emptyShadowTexture : emptyTexture; + textures.setTexture2D(v || emptyTexture2D, unit); + } + function setValueT3D1(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTexture3D(v || empty3dTexture, unit); + } + function setValueT6(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTextureCube(v || emptyCubeTexture, unit); + } + function setValueT2DArray1(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTexture2DArray(v || emptyArrayTexture, unit); + } + function getSingularSetter(type) { + switch (type) { + case 5126: + return setValueV1f; + // FLOAT + case 35664: + return setValueV2f; + // _VEC2 + case 35665: + return setValueV3f; + // _VEC3 + case 35666: + return setValueV4f; + // _VEC4 + case 35674: + return setValueM2; + // _MAT2 + case 35675: + return setValueM3; + // _MAT3 + case 35676: + return setValueM4; + // _MAT4 + case 5124: + case 35670: + return setValueV1i; + // INT, BOOL + case 35667: + case 35671: + return setValueV2i; + // _VEC2 + case 35668: + case 35672: + return setValueV3i; + // _VEC3 + case 35669: + case 35673: + return setValueV4i; + // _VEC4 + case 5125: + return setValueV1ui; + // UINT + case 36294: + return setValueV2ui; + // _VEC2 + case 36295: + return setValueV3ui; + // _VEC3 + case 36296: + return setValueV4ui; + // _VEC4 + case 35678: + // SAMPLER_2D + case 36198: + // SAMPLER_EXTERNAL_OES + case 36298: + // INT_SAMPLER_2D + case 36306: + // UNSIGNED_INT_SAMPLER_2D + case 35682: + return setValueT1; + case 35679: + // SAMPLER_3D + case 36299: + // INT_SAMPLER_3D + case 36307: + return setValueT3D1; + case 35680: + // SAMPLER_CUBE + case 36300: + // INT_SAMPLER_CUBE + case 36308: + // UNSIGNED_INT_SAMPLER_CUBE + case 36293: + return setValueT6; + case 36289: + // SAMPLER_2D_ARRAY + case 36303: + // INT_SAMPLER_2D_ARRAY + case 36311: + // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 36292: + return setValueT2DArray1; + } + } + function setValueV1fArray(gl, v) { + gl.uniform1fv(this.addr, v); + } + function setValueV2fArray(gl, v) { + const data = flatten(v, this.size, 2); + gl.uniform2fv(this.addr, data); + } + function setValueV3fArray(gl, v) { + const data = flatten(v, this.size, 3); + gl.uniform3fv(this.addr, data); + } + function setValueV4fArray(gl, v) { + const data = flatten(v, this.size, 4); + gl.uniform4fv(this.addr, data); + } + function setValueM2Array(gl, v) { + const data = flatten(v, this.size, 4); + gl.uniformMatrix2fv(this.addr, false, data); + } + function setValueM3Array(gl, v) { + const data = flatten(v, this.size, 9); + gl.uniformMatrix3fv(this.addr, false, data); + } + function setValueM4Array(gl, v) { + const data = flatten(v, this.size, 16); + gl.uniformMatrix4fv(this.addr, false, data); + } + function setValueV1iArray(gl, v) { + gl.uniform1iv(this.addr, v); + } + function setValueV2iArray(gl, v) { + gl.uniform2iv(this.addr, v); + } + function setValueV3iArray(gl, v) { + gl.uniform3iv(this.addr, v); + } + function setValueV4iArray(gl, v) { + gl.uniform4iv(this.addr, v); + } + function setValueV1uiArray(gl, v) { + gl.uniform1uiv(this.addr, v); + } + function setValueV2uiArray(gl, v) { + gl.uniform2uiv(this.addr, v); + } + function setValueV3uiArray(gl, v) { + gl.uniform3uiv(this.addr, v); + } + function setValueV4uiArray(gl, v) { + gl.uniform4uiv(this.addr, v); + } + function setValueT1Array(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits(textures, n); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i = 0; i !== n; ++i) { + textures.setTexture2D(v[i] || emptyTexture, units[i]); + } + } + function setValueT3DArray(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits(textures, n); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i = 0; i !== n; ++i) { + textures.setTexture3D(v[i] || empty3dTexture, units[i]); + } + } + function setValueT6Array(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits(textures, n); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i = 0; i !== n; ++i) { + textures.setTextureCube(v[i] || emptyCubeTexture, units[i]); + } + } + function setValueT2DArrayArray(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits(textures, n); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i = 0; i !== n; ++i) { + textures.setTexture2DArray(v[i] || emptyArrayTexture, units[i]); + } + } + function getPureArraySetter(type) { + switch (type) { + case 5126: + return setValueV1fArray; + // FLOAT + case 35664: + return setValueV2fArray; + // _VEC2 + case 35665: + return setValueV3fArray; + // _VEC3 + case 35666: + return setValueV4fArray; + // _VEC4 + case 35674: + return setValueM2Array; + // _MAT2 + case 35675: + return setValueM3Array; + // _MAT3 + case 35676: + return setValueM4Array; + // _MAT4 + case 5124: + case 35670: + return setValueV1iArray; + // INT, BOOL + case 35667: + case 35671: + return setValueV2iArray; + // _VEC2 + case 35668: + case 35672: + return setValueV3iArray; + // _VEC3 + case 35669: + case 35673: + return setValueV4iArray; + // _VEC4 + case 5125: + return setValueV1uiArray; + // UINT + case 36294: + return setValueV2uiArray; + // _VEC2 + case 36295: + return setValueV3uiArray; + // _VEC3 + case 36296: + return setValueV4uiArray; + // _VEC4 + case 35678: + // SAMPLER_2D + case 36198: + // SAMPLER_EXTERNAL_OES + case 36298: + // INT_SAMPLER_2D + case 36306: + // UNSIGNED_INT_SAMPLER_2D + case 35682: + return setValueT1Array; + case 35679: + // SAMPLER_3D + case 36299: + // INT_SAMPLER_3D + case 36307: + return setValueT3DArray; + case 35680: + // SAMPLER_CUBE + case 36300: + // INT_SAMPLER_CUBE + case 36308: + // UNSIGNED_INT_SAMPLER_CUBE + case 36293: + return setValueT6Array; + case 36289: + // SAMPLER_2D_ARRAY + case 36303: + // INT_SAMPLER_2D_ARRAY + case 36311: + // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 36292: + return setValueT2DArrayArray; + } + } + var SingleUniform = class { + constructor(id, activeInfo, addr) { + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.setValue = getSingularSetter(activeInfo.type); + } + }; + var PureArrayUniform = class { + constructor(id, activeInfo, addr) { + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.size = activeInfo.size; + this.setValue = getPureArraySetter(activeInfo.type); + } + }; + var StructuredUniform = class { + constructor(id) { + this.id = id; + this.seq = []; + this.map = {}; + } + setValue(gl, value, textures) { + const seq = this.seq; + for (let i = 0, n = seq.length; i !== n; ++i) { + const u = seq[i]; + u.setValue(gl, value[u.id], textures); + } + } + }; + var RePathPart = /(\w+)(\])?(\[|\.)?/g; + function addUniform(container, uniformObject) { + container.seq.push(uniformObject); + container.map[uniformObject.id] = uniformObject; + } + function parseUniform(activeInfo, addr, container) { + const path = activeInfo.name, pathLength = path.length; + RePathPart.lastIndex = 0; + while (true) { + const match = RePathPart.exec(path), matchEnd = RePathPart.lastIndex; + let id = match[1]; + const idIsIndex = match[2] === "]", subscript = match[3]; + if (idIsIndex) id = id | 0; + if (subscript === void 0 || subscript === "[" && matchEnd + 2 === pathLength) { + addUniform(container, subscript === void 0 ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr)); + break; + } else { + const map = container.map; + let next = map[id]; + if (next === void 0) { + next = new StructuredUniform(id); + addUniform(container, next); + } + container = next; + } + } + } + var WebGLUniforms = class { + constructor(gl, program) { + this.seq = []; + this.map = {}; + const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + for (let i = 0; i < n; ++i) { + const info = gl.getActiveUniform(program, i), addr = gl.getUniformLocation(program, info.name); + parseUniform(info, addr, this); + } + } + setValue(gl, name, value, textures) { + const u = this.map[name]; + if (u !== void 0) u.setValue(gl, value, textures); + } + setOptional(gl, object, name) { + const v = object[name]; + if (v !== void 0) this.setValue(gl, name, v); + } + static upload(gl, seq, values, textures) { + for (let i = 0, n = seq.length; i !== n; ++i) { + const u = seq[i], v = values[u.id]; + if (v.needsUpdate !== false) { + u.setValue(gl, v.value, textures); + } + } + } + static seqWithValue(seq, values) { + const r = []; + for (let i = 0, n = seq.length; i !== n; ++i) { + const u = seq[i]; + if (u.id in values) r.push(u); + } + return r; + } + }; + function WebGLShader(gl, type, string) { + const shader = gl.createShader(type); + gl.shaderSource(shader, string); + gl.compileShader(shader); + return shader; + } + var COMPLETION_STATUS_KHR = 37297; + var programIdCount = 0; + function handleSource(string, errorLine) { + const lines = string.split("\n"); + const lines2 = []; + const from = Math.max(errorLine - 6, 0); + const to = Math.min(errorLine + 6, lines.length); + for (let i = from; i < to; i++) { + const line = i + 1; + lines2.push(`${line === errorLine ? ">" : " "} ${line}: ${lines[i]}`); + } + return lines2.join("\n"); + } + function getEncodingComponents(colorSpace) { + const workingPrimaries = ColorManagement.getPrimaries(ColorManagement.workingColorSpace); + const encodingPrimaries = ColorManagement.getPrimaries(colorSpace); + let gamutMapping; + if (workingPrimaries === encodingPrimaries) { + gamutMapping = ""; + } else if (workingPrimaries === P3Primaries && encodingPrimaries === Rec709Primaries) { + gamutMapping = "LinearDisplayP3ToLinearSRGB"; + } else if (workingPrimaries === Rec709Primaries && encodingPrimaries === P3Primaries) { + gamutMapping = "LinearSRGBToLinearDisplayP3"; + } + switch (colorSpace) { + case LinearSRGBColorSpace: + case LinearDisplayP3ColorSpace: + return [gamutMapping, "LinearTransferOETF"]; + case SRGBColorSpace: + case DisplayP3ColorSpace: + return [gamutMapping, "sRGBTransferOETF"]; + default: + console.warn("THREE.WebGLProgram: Unsupported color space:", colorSpace); + return [gamutMapping, "LinearTransferOETF"]; + } + } + function getShaderErrors(gl, shader, type) { + const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS); + const errors = gl.getShaderInfoLog(shader).trim(); + if (status && errors === "") return ""; + const errorMatches = /ERROR: 0:(\d+)/.exec(errors); + if (errorMatches) { + const errorLine = parseInt(errorMatches[1]); + return type.toUpperCase() + "\n\n" + errors + "\n\n" + handleSource(gl.getShaderSource(shader), errorLine); + } else { + return errors; + } + } + function getTexelEncodingFunction(functionName, colorSpace) { + const components = getEncodingComponents(colorSpace); + return `vec4 ${functionName}( vec4 value ) { return ${components[0]}( ${components[1]}( value ) ); }`; + } + function getToneMappingFunction(functionName, toneMapping) { + let toneMappingName; + switch (toneMapping) { + case LinearToneMapping: + toneMappingName = "Linear"; + break; + case ReinhardToneMapping: + toneMappingName = "Reinhard"; + break; + case CineonToneMapping: + toneMappingName = "OptimizedCineon"; + break; + case ACESFilmicToneMapping: + toneMappingName = "ACESFilmic"; + break; + case AgXToneMapping: + toneMappingName = "AgX"; + break; + case CustomToneMapping: + toneMappingName = "Custom"; + break; + default: + console.warn("THREE.WebGLProgram: Unsupported toneMapping:", toneMapping); + toneMappingName = "Linear"; + } + return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }"; + } + function generateExtensions(parameters) { + const chunks = [ + parameters.extensionDerivatives || !!parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.normalMapTangentSpace || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === "physical" ? "#extension GL_OES_standard_derivatives : enable" : "", + (parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? "#extension GL_EXT_frag_depth : enable" : "", + parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? "#extension GL_EXT_draw_buffers : require" : "", + (parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission) && parameters.rendererExtensionShaderTextureLod ? "#extension GL_EXT_shader_texture_lod : enable" : "" + ]; + return chunks.filter(filterEmptyLine).join("\n"); + } + function generateVertexExtensions(parameters) { + const chunks = [ + parameters.extensionClipCullDistance ? "#extension GL_ANGLE_clip_cull_distance : require" : "" + ]; + return chunks.filter(filterEmptyLine).join("\n"); + } + function generateDefines(defines) { + const chunks = []; + for (const name in defines) { + const value = defines[name]; + if (value === false) continue; + chunks.push("#define " + name + " " + value); + } + return chunks.join("\n"); + } + function fetchAttributeLocations(gl, program) { + const attributes = {}; + const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + for (let i = 0; i < n; i++) { + const info = gl.getActiveAttrib(program, i); + const name = info.name; + let locationSize = 1; + if (info.type === gl.FLOAT_MAT2) locationSize = 2; + if (info.type === gl.FLOAT_MAT3) locationSize = 3; + if (info.type === gl.FLOAT_MAT4) locationSize = 4; + attributes[name] = { + type: info.type, + location: gl.getAttribLocation(program, name), + locationSize + }; + } + return attributes; + } + function filterEmptyLine(string) { + return string !== ""; + } + function replaceLightNums(string, parameters) { + const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps; + return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows); + } + function replaceClippingPlaneNums(string, parameters) { + return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection); + } + var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm; + function resolveIncludes(string) { + return string.replace(includePattern, includeReplacer); + } + var shaderChunkMap = /* @__PURE__ */ new Map([ + ["encodings_fragment", "colorspace_fragment"], + // @deprecated, r154 + ["encodings_pars_fragment", "colorspace_pars_fragment"], + // @deprecated, r154 + ["output_fragment", "opaque_fragment"] + // @deprecated, r154 + ]); + function includeReplacer(match, include) { + let string = ShaderChunk[include]; + if (string === void 0) { + const newInclude = shaderChunkMap.get(include); + if (newInclude !== void 0) { + string = ShaderChunk[newInclude]; + console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude); + } else { + throw new Error("Can not resolve #include <" + include + ">"); + } + } + return resolveIncludes(string); + } + var unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; + function unrollLoops(string) { + return string.replace(unrollLoopPattern, loopReplacer); + } + function loopReplacer(match, start, end, snippet) { + let string = ""; + for (let i = parseInt(start); i < parseInt(end); i++) { + string += snippet.replace(/\[\s*i\s*\]/g, "[ " + i + " ]").replace(/UNROLLED_LOOP_INDEX/g, i); + } + return string; + } + function generatePrecision(parameters) { + let precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;"; + if (parameters.precision === "highp") { + precisionstring += "\n#define HIGH_PRECISION"; + } else if (parameters.precision === "mediump") { + precisionstring += "\n#define MEDIUM_PRECISION"; + } else if (parameters.precision === "lowp") { + precisionstring += "\n#define LOW_PRECISION"; + } + return precisionstring; + } + function generateShadowMapTypeDefine(parameters) { + let shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC"; + if (parameters.shadowMapType === PCFShadowMap) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF"; + } else if (parameters.shadowMapType === PCFSoftShadowMap) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT"; + } else if (parameters.shadowMapType === VSMShadowMap) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_VSM"; + } + return shadowMapTypeDefine; + } + function generateEnvMapTypeDefine(parameters) { + let envMapTypeDefine = "ENVMAP_TYPE_CUBE"; + if (parameters.envMap) { + switch (parameters.envMapMode) { + case CubeReflectionMapping: + case CubeRefractionMapping: + envMapTypeDefine = "ENVMAP_TYPE_CUBE"; + break; + case CubeUVReflectionMapping: + envMapTypeDefine = "ENVMAP_TYPE_CUBE_UV"; + break; + } + } + return envMapTypeDefine; + } + function generateEnvMapModeDefine(parameters) { + let envMapModeDefine = "ENVMAP_MODE_REFLECTION"; + if (parameters.envMap) { + switch (parameters.envMapMode) { + case CubeRefractionMapping: + envMapModeDefine = "ENVMAP_MODE_REFRACTION"; + break; + } + } + return envMapModeDefine; + } + function generateEnvMapBlendingDefine(parameters) { + let envMapBlendingDefine = "ENVMAP_BLENDING_NONE"; + if (parameters.envMap) { + switch (parameters.combine) { + case MultiplyOperation: + envMapBlendingDefine = "ENVMAP_BLENDING_MULTIPLY"; + break; + case MixOperation: + envMapBlendingDefine = "ENVMAP_BLENDING_MIX"; + break; + case AddOperation: + envMapBlendingDefine = "ENVMAP_BLENDING_ADD"; + break; + } + } + return envMapBlendingDefine; + } + function generateCubeUVSize(parameters) { + const imageHeight = parameters.envMapCubeUVHeight; + if (imageHeight === null) return null; + const maxMip = Math.log2(imageHeight) - 2; + const texelHeight = 1 / imageHeight; + const texelWidth = 1 / (3 * Math.max(Math.pow(2, maxMip), 7 * 16)); + return { texelWidth, texelHeight, maxMip }; + } + function WebGLProgram(renderer, cacheKey, parameters, bindingStates) { + const gl = renderer.getContext(); + const defines = parameters.defines; + let vertexShader = parameters.vertexShader; + let fragmentShader = parameters.fragmentShader; + const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters); + const envMapTypeDefine = generateEnvMapTypeDefine(parameters); + const envMapModeDefine = generateEnvMapModeDefine(parameters); + const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters); + const envMapCubeUVSize = generateCubeUVSize(parameters); + const customExtensions = parameters.isWebGL2 ? "" : generateExtensions(parameters); + const customVertexExtensions = generateVertexExtensions(parameters); + const customDefines = generateDefines(defines); + const program = gl.createProgram(); + let prefixVertex, prefixFragment; + let versionString = parameters.glslVersion ? "#version " + parameters.glslVersion + "\n" : ""; + if (parameters.isRawShaderMaterial) { + prefixVertex = [ + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines + ].filter(filterEmptyLine).join("\n"); + if (prefixVertex.length > 0) { + prefixVertex += "\n"; + } + prefixFragment = [ + customExtensions, + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines + ].filter(filterEmptyLine).join("\n"); + if (prefixFragment.length > 0) { + prefixFragment += "\n"; + } + } else { + prefixVertex = [ + generatePrecision(parameters), + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines, + parameters.extensionClipCullDistance ? "#define USE_CLIP_DISTANCE" : "", + parameters.batching ? "#define USE_BATCHING" : "", + parameters.instancing ? "#define USE_INSTANCING" : "", + parameters.instancingColor ? "#define USE_INSTANCING_COLOR" : "", + parameters.useFog && parameters.fog ? "#define USE_FOG" : "", + parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "", + parameters.map ? "#define USE_MAP" : "", + parameters.envMap ? "#define USE_ENVMAP" : "", + parameters.envMap ? "#define " + envMapModeDefine : "", + parameters.lightMap ? "#define USE_LIGHTMAP" : "", + parameters.aoMap ? "#define USE_AOMAP" : "", + parameters.bumpMap ? "#define USE_BUMPMAP" : "", + parameters.normalMap ? "#define USE_NORMALMAP" : "", + parameters.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", + parameters.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", + parameters.displacementMap ? "#define USE_DISPLACEMENTMAP" : "", + parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "", + parameters.anisotropy ? "#define USE_ANISOTROPY" : "", + parameters.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", + parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", + parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", + parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", + parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", + parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", + parameters.specularMap ? "#define USE_SPECULARMAP" : "", + parameters.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", + parameters.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", + parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", + parameters.metalnessMap ? "#define USE_METALNESSMAP" : "", + parameters.alphaMap ? "#define USE_ALPHAMAP" : "", + parameters.alphaHash ? "#define USE_ALPHAHASH" : "", + parameters.transmission ? "#define USE_TRANSMISSION" : "", + parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", + parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "", + parameters.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", + parameters.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", + // + parameters.mapUv ? "#define MAP_UV " + parameters.mapUv : "", + parameters.alphaMapUv ? "#define ALPHAMAP_UV " + parameters.alphaMapUv : "", + parameters.lightMapUv ? "#define LIGHTMAP_UV " + parameters.lightMapUv : "", + parameters.aoMapUv ? "#define AOMAP_UV " + parameters.aoMapUv : "", + parameters.emissiveMapUv ? "#define EMISSIVEMAP_UV " + parameters.emissiveMapUv : "", + parameters.bumpMapUv ? "#define BUMPMAP_UV " + parameters.bumpMapUv : "", + parameters.normalMapUv ? "#define NORMALMAP_UV " + parameters.normalMapUv : "", + parameters.displacementMapUv ? "#define DISPLACEMENTMAP_UV " + parameters.displacementMapUv : "", + parameters.metalnessMapUv ? "#define METALNESSMAP_UV " + parameters.metalnessMapUv : "", + parameters.roughnessMapUv ? "#define ROUGHNESSMAP_UV " + parameters.roughnessMapUv : "", + parameters.anisotropyMapUv ? "#define ANISOTROPYMAP_UV " + parameters.anisotropyMapUv : "", + parameters.clearcoatMapUv ? "#define CLEARCOATMAP_UV " + parameters.clearcoatMapUv : "", + parameters.clearcoatNormalMapUv ? "#define CLEARCOAT_NORMALMAP_UV " + parameters.clearcoatNormalMapUv : "", + parameters.clearcoatRoughnessMapUv ? "#define CLEARCOAT_ROUGHNESSMAP_UV " + parameters.clearcoatRoughnessMapUv : "", + parameters.iridescenceMapUv ? "#define IRIDESCENCEMAP_UV " + parameters.iridescenceMapUv : "", + parameters.iridescenceThicknessMapUv ? "#define IRIDESCENCE_THICKNESSMAP_UV " + parameters.iridescenceThicknessMapUv : "", + parameters.sheenColorMapUv ? "#define SHEEN_COLORMAP_UV " + parameters.sheenColorMapUv : "", + parameters.sheenRoughnessMapUv ? "#define SHEEN_ROUGHNESSMAP_UV " + parameters.sheenRoughnessMapUv : "", + parameters.specularMapUv ? "#define SPECULARMAP_UV " + parameters.specularMapUv : "", + parameters.specularColorMapUv ? "#define SPECULAR_COLORMAP_UV " + parameters.specularColorMapUv : "", + parameters.specularIntensityMapUv ? "#define SPECULAR_INTENSITYMAP_UV " + parameters.specularIntensityMapUv : "", + parameters.transmissionMapUv ? "#define TRANSMISSIONMAP_UV " + parameters.transmissionMapUv : "", + parameters.thicknessMapUv ? "#define THICKNESSMAP_UV " + parameters.thicknessMapUv : "", + // + parameters.vertexTangents && parameters.flatShading === false ? "#define USE_TANGENT" : "", + parameters.vertexColors ? "#define USE_COLOR" : "", + parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", + parameters.vertexUv1s ? "#define USE_UV1" : "", + parameters.vertexUv2s ? "#define USE_UV2" : "", + parameters.vertexUv3s ? "#define USE_UV3" : "", + parameters.pointsUvs ? "#define USE_POINTS_UV" : "", + parameters.flatShading ? "#define FLAT_SHADED" : "", + parameters.skinning ? "#define USE_SKINNING" : "", + parameters.morphTargets ? "#define USE_MORPHTARGETS" : "", + parameters.morphNormals && parameters.flatShading === false ? "#define USE_MORPHNORMALS" : "", + parameters.morphColors && parameters.isWebGL2 ? "#define USE_MORPHCOLORS" : "", + parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? "#define MORPHTARGETS_TEXTURE" : "", + parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? "#define MORPHTARGETS_TEXTURE_STRIDE " + parameters.morphTextureStride : "", + parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? "#define MORPHTARGETS_COUNT " + parameters.morphTargetsCount : "", + parameters.doubleSided ? "#define DOUBLE_SIDED" : "", + parameters.flipSided ? "#define FLIP_SIDED" : "", + parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", + parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "", + parameters.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", + parameters.useLegacyLights ? "#define LEGACY_LIGHTS" : "", + parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "", + parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "", + "uniform mat4 modelMatrix;", + "uniform mat4 modelViewMatrix;", + "uniform mat4 projectionMatrix;", + "uniform mat4 viewMatrix;", + "uniform mat3 normalMatrix;", + "uniform vec3 cameraPosition;", + "uniform bool isOrthographic;", + "#ifdef USE_INSTANCING", + " attribute mat4 instanceMatrix;", + "#endif", + "#ifdef USE_INSTANCING_COLOR", + " attribute vec3 instanceColor;", + "#endif", + "attribute vec3 position;", + "attribute vec3 normal;", + "attribute vec2 uv;", + "#ifdef USE_UV1", + " attribute vec2 uv1;", + "#endif", + "#ifdef USE_UV2", + " attribute vec2 uv2;", + "#endif", + "#ifdef USE_UV3", + " attribute vec2 uv3;", + "#endif", + "#ifdef USE_TANGENT", + " attribute vec4 tangent;", + "#endif", + "#if defined( USE_COLOR_ALPHA )", + " attribute vec4 color;", + "#elif defined( USE_COLOR )", + " attribute vec3 color;", + "#endif", + "#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )", + " attribute vec3 morphTarget0;", + " attribute vec3 morphTarget1;", + " attribute vec3 morphTarget2;", + " attribute vec3 morphTarget3;", + " #ifdef USE_MORPHNORMALS", + " attribute vec3 morphNormal0;", + " attribute vec3 morphNormal1;", + " attribute vec3 morphNormal2;", + " attribute vec3 morphNormal3;", + " #else", + " attribute vec3 morphTarget4;", + " attribute vec3 morphTarget5;", + " attribute vec3 morphTarget6;", + " attribute vec3 morphTarget7;", + " #endif", + "#endif", + "#ifdef USE_SKINNING", + " attribute vec4 skinIndex;", + " attribute vec4 skinWeight;", + "#endif", + "\n" + ].filter(filterEmptyLine).join("\n"); + prefixFragment = [ + customExtensions, + generatePrecision(parameters), + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines, + parameters.useFog && parameters.fog ? "#define USE_FOG" : "", + parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "", + parameters.map ? "#define USE_MAP" : "", + parameters.matcap ? "#define USE_MATCAP" : "", + parameters.envMap ? "#define USE_ENVMAP" : "", + parameters.envMap ? "#define " + envMapTypeDefine : "", + parameters.envMap ? "#define " + envMapModeDefine : "", + parameters.envMap ? "#define " + envMapBlendingDefine : "", + envMapCubeUVSize ? "#define CUBEUV_TEXEL_WIDTH " + envMapCubeUVSize.texelWidth : "", + envMapCubeUVSize ? "#define CUBEUV_TEXEL_HEIGHT " + envMapCubeUVSize.texelHeight : "", + envMapCubeUVSize ? "#define CUBEUV_MAX_MIP " + envMapCubeUVSize.maxMip + ".0" : "", + parameters.lightMap ? "#define USE_LIGHTMAP" : "", + parameters.aoMap ? "#define USE_AOMAP" : "", + parameters.bumpMap ? "#define USE_BUMPMAP" : "", + parameters.normalMap ? "#define USE_NORMALMAP" : "", + parameters.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", + parameters.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", + parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "", + parameters.anisotropy ? "#define USE_ANISOTROPY" : "", + parameters.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", + parameters.clearcoat ? "#define USE_CLEARCOAT" : "", + parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", + parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", + parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", + parameters.iridescence ? "#define USE_IRIDESCENCE" : "", + parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", + parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", + parameters.specularMap ? "#define USE_SPECULARMAP" : "", + parameters.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", + parameters.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", + parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", + parameters.metalnessMap ? "#define USE_METALNESSMAP" : "", + parameters.alphaMap ? "#define USE_ALPHAMAP" : "", + parameters.alphaTest ? "#define USE_ALPHATEST" : "", + parameters.alphaHash ? "#define USE_ALPHAHASH" : "", + parameters.sheen ? "#define USE_SHEEN" : "", + parameters.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", + parameters.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", + parameters.transmission ? "#define USE_TRANSMISSION" : "", + parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", + parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "", + parameters.vertexTangents && parameters.flatShading === false ? "#define USE_TANGENT" : "", + parameters.vertexColors || parameters.instancingColor ? "#define USE_COLOR" : "", + parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", + parameters.vertexUv1s ? "#define USE_UV1" : "", + parameters.vertexUv2s ? "#define USE_UV2" : "", + parameters.vertexUv3s ? "#define USE_UV3" : "", + parameters.pointsUvs ? "#define USE_POINTS_UV" : "", + parameters.gradientMap ? "#define USE_GRADIENTMAP" : "", + parameters.flatShading ? "#define FLAT_SHADED" : "", + parameters.doubleSided ? "#define DOUBLE_SIDED" : "", + parameters.flipSided ? "#define FLIP_SIDED" : "", + parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", + parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : "", + parameters.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", + parameters.useLegacyLights ? "#define LEGACY_LIGHTS" : "", + parameters.decodeVideoTexture ? "#define DECODE_VIDEO_TEXTURE" : "", + parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "", + parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "", + "uniform mat4 viewMatrix;", + "uniform vec3 cameraPosition;", + "uniform bool isOrthographic;", + parameters.toneMapping !== NoToneMapping ? "#define TONE_MAPPING" : "", + parameters.toneMapping !== NoToneMapping ? ShaderChunk["tonemapping_pars_fragment"] : "", + // this code is required here because it is used by the toneMapping() function defined below + parameters.toneMapping !== NoToneMapping ? getToneMappingFunction("toneMapping", parameters.toneMapping) : "", + parameters.dithering ? "#define DITHERING" : "", + parameters.opaque ? "#define OPAQUE" : "", + ShaderChunk["colorspace_pars_fragment"], + // this code is required here because it is used by the various encoding/decoding function defined below + getTexelEncodingFunction("linearToOutputTexel", parameters.outputColorSpace), + parameters.useDepthPacking ? "#define DEPTH_PACKING " + parameters.depthPacking : "", + "\n" + ].filter(filterEmptyLine).join("\n"); + } + vertexShader = resolveIncludes(vertexShader); + vertexShader = replaceLightNums(vertexShader, parameters); + vertexShader = replaceClippingPlaneNums(vertexShader, parameters); + fragmentShader = resolveIncludes(fragmentShader); + fragmentShader = replaceLightNums(fragmentShader, parameters); + fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters); + vertexShader = unrollLoops(vertexShader); + fragmentShader = unrollLoops(fragmentShader); + if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) { + versionString = "#version 300 es\n"; + prefixVertex = [ + customVertexExtensions, + "precision mediump sampler2DArray;", + "#define attribute in", + "#define varying out", + "#define texture2D texture" + ].join("\n") + "\n" + prefixVertex; + prefixFragment = [ + "precision mediump sampler2DArray;", + "#define varying in", + parameters.glslVersion === GLSL3 ? "" : "layout(location = 0) out highp vec4 pc_fragColor;", + parameters.glslVersion === GLSL3 ? "" : "#define gl_FragColor pc_fragColor", + "#define gl_FragDepthEXT gl_FragDepth", + "#define texture2D texture", + "#define textureCube texture", + "#define texture2DProj textureProj", + "#define texture2DLodEXT textureLod", + "#define texture2DProjLodEXT textureProjLod", + "#define textureCubeLodEXT textureLod", + "#define texture2DGradEXT textureGrad", + "#define texture2DProjGradEXT textureProjGrad", + "#define textureCubeGradEXT textureGrad" + ].join("\n") + "\n" + prefixFragment; + } + const vertexGlsl = versionString + prefixVertex + vertexShader; + const fragmentGlsl = versionString + prefixFragment + fragmentShader; + const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl); + const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl); + gl.attachShader(program, glVertexShader); + gl.attachShader(program, glFragmentShader); + if (parameters.index0AttributeName !== void 0) { + gl.bindAttribLocation(program, 0, parameters.index0AttributeName); + } else if (parameters.morphTargets === true) { + gl.bindAttribLocation(program, 0, "position"); + } + gl.linkProgram(program); + function onFirstUse(self2) { + if (renderer.debug.checkShaderErrors) { + const programLog = gl.getProgramInfoLog(program).trim(); + const vertexLog = gl.getShaderInfoLog(glVertexShader).trim(); + const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim(); + let runnable = true; + let haveDiagnostics = true; + if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) { + runnable = false; + if (typeof renderer.debug.onShaderError === "function") { + renderer.debug.onShaderError(gl, program, glVertexShader, glFragmentShader); + } else { + const vertexErrors = getShaderErrors(gl, glVertexShader, "vertex"); + const fragmentErrors = getShaderErrors(gl, glFragmentShader, "fragment"); + console.error( + "THREE.WebGLProgram: Shader Error " + gl.getError() + " - VALIDATE_STATUS " + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + "\n\nProgram Info Log: " + programLog + "\n" + vertexErrors + "\n" + fragmentErrors + ); + } + } else if (programLog !== "") { + console.warn("THREE.WebGLProgram: Program Info Log:", programLog); + } else if (vertexLog === "" || fragmentLog === "") { + haveDiagnostics = false; + } + if (haveDiagnostics) { + self2.diagnostics = { + runnable, + programLog, + vertexShader: { + log: vertexLog, + prefix: prefixVertex + }, + fragmentShader: { + log: fragmentLog, + prefix: prefixFragment + } + }; + } + } + gl.deleteShader(glVertexShader); + gl.deleteShader(glFragmentShader); + cachedUniforms = new WebGLUniforms(gl, program); + cachedAttributes = fetchAttributeLocations(gl, program); + } + let cachedUniforms; + this.getUniforms = function() { + if (cachedUniforms === void 0) { + onFirstUse(this); + } + return cachedUniforms; + }; + let cachedAttributes; + this.getAttributes = function() { + if (cachedAttributes === void 0) { + onFirstUse(this); + } + return cachedAttributes; + }; + let programReady = parameters.rendererExtensionParallelShaderCompile === false; + this.isReady = function() { + if (programReady === false) { + programReady = gl.getProgramParameter(program, COMPLETION_STATUS_KHR); + } + return programReady; + }; + this.destroy = function() { + bindingStates.releaseStatesOfProgram(this); + gl.deleteProgram(program); + this.program = void 0; + }; + this.type = parameters.shaderType; + this.name = parameters.shaderName; + this.id = programIdCount++; + this.cacheKey = cacheKey; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; + return this; + } + var _id$1 = 0; + var WebGLShaderCache = class { + constructor() { + this.shaderCache = /* @__PURE__ */ new Map(); + this.materialCache = /* @__PURE__ */ new Map(); + } + update(material) { + const vertexShader = material.vertexShader; + const fragmentShader = material.fragmentShader; + const vertexShaderStage = this._getShaderStage(vertexShader); + const fragmentShaderStage = this._getShaderStage(fragmentShader); + const materialShaders = this._getShaderCacheForMaterial(material); + if (materialShaders.has(vertexShaderStage) === false) { + materialShaders.add(vertexShaderStage); + vertexShaderStage.usedTimes++; + } + if (materialShaders.has(fragmentShaderStage) === false) { + materialShaders.add(fragmentShaderStage); + fragmentShaderStage.usedTimes++; + } + return this; + } + remove(material) { + const materialShaders = this.materialCache.get(material); + for (const shaderStage of materialShaders) { + shaderStage.usedTimes--; + if (shaderStage.usedTimes === 0) this.shaderCache.delete(shaderStage.code); + } + this.materialCache.delete(material); + return this; + } + getVertexShaderID(material) { + return this._getShaderStage(material.vertexShader).id; + } + getFragmentShaderID(material) { + return this._getShaderStage(material.fragmentShader).id; + } + dispose() { + this.shaderCache.clear(); + this.materialCache.clear(); + } + _getShaderCacheForMaterial(material) { + const cache = this.materialCache; + let set = cache.get(material); + if (set === void 0) { + set = /* @__PURE__ */ new Set(); + cache.set(material, set); + } + return set; + } + _getShaderStage(code) { + const cache = this.shaderCache; + let stage = cache.get(code); + if (stage === void 0) { + stage = new WebGLShaderStage(code); + cache.set(code, stage); + } + return stage; + } + }; + var WebGLShaderStage = class { + constructor(code) { + this.id = _id$1++; + this.code = code; + this.usedTimes = 0; + } + }; + function WebGLPrograms(renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) { + const _programLayers = new Layers(); + const _customShaders = new WebGLShaderCache(); + const programs = []; + const IS_WEBGL2 = capabilities.isWebGL2; + const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; + const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures; + let precision = capabilities.precision; + const shaderIDs = { + MeshDepthMaterial: "depth", + MeshDistanceMaterial: "distanceRGBA", + MeshNormalMaterial: "normal", + MeshBasicMaterial: "basic", + MeshLambertMaterial: "lambert", + MeshPhongMaterial: "phong", + MeshToonMaterial: "toon", + MeshStandardMaterial: "physical", + MeshPhysicalMaterial: "physical", + MeshMatcapMaterial: "matcap", + LineBasicMaterial: "basic", + LineDashedMaterial: "dashed", + PointsMaterial: "points", + ShadowMaterial: "shadow", + SpriteMaterial: "sprite" + }; + function getChannel(value) { + if (value === 0) return "uv"; + return `uv${value}`; + } + function getParameters(material, lights, shadows, scene, object) { + const fog = scene.fog; + const geometry = object.geometry; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment); + const envMapCubeUVHeight = !!envMap && envMap.mapping === CubeUVReflectionMapping ? envMap.image.height : null; + const shaderID = shaderIDs[material.type]; + if (material.precision !== null) { + precision = capabilities.getMaxPrecision(material.precision); + if (precision !== material.precision) { + console.warn("THREE.WebGLProgram.getParameters:", material.precision, "not supported, using", precision, "instead."); + } + } + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== void 0 ? morphAttribute.length : 0; + let morphTextureStride = 0; + if (geometry.morphAttributes.position !== void 0) morphTextureStride = 1; + if (geometry.morphAttributes.normal !== void 0) morphTextureStride = 2; + if (geometry.morphAttributes.color !== void 0) morphTextureStride = 3; + let vertexShader, fragmentShader; + let customVertexShaderID, customFragmentShaderID; + if (shaderID) { + const shader = ShaderLib[shaderID]; + vertexShader = shader.vertexShader; + fragmentShader = shader.fragmentShader; + } else { + vertexShader = material.vertexShader; + fragmentShader = material.fragmentShader; + _customShaders.update(material); + customVertexShaderID = _customShaders.getVertexShaderID(material); + customFragmentShaderID = _customShaders.getFragmentShaderID(material); + } + const currentRenderTarget = renderer.getRenderTarget(); + const IS_INSTANCEDMESH = object.isInstancedMesh === true; + const IS_BATCHEDMESH = object.isBatchedMesh === true; + const HAS_MAP = !!material.map; + const HAS_MATCAP = !!material.matcap; + const HAS_ENVMAP = !!envMap; + const HAS_AOMAP = !!material.aoMap; + const HAS_LIGHTMAP = !!material.lightMap; + const HAS_BUMPMAP = !!material.bumpMap; + const HAS_NORMALMAP = !!material.normalMap; + const HAS_DISPLACEMENTMAP = !!material.displacementMap; + const HAS_EMISSIVEMAP = !!material.emissiveMap; + const HAS_METALNESSMAP = !!material.metalnessMap; + const HAS_ROUGHNESSMAP = !!material.roughnessMap; + const HAS_ANISOTROPY = material.anisotropy > 0; + const HAS_CLEARCOAT = material.clearcoat > 0; + const HAS_IRIDESCENCE = material.iridescence > 0; + const HAS_SHEEN = material.sheen > 0; + const HAS_TRANSMISSION = material.transmission > 0; + const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !!material.anisotropyMap; + const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !!material.clearcoatMap; + const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !!material.clearcoatNormalMap; + const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !!material.clearcoatRoughnessMap; + const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !!material.iridescenceMap; + const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !!material.iridescenceThicknessMap; + const HAS_SHEEN_COLORMAP = HAS_SHEEN && !!material.sheenColorMap; + const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !!material.sheenRoughnessMap; + const HAS_SPECULARMAP = !!material.specularMap; + const HAS_SPECULAR_COLORMAP = !!material.specularColorMap; + const HAS_SPECULAR_INTENSITYMAP = !!material.specularIntensityMap; + const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !!material.transmissionMap; + const HAS_THICKNESSMAP = HAS_TRANSMISSION && !!material.thicknessMap; + const HAS_GRADIENTMAP = !!material.gradientMap; + const HAS_ALPHAMAP = !!material.alphaMap; + const HAS_ALPHATEST = material.alphaTest > 0; + const HAS_ALPHAHASH = !!material.alphaHash; + const HAS_EXTENSIONS = !!material.extensions; + const HAS_ATTRIBUTE_UV1 = !!geometry.attributes.uv1; + const HAS_ATTRIBUTE_UV2 = !!geometry.attributes.uv2; + const HAS_ATTRIBUTE_UV3 = !!geometry.attributes.uv3; + let toneMapping = NoToneMapping; + if (material.toneMapped) { + if (currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true) { + toneMapping = renderer.toneMapping; + } + } + const parameters = { + isWebGL2: IS_WEBGL2, + shaderID, + shaderType: material.type, + shaderName: material.name, + vertexShader, + fragmentShader, + defines: material.defines, + customVertexShaderID, + customFragmentShaderID, + isRawShaderMaterial: material.isRawShaderMaterial === true, + glslVersion: material.glslVersion, + precision, + batching: IS_BATCHEDMESH, + instancing: IS_INSTANCEDMESH, + instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null, + supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES, + outputColorSpace: currentRenderTarget === null ? renderer.outputColorSpace : currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace, + map: HAS_MAP, + matcap: HAS_MATCAP, + envMap: HAS_ENVMAP, + envMapMode: HAS_ENVMAP && envMap.mapping, + envMapCubeUVHeight, + aoMap: HAS_AOMAP, + lightMap: HAS_LIGHTMAP, + bumpMap: HAS_BUMPMAP, + normalMap: HAS_NORMALMAP, + displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP, + emissiveMap: HAS_EMISSIVEMAP, + normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap, + normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap, + metalnessMap: HAS_METALNESSMAP, + roughnessMap: HAS_ROUGHNESSMAP, + anisotropy: HAS_ANISOTROPY, + anisotropyMap: HAS_ANISOTROPYMAP, + clearcoat: HAS_CLEARCOAT, + clearcoatMap: HAS_CLEARCOATMAP, + clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP, + clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP, + iridescence: HAS_IRIDESCENCE, + iridescenceMap: HAS_IRIDESCENCEMAP, + iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP, + sheen: HAS_SHEEN, + sheenColorMap: HAS_SHEEN_COLORMAP, + sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP, + specularMap: HAS_SPECULARMAP, + specularColorMap: HAS_SPECULAR_COLORMAP, + specularIntensityMap: HAS_SPECULAR_INTENSITYMAP, + transmission: HAS_TRANSMISSION, + transmissionMap: HAS_TRANSMISSIONMAP, + thicknessMap: HAS_THICKNESSMAP, + gradientMap: HAS_GRADIENTMAP, + opaque: material.transparent === false && material.blending === NormalBlending, + alphaMap: HAS_ALPHAMAP, + alphaTest: HAS_ALPHATEST, + alphaHash: HAS_ALPHAHASH, + combine: material.combine, + // + mapUv: HAS_MAP && getChannel(material.map.channel), + aoMapUv: HAS_AOMAP && getChannel(material.aoMap.channel), + lightMapUv: HAS_LIGHTMAP && getChannel(material.lightMap.channel), + bumpMapUv: HAS_BUMPMAP && getChannel(material.bumpMap.channel), + normalMapUv: HAS_NORMALMAP && getChannel(material.normalMap.channel), + displacementMapUv: HAS_DISPLACEMENTMAP && getChannel(material.displacementMap.channel), + emissiveMapUv: HAS_EMISSIVEMAP && getChannel(material.emissiveMap.channel), + metalnessMapUv: HAS_METALNESSMAP && getChannel(material.metalnessMap.channel), + roughnessMapUv: HAS_ROUGHNESSMAP && getChannel(material.roughnessMap.channel), + anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel(material.anisotropyMap.channel), + clearcoatMapUv: HAS_CLEARCOATMAP && getChannel(material.clearcoatMap.channel), + clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel(material.clearcoatNormalMap.channel), + clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel(material.clearcoatRoughnessMap.channel), + iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel(material.iridescenceMap.channel), + iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel(material.iridescenceThicknessMap.channel), + sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel(material.sheenColorMap.channel), + sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel(material.sheenRoughnessMap.channel), + specularMapUv: HAS_SPECULARMAP && getChannel(material.specularMap.channel), + specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel(material.specularColorMap.channel), + specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel(material.specularIntensityMap.channel), + transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel(material.transmissionMap.channel), + thicknessMapUv: HAS_THICKNESSMAP && getChannel(material.thicknessMap.channel), + alphaMapUv: HAS_ALPHAMAP && getChannel(material.alphaMap.channel), + // + vertexTangents: !!geometry.attributes.tangent && (HAS_NORMALMAP || HAS_ANISOTROPY), + vertexColors: material.vertexColors, + vertexAlphas: material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4, + vertexUv1s: HAS_ATTRIBUTE_UV1, + vertexUv2s: HAS_ATTRIBUTE_UV2, + vertexUv3s: HAS_ATTRIBUTE_UV3, + pointsUvs: object.isPoints === true && !!geometry.attributes.uv && (HAS_MAP || HAS_ALPHAMAP), + fog: !!fog, + useFog: material.fog === true, + fogExp2: fog && fog.isFogExp2, + flatShading: material.flatShading === true, + sizeAttenuation: material.sizeAttenuation === true, + logarithmicDepthBuffer, + skinning: object.isSkinnedMesh === true, + morphTargets: geometry.morphAttributes.position !== void 0, + morphNormals: geometry.morphAttributes.normal !== void 0, + morphColors: geometry.morphAttributes.color !== void 0, + morphTargetsCount, + morphTextureStride, + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numSpotLightMaps: lights.spotLightMap.length, + numRectAreaLights: lights.rectArea.length, + numHemiLights: lights.hemi.length, + numDirLightShadows: lights.directionalShadowMap.length, + numPointLightShadows: lights.pointShadowMap.length, + numSpotLightShadows: lights.spotShadowMap.length, + numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps, + numLightProbes: lights.numLightProbes, + numClippingPlanes: clipping.numPlanes, + numClipIntersection: clipping.numIntersection, + dithering: material.dithering, + shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0, + shadowMapType: renderer.shadowMap.type, + toneMapping, + useLegacyLights: renderer._useLegacyLights, + decodeVideoTexture: HAS_MAP && material.map.isVideoTexture === true && ColorManagement.getTransfer(material.map.colorSpace) === SRGBTransfer, + premultipliedAlpha: material.premultipliedAlpha, + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, + useDepthPacking: material.depthPacking >= 0, + depthPacking: material.depthPacking || 0, + index0AttributeName: material.index0AttributeName, + extensionDerivatives: HAS_EXTENSIONS && material.extensions.derivatives === true, + extensionFragDepth: HAS_EXTENSIONS && material.extensions.fragDepth === true, + extensionDrawBuffers: HAS_EXTENSIONS && material.extensions.drawBuffers === true, + extensionShaderTextureLOD: HAS_EXTENSIONS && material.extensions.shaderTextureLOD === true, + extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance && extensions.has("WEBGL_clip_cull_distance"), + rendererExtensionFragDepth: IS_WEBGL2 || extensions.has("EXT_frag_depth"), + rendererExtensionDrawBuffers: IS_WEBGL2 || extensions.has("WEBGL_draw_buffers"), + rendererExtensionShaderTextureLod: IS_WEBGL2 || extensions.has("EXT_shader_texture_lod"), + rendererExtensionParallelShaderCompile: extensions.has("KHR_parallel_shader_compile"), + customProgramCacheKey: material.customProgramCacheKey() + }; + return parameters; + } + function getProgramCacheKey(parameters) { + const array = []; + if (parameters.shaderID) { + array.push(parameters.shaderID); + } else { + array.push(parameters.customVertexShaderID); + array.push(parameters.customFragmentShaderID); + } + if (parameters.defines !== void 0) { + for (const name in parameters.defines) { + array.push(name); + array.push(parameters.defines[name]); + } + } + if (parameters.isRawShaderMaterial === false) { + getProgramCacheKeyParameters(array, parameters); + getProgramCacheKeyBooleans(array, parameters); + array.push(renderer.outputColorSpace); + } + array.push(parameters.customProgramCacheKey); + return array.join(); + } + function getProgramCacheKeyParameters(array, parameters) { + array.push(parameters.precision); + array.push(parameters.outputColorSpace); + array.push(parameters.envMapMode); + array.push(parameters.envMapCubeUVHeight); + array.push(parameters.mapUv); + array.push(parameters.alphaMapUv); + array.push(parameters.lightMapUv); + array.push(parameters.aoMapUv); + array.push(parameters.bumpMapUv); + array.push(parameters.normalMapUv); + array.push(parameters.displacementMapUv); + array.push(parameters.emissiveMapUv); + array.push(parameters.metalnessMapUv); + array.push(parameters.roughnessMapUv); + array.push(parameters.anisotropyMapUv); + array.push(parameters.clearcoatMapUv); + array.push(parameters.clearcoatNormalMapUv); + array.push(parameters.clearcoatRoughnessMapUv); + array.push(parameters.iridescenceMapUv); + array.push(parameters.iridescenceThicknessMapUv); + array.push(parameters.sheenColorMapUv); + array.push(parameters.sheenRoughnessMapUv); + array.push(parameters.specularMapUv); + array.push(parameters.specularColorMapUv); + array.push(parameters.specularIntensityMapUv); + array.push(parameters.transmissionMapUv); + array.push(parameters.thicknessMapUv); + array.push(parameters.combine); + array.push(parameters.fogExp2); + array.push(parameters.sizeAttenuation); + array.push(parameters.morphTargetsCount); + array.push(parameters.morphAttributeCount); + array.push(parameters.numDirLights); + array.push(parameters.numPointLights); + array.push(parameters.numSpotLights); + array.push(parameters.numSpotLightMaps); + array.push(parameters.numHemiLights); + array.push(parameters.numRectAreaLights); + array.push(parameters.numDirLightShadows); + array.push(parameters.numPointLightShadows); + array.push(parameters.numSpotLightShadows); + array.push(parameters.numSpotLightShadowsWithMaps); + array.push(parameters.numLightProbes); + array.push(parameters.shadowMapType); + array.push(parameters.toneMapping); + array.push(parameters.numClippingPlanes); + array.push(parameters.numClipIntersection); + array.push(parameters.depthPacking); + } + function getProgramCacheKeyBooleans(array, parameters) { + _programLayers.disableAll(); + if (parameters.isWebGL2) + _programLayers.enable(0); + if (parameters.supportsVertexTextures) + _programLayers.enable(1); + if (parameters.instancing) + _programLayers.enable(2); + if (parameters.instancingColor) + _programLayers.enable(3); + if (parameters.matcap) + _programLayers.enable(4); + if (parameters.envMap) + _programLayers.enable(5); + if (parameters.normalMapObjectSpace) + _programLayers.enable(6); + if (parameters.normalMapTangentSpace) + _programLayers.enable(7); + if (parameters.clearcoat) + _programLayers.enable(8); + if (parameters.iridescence) + _programLayers.enable(9); + if (parameters.alphaTest) + _programLayers.enable(10); + if (parameters.vertexColors) + _programLayers.enable(11); + if (parameters.vertexAlphas) + _programLayers.enable(12); + if (parameters.vertexUv1s) + _programLayers.enable(13); + if (parameters.vertexUv2s) + _programLayers.enable(14); + if (parameters.vertexUv3s) + _programLayers.enable(15); + if (parameters.vertexTangents) + _programLayers.enable(16); + if (parameters.anisotropy) + _programLayers.enable(17); + if (parameters.alphaHash) + _programLayers.enable(18); + if (parameters.batching) + _programLayers.enable(19); + array.push(_programLayers.mask); + _programLayers.disableAll(); + if (parameters.fog) + _programLayers.enable(0); + if (parameters.useFog) + _programLayers.enable(1); + if (parameters.flatShading) + _programLayers.enable(2); + if (parameters.logarithmicDepthBuffer) + _programLayers.enable(3); + if (parameters.skinning) + _programLayers.enable(4); + if (parameters.morphTargets) + _programLayers.enable(5); + if (parameters.morphNormals) + _programLayers.enable(6); + if (parameters.morphColors) + _programLayers.enable(7); + if (parameters.premultipliedAlpha) + _programLayers.enable(8); + if (parameters.shadowMapEnabled) + _programLayers.enable(9); + if (parameters.useLegacyLights) + _programLayers.enable(10); + if (parameters.doubleSided) + _programLayers.enable(11); + if (parameters.flipSided) + _programLayers.enable(12); + if (parameters.useDepthPacking) + _programLayers.enable(13); + if (parameters.dithering) + _programLayers.enable(14); + if (parameters.transmission) + _programLayers.enable(15); + if (parameters.sheen) + _programLayers.enable(16); + if (parameters.opaque) + _programLayers.enable(17); + if (parameters.pointsUvs) + _programLayers.enable(18); + if (parameters.decodeVideoTexture) + _programLayers.enable(19); + array.push(_programLayers.mask); + } + function getUniforms(material) { + const shaderID = shaderIDs[material.type]; + let uniforms; + if (shaderID) { + const shader = ShaderLib[shaderID]; + uniforms = UniformsUtils.clone(shader.uniforms); + } else { + uniforms = material.uniforms; + } + return uniforms; + } + function acquireProgram(parameters, cacheKey) { + let program; + for (let p = 0, pl = programs.length; p < pl; p++) { + const preexistingProgram = programs[p]; + if (preexistingProgram.cacheKey === cacheKey) { + program = preexistingProgram; + ++program.usedTimes; + break; + } + } + if (program === void 0) { + program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates); + programs.push(program); + } + return program; + } + function releaseProgram(program) { + if (--program.usedTimes === 0) { + const i = programs.indexOf(program); + programs[i] = programs[programs.length - 1]; + programs.pop(); + program.destroy(); + } + } + function releaseShaderCache(material) { + _customShaders.remove(material); + } + function dispose() { + _customShaders.dispose(); + } + return { + getParameters, + getProgramCacheKey, + getUniforms, + acquireProgram, + releaseProgram, + releaseShaderCache, + // Exposed for resource monitoring & error feedback via renderer.info: + programs, + dispose + }; + } + function WebGLProperties() { + let properties = /* @__PURE__ */ new WeakMap(); + function get(object) { + let map = properties.get(object); + if (map === void 0) { + map = {}; + properties.set(object, map); + } + return map; + } + function remove(object) { + properties.delete(object); + } + function update(object, key, value) { + properties.get(object)[key] = value; + } + function dispose() { + properties = /* @__PURE__ */ new WeakMap(); + } + return { + get, + remove, + update, + dispose + }; + } + function painterSortStable(a, b) { + if (a.groupOrder !== b.groupOrder) { + return a.groupOrder - b.groupOrder; + } else if (a.renderOrder !== b.renderOrder) { + return a.renderOrder - b.renderOrder; + } else if (a.material.id !== b.material.id) { + return a.material.id - b.material.id; + } else if (a.z !== b.z) { + return a.z - b.z; + } else { + return a.id - b.id; + } + } + function reversePainterSortStable(a, b) { + if (a.groupOrder !== b.groupOrder) { + return a.groupOrder - b.groupOrder; + } else if (a.renderOrder !== b.renderOrder) { + return a.renderOrder - b.renderOrder; + } else if (a.z !== b.z) { + return b.z - a.z; + } else { + return a.id - b.id; + } + } + function WebGLRenderList() { + const renderItems = []; + let renderItemsIndex = 0; + const opaque = []; + const transmissive = []; + const transparent = []; + function init() { + renderItemsIndex = 0; + opaque.length = 0; + transmissive.length = 0; + transparent.length = 0; + } + function getNextRenderItem(object, geometry, material, groupOrder, z, group) { + let renderItem = renderItems[renderItemsIndex]; + if (renderItem === void 0) { + renderItem = { + id: object.id, + object, + geometry, + material, + groupOrder, + renderOrder: object.renderOrder, + z, + group + }; + renderItems[renderItemsIndex] = renderItem; + } else { + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.groupOrder = groupOrder; + renderItem.renderOrder = object.renderOrder; + renderItem.z = z; + renderItem.group = group; + } + renderItemsIndex++; + return renderItem; + } + function push(object, geometry, material, groupOrder, z, group) { + const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group); + if (material.transmission > 0) { + transmissive.push(renderItem); + } else if (material.transparent === true) { + transparent.push(renderItem); + } else { + opaque.push(renderItem); + } + } + function unshift(object, geometry, material, groupOrder, z, group) { + const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group); + if (material.transmission > 0) { + transmissive.unshift(renderItem); + } else if (material.transparent === true) { + transparent.unshift(renderItem); + } else { + opaque.unshift(renderItem); + } + } + function sort(customOpaqueSort, customTransparentSort) { + if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable); + if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable); + if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable); + } + function finish() { + for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) { + const renderItem = renderItems[i]; + if (renderItem.id === null) break; + renderItem.id = null; + renderItem.object = null; + renderItem.geometry = null; + renderItem.material = null; + renderItem.group = null; + } + } + return { + opaque, + transmissive, + transparent, + init, + push, + unshift, + finish, + sort + }; + } + function WebGLRenderLists() { + let lists = /* @__PURE__ */ new WeakMap(); + function get(scene, renderCallDepth) { + const listArray = lists.get(scene); + let list; + if (listArray === void 0) { + list = new WebGLRenderList(); + lists.set(scene, [list]); + } else { + if (renderCallDepth >= listArray.length) { + list = new WebGLRenderList(); + listArray.push(list); + } else { + list = listArray[renderCallDepth]; + } + } + return list; + } + function dispose() { + lists = /* @__PURE__ */ new WeakMap(); + } + return { + get, + dispose + }; + } + function UniformsCache() { + const lights = {}; + return { + get: function(light) { + if (lights[light.id] !== void 0) { + return lights[light.id]; + } + let uniforms; + switch (light.type) { + case "DirectionalLight": + uniforms = { + direction: new Vector3(), + color: new Color() + }; + break; + case "SpotLight": + uniforms = { + position: new Vector3(), + direction: new Vector3(), + color: new Color(), + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0 + }; + break; + case "PointLight": + uniforms = { + position: new Vector3(), + color: new Color(), + distance: 0, + decay: 0 + }; + break; + case "HemisphereLight": + uniforms = { + direction: new Vector3(), + skyColor: new Color(), + groundColor: new Color() + }; + break; + case "RectAreaLight": + uniforms = { + color: new Color(), + position: new Vector3(), + halfWidth: new Vector3(), + halfHeight: new Vector3() + }; + break; + } + lights[light.id] = uniforms; + return uniforms; + } + }; + } + function ShadowUniformsCache() { + const lights = {}; + return { + get: function(light) { + if (lights[light.id] !== void 0) { + return lights[light.id]; + } + let uniforms; + switch (light.type) { + case "DirectionalLight": + uniforms = { + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; + case "SpotLight": + uniforms = { + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; + case "PointLight": + uniforms = { + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2(), + shadowCameraNear: 1, + shadowCameraFar: 1e3 + }; + break; + } + lights[light.id] = uniforms; + return uniforms; + } + }; + } + var nextVersion = 0; + function shadowCastingAndTexturingLightsFirst(lightA, lightB) { + return (lightB.castShadow ? 2 : 0) - (lightA.castShadow ? 2 : 0) + (lightB.map ? 1 : 0) - (lightA.map ? 1 : 0); + } + function WebGLLights(extensions, capabilities) { + const cache = new UniformsCache(); + const shadowCache = ShadowUniformsCache(); + const state = { + version: 0, + hash: { + directionalLength: -1, + pointLength: -1, + spotLength: -1, + rectAreaLength: -1, + hemiLength: -1, + numDirectionalShadows: -1, + numPointShadows: -1, + numSpotShadows: -1, + numSpotMaps: -1, + numLightProbes: -1 + }, + ambient: [0, 0, 0], + probe: [], + directional: [], + directionalShadow: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotLightMap: [], + spotShadow: [], + spotShadowMap: [], + spotLightMatrix: [], + rectArea: [], + rectAreaLTC1: null, + rectAreaLTC2: null, + point: [], + pointShadow: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [], + numSpotLightShadowsWithMaps: 0, + numLightProbes: 0 + }; + for (let i = 0; i < 9; i++) state.probe.push(new Vector3()); + const vector3 = new Vector3(); + const matrix4 = new Matrix4(); + const matrix42 = new Matrix4(); + function setup(lights, useLegacyLights) { + let r = 0, g = 0, b = 0; + for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0); + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + let numDirectionalShadows = 0; + let numPointShadows = 0; + let numSpotShadows = 0; + let numSpotMaps = 0; + let numSpotShadowsWithMaps = 0; + let numLightProbes = 0; + lights.sort(shadowCastingAndTexturingLightsFirst); + const scaleFactor = useLegacyLights === true ? Math.PI : 1; + for (let i = 0, l = lights.length; i < l; i++) { + const light = lights[i]; + const color = light.color; + const intensity = light.intensity; + const distance = light.distance; + const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null; + if (light.isAmbientLight) { + r += color.r * intensity * scaleFactor; + g += color.g * intensity * scaleFactor; + b += color.b * intensity * scaleFactor; + } else if (light.isLightProbe) { + for (let j = 0; j < 9; j++) { + state.probe[j].addScaledVector(light.sh.coefficients[j], intensity); + } + numLightProbes++; + } else if (light.isDirectionalLight) { + const uniforms = cache.get(light); + uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor); + if (light.castShadow) { + const shadow = light.shadow; + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + state.directionalShadow[directionalLength] = shadowUniforms; + state.directionalShadowMap[directionalLength] = shadowMap; + state.directionalShadowMatrix[directionalLength] = light.shadow.matrix; + numDirectionalShadows++; + } + state.directional[directionalLength] = uniforms; + directionalLength++; + } else if (light.isSpotLight) { + const uniforms = cache.get(light); + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.color.copy(color).multiplyScalar(intensity * scaleFactor); + uniforms.distance = distance; + uniforms.coneCos = Math.cos(light.angle); + uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra)); + uniforms.decay = light.decay; + state.spot[spotLength] = uniforms; + const shadow = light.shadow; + if (light.map) { + state.spotLightMap[numSpotMaps] = light.map; + numSpotMaps++; + shadow.updateMatrices(light); + if (light.castShadow) numSpotShadowsWithMaps++; + } + state.spotLightMatrix[spotLength] = shadow.matrix; + if (light.castShadow) { + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + state.spotShadow[spotLength] = shadowUniforms; + state.spotShadowMap[spotLength] = shadowMap; + numSpotShadows++; + } + spotLength++; + } else if (light.isRectAreaLight) { + const uniforms = cache.get(light); + uniforms.color.copy(color).multiplyScalar(intensity); + uniforms.halfWidth.set(light.width * 0.5, 0, 0); + uniforms.halfHeight.set(0, light.height * 0.5, 0); + state.rectArea[rectAreaLength] = uniforms; + rectAreaLength++; + } else if (light.isPointLight) { + const uniforms = cache.get(light); + uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor); + uniforms.distance = light.distance; + uniforms.decay = light.decay; + if (light.castShadow) { + const shadow = light.shadow; + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + shadowUniforms.shadowCameraNear = shadow.camera.near; + shadowUniforms.shadowCameraFar = shadow.camera.far; + state.pointShadow[pointLength] = shadowUniforms; + state.pointShadowMap[pointLength] = shadowMap; + state.pointShadowMatrix[pointLength] = light.shadow.matrix; + numPointShadows++; + } + state.point[pointLength] = uniforms; + pointLength++; + } else if (light.isHemisphereLight) { + const uniforms = cache.get(light); + uniforms.skyColor.copy(light.color).multiplyScalar(intensity * scaleFactor); + uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity * scaleFactor); + state.hemi[hemiLength] = uniforms; + hemiLength++; + } + } + if (rectAreaLength > 0) { + if (capabilities.isWebGL2) { + if (extensions.has("OES_texture_float_linear") === true) { + state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1; + state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2; + } else { + state.rectAreaLTC1 = UniformsLib.LTC_HALF_1; + state.rectAreaLTC2 = UniformsLib.LTC_HALF_2; + } + } else { + if (extensions.has("OES_texture_float_linear") === true) { + state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1; + state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2; + } else if (extensions.has("OES_texture_half_float_linear") === true) { + state.rectAreaLTC1 = UniformsLib.LTC_HALF_1; + state.rectAreaLTC2 = UniformsLib.LTC_HALF_2; + } else { + console.error("THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions."); + } + } + } + state.ambient[0] = r; + state.ambient[1] = g; + state.ambient[2] = b; + const hash = state.hash; + if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows || hash.numSpotMaps !== numSpotMaps || hash.numLightProbes !== numLightProbes) { + state.directional.length = directionalLength; + state.spot.length = spotLength; + state.rectArea.length = rectAreaLength; + state.point.length = pointLength; + state.hemi.length = hemiLength; + state.directionalShadow.length = numDirectionalShadows; + state.directionalShadowMap.length = numDirectionalShadows; + state.pointShadow.length = numPointShadows; + state.pointShadowMap.length = numPointShadows; + state.spotShadow.length = numSpotShadows; + state.spotShadowMap.length = numSpotShadows; + state.directionalShadowMatrix.length = numDirectionalShadows; + state.pointShadowMatrix.length = numPointShadows; + state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps; + state.spotLightMap.length = numSpotMaps; + state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps; + state.numLightProbes = numLightProbes; + hash.directionalLength = directionalLength; + hash.pointLength = pointLength; + hash.spotLength = spotLength; + hash.rectAreaLength = rectAreaLength; + hash.hemiLength = hemiLength; + hash.numDirectionalShadows = numDirectionalShadows; + hash.numPointShadows = numPointShadows; + hash.numSpotShadows = numSpotShadows; + hash.numSpotMaps = numSpotMaps; + hash.numLightProbes = numLightProbes; + state.version = nextVersion++; + } + } + function setupView(lights, camera) { + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + const viewMatrix = camera.matrixWorldInverse; + for (let i = 0, l = lights.length; i < l; i++) { + const light = lights[i]; + if (light.isDirectionalLight) { + const uniforms = state.directional[directionalLength]; + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + vector3.setFromMatrixPosition(light.target.matrixWorld); + uniforms.direction.sub(vector3); + uniforms.direction.transformDirection(viewMatrix); + directionalLength++; + } else if (light.isSpotLight) { + const uniforms = state.spot[spotLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + vector3.setFromMatrixPosition(light.target.matrixWorld); + uniforms.direction.sub(vector3); + uniforms.direction.transformDirection(viewMatrix); + spotLength++; + } else if (light.isRectAreaLight) { + const uniforms = state.rectArea[rectAreaLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + matrix42.identity(); + matrix4.copy(light.matrixWorld); + matrix4.premultiply(viewMatrix); + matrix42.extractRotation(matrix4); + uniforms.halfWidth.set(light.width * 0.5, 0, 0); + uniforms.halfHeight.set(0, light.height * 0.5, 0); + uniforms.halfWidth.applyMatrix4(matrix42); + uniforms.halfHeight.applyMatrix4(matrix42); + rectAreaLength++; + } else if (light.isPointLight) { + const uniforms = state.point[pointLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + pointLength++; + } else if (light.isHemisphereLight) { + const uniforms = state.hemi[hemiLength]; + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + uniforms.direction.transformDirection(viewMatrix); + hemiLength++; + } + } + } + return { + setup, + setupView, + state + }; + } + function WebGLRenderState(extensions, capabilities) { + const lights = new WebGLLights(extensions, capabilities); + const lightsArray = []; + const shadowsArray = []; + function init() { + lightsArray.length = 0; + shadowsArray.length = 0; + } + function pushLight(light) { + lightsArray.push(light); + } + function pushShadow(shadowLight) { + shadowsArray.push(shadowLight); + } + function setupLights(useLegacyLights) { + lights.setup(lightsArray, useLegacyLights); + } + function setupLightsView(camera) { + lights.setupView(lightsArray, camera); + } + const state = { + lightsArray, + shadowsArray, + lights + }; + return { + init, + state, + setupLights, + setupLightsView, + pushLight, + pushShadow + }; + } + function WebGLRenderStates(extensions, capabilities) { + let renderStates = /* @__PURE__ */ new WeakMap(); + function get(scene, renderCallDepth = 0) { + const renderStateArray = renderStates.get(scene); + let renderState; + if (renderStateArray === void 0) { + renderState = new WebGLRenderState(extensions, capabilities); + renderStates.set(scene, [renderState]); + } else { + if (renderCallDepth >= renderStateArray.length) { + renderState = new WebGLRenderState(extensions, capabilities); + renderStateArray.push(renderState); + } else { + renderState = renderStateArray[renderCallDepth]; + } + } + return renderState; + } + function dispose() { + renderStates = /* @__PURE__ */ new WeakMap(); + } + return { + get, + dispose + }; + } + var MeshDepthMaterial = class extends Material { + constructor(parameters) { + super(); + this.isMeshDepthMaterial = true; + this.type = "MeshDepthMaterial"; + this.depthPacking = BasicDepthPacking; + this.map = null; + this.alphaMap = null; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.depthPacking = source.depthPacking; + this.map = source.map; + this.alphaMap = source.alphaMap; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + return this; + } + }; + var MeshDistanceMaterial = class extends Material { + constructor(parameters) { + super(); + this.isMeshDistanceMaterial = true; + this.type = "MeshDistanceMaterial"; + this.map = null; + this.alphaMap = null; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + return this; + } + }; + var vertex = "void main() {\n gl_Position = vec4( position, 1.0 );\n}"; + var fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n const float samples = float( VSM_SAMPLES );\n float mean = 0.0;\n float squared_mean = 0.0;\n float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n float uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n for ( float i = 0.0; i < samples; i ++ ) {\n float uvOffset = uvStart + i * uvStride;\n #ifdef HORIZONTAL_PASS\n vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n mean += distribution.x;\n squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n #else\n float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n mean += depth;\n squared_mean += depth * depth;\n #endif\n }\n mean = mean / samples;\n squared_mean = squared_mean / samples;\n float std_dev = sqrt( squared_mean - mean * mean );\n gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"; + function WebGLShadowMap(_renderer2, _objects, _capabilities) { + let _frustum2 = new Frustum(); + const _shadowMapSize = new Vector2(), _viewportSize = new Vector2(), _viewport = new Vector4(), _depthMaterial = new MeshDepthMaterial({ depthPacking: RGBADepthPacking }), _distanceMaterial = new MeshDistanceMaterial(), _materialCache = {}, _maxTextureSize = _capabilities.maxTextureSize; + const shadowSide = { [FrontSide]: BackSide, [BackSide]: FrontSide, [DoubleSide]: DoubleSide }; + const shadowMaterialVertical = new ShaderMaterial({ + defines: { + VSM_SAMPLES: 8 + }, + uniforms: { + shadow_pass: { value: null }, + resolution: { value: new Vector2() }, + radius: { value: 4 } + }, + vertexShader: vertex, + fragmentShader: fragment + }); + const shadowMaterialHorizontal = shadowMaterialVertical.clone(); + shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1; + const fullScreenTri = new BufferGeometry(); + fullScreenTri.setAttribute( + "position", + new BufferAttribute( + new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), + 3 + ) + ); + const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical); + const scope = this; + this.enabled = false; + this.autoUpdate = true; + this.needsUpdate = false; + this.type = PCFShadowMap; + let _previousType = this.type; + this.render = function(lights, scene, camera) { + if (scope.enabled === false) return; + if (scope.autoUpdate === false && scope.needsUpdate === false) return; + if (lights.length === 0) return; + const currentRenderTarget = _renderer2.getRenderTarget(); + const activeCubeFace = _renderer2.getActiveCubeFace(); + const activeMipmapLevel = _renderer2.getActiveMipmapLevel(); + const _state = _renderer2.state; + _state.setBlending(NoBlending); + _state.buffers.color.setClear(1, 1, 1, 1); + _state.buffers.depth.setTest(true); + _state.setScissorTest(false); + const toVSM = _previousType !== VSMShadowMap && this.type === VSMShadowMap; + const fromVSM = _previousType === VSMShadowMap && this.type !== VSMShadowMap; + for (let i = 0, il = lights.length; i < il; i++) { + const light = lights[i]; + const shadow = light.shadow; + if (shadow === void 0) { + console.warn("THREE.WebGLShadowMap:", light, "has no shadow."); + continue; + } + if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue; + _shadowMapSize.copy(shadow.mapSize); + const shadowFrameExtents = shadow.getFrameExtents(); + _shadowMapSize.multiply(shadowFrameExtents); + _viewportSize.copy(shadow.mapSize); + if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) { + if (_shadowMapSize.x > _maxTextureSize) { + _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x); + _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; + shadow.mapSize.x = _viewportSize.x; + } + if (_shadowMapSize.y > _maxTextureSize) { + _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y); + _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; + shadow.mapSize.y = _viewportSize.y; + } + } + if (shadow.map === null || toVSM === true || fromVSM === true) { + const pars = this.type !== VSMShadowMap ? { minFilter: NearestFilter, magFilter: NearestFilter } : {}; + if (shadow.map !== null) { + shadow.map.dispose(); + } + shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars); + shadow.map.texture.name = light.name + ".shadowMap"; + shadow.camera.updateProjectionMatrix(); + } + _renderer2.setRenderTarget(shadow.map); + _renderer2.clear(); + const viewportCount = shadow.getViewportCount(); + for (let vp = 0; vp < viewportCount; vp++) { + const viewport = shadow.getViewport(vp); + _viewport.set( + _viewportSize.x * viewport.x, + _viewportSize.y * viewport.y, + _viewportSize.x * viewport.z, + _viewportSize.y * viewport.w + ); + _state.viewport(_viewport); + shadow.updateMatrices(light, vp); + _frustum2 = shadow.getFrustum(); + renderObject(scene, camera, shadow.camera, light, this.type); + } + if (shadow.isPointLightShadow !== true && this.type === VSMShadowMap) { + VSMPass(shadow, camera); + } + shadow.needsUpdate = false; + } + _previousType = this.type; + scope.needsUpdate = false; + _renderer2.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel); + }; + function VSMPass(shadow, camera) { + const geometry = _objects.update(fullScreenMesh); + if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) { + shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialVertical.needsUpdate = true; + shadowMaterialHorizontal.needsUpdate = true; + } + if (shadow.mapPass === null) { + shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y); + } + shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; + shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize; + shadowMaterialVertical.uniforms.radius.value = shadow.radius; + _renderer2.setRenderTarget(shadow.mapPass); + _renderer2.clear(); + _renderer2.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); + shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture; + shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize; + shadowMaterialHorizontal.uniforms.radius.value = shadow.radius; + _renderer2.setRenderTarget(shadow.map); + _renderer2.clear(); + _renderer2.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null); + } + function getDepthMaterial(object, material, light, type) { + let result = null; + const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial; + if (customMaterial !== void 0) { + result = customMaterial; + } else { + result = light.isPointLight === true ? _distanceMaterial : _depthMaterial; + if (_renderer2.localClippingEnabled && material.clipShadows === true && Array.isArray(material.clippingPlanes) && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0 || material.map && material.alphaTest > 0) { + const keyA = result.uuid, keyB = material.uuid; + let materialsForVariant = _materialCache[keyA]; + if (materialsForVariant === void 0) { + materialsForVariant = {}; + _materialCache[keyA] = materialsForVariant; + } + let cachedMaterial = materialsForVariant[keyB]; + if (cachedMaterial === void 0) { + cachedMaterial = result.clone(); + materialsForVariant[keyB] = cachedMaterial; + material.addEventListener("dispose", onMaterialDispose); + } + result = cachedMaterial; + } + } + result.visible = material.visible; + result.wireframe = material.wireframe; + if (type === VSMShadowMap) { + result.side = material.shadowSide !== null ? material.shadowSide : material.side; + } else { + result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side]; + } + result.alphaMap = material.alphaMap; + result.alphaTest = material.alphaTest; + result.map = material.map; + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; + result.clipIntersection = material.clipIntersection; + result.displacementMap = material.displacementMap; + result.displacementScale = material.displacementScale; + result.displacementBias = material.displacementBias; + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; + if (light.isPointLight === true && result.isMeshDistanceMaterial === true) { + const materialProperties = _renderer2.properties.get(result); + materialProperties.light = light; + } + return result; + } + function renderObject(object, camera, shadowCamera, light, type) { + if (object.visible === false) return; + const visible = object.layers.test(camera.layers); + if (visible && (object.isMesh || object.isLine || object.isPoints)) { + if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum2.intersectsObject(object))) { + object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld); + const geometry = _objects.update(object); + const material = object.material; + if (Array.isArray(material)) { + const groups = geometry.groups; + for (let k = 0, kl = groups.length; k < kl; k++) { + const group = groups[k]; + const groupMaterial = material[group.materialIndex]; + if (groupMaterial && groupMaterial.visible) { + const depthMaterial = getDepthMaterial(object, groupMaterial, light, type); + object.onBeforeShadow(_renderer2, object, camera, shadowCamera, geometry, depthMaterial, group); + _renderer2.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group); + object.onAfterShadow(_renderer2, object, camera, shadowCamera, geometry, depthMaterial, group); + } + } + } else if (material.visible) { + const depthMaterial = getDepthMaterial(object, material, light, type); + object.onBeforeShadow(_renderer2, object, camera, shadowCamera, geometry, depthMaterial, null); + _renderer2.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null); + object.onAfterShadow(_renderer2, object, camera, shadowCamera, geometry, depthMaterial, null); + } + } + } + const children = object.children; + for (let i = 0, l = children.length; i < l; i++) { + renderObject(children[i], camera, shadowCamera, light, type); + } + } + function onMaterialDispose(event) { + const material = event.target; + material.removeEventListener("dispose", onMaterialDispose); + for (const id in _materialCache) { + const cache = _materialCache[id]; + const uuid = event.target.uuid; + if (uuid in cache) { + const shadowMaterial = cache[uuid]; + shadowMaterial.dispose(); + delete cache[uuid]; + } + } + } + } + function WebGLState(gl, extensions, capabilities) { + const isWebGL2 = capabilities.isWebGL2; + function ColorBuffer() { + let locked = false; + const color = new Vector4(); + let currentColorMask = null; + const currentColorClear = new Vector4(0, 0, 0, 0); + return { + setMask: function(colorMask) { + if (currentColorMask !== colorMask && !locked) { + gl.colorMask(colorMask, colorMask, colorMask, colorMask); + currentColorMask = colorMask; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(r, g, b, a, premultipliedAlpha) { + if (premultipliedAlpha === true) { + r *= a; + g *= a; + b *= a; + } + color.set(r, g, b, a); + if (currentColorClear.equals(color) === false) { + gl.clearColor(r, g, b, a); + currentColorClear.copy(color); + } + }, + reset: function() { + locked = false; + currentColorMask = null; + currentColorClear.set(-1, 0, 0, 0); + } + }; + } + function DepthBuffer() { + let locked = false; + let currentDepthMask = null; + let currentDepthFunc = null; + let currentDepthClear = null; + return { + setTest: function(depthTest) { + if (depthTest) { + enable(gl.DEPTH_TEST); + } else { + disable(gl.DEPTH_TEST); + } + }, + setMask: function(depthMask) { + if (currentDepthMask !== depthMask && !locked) { + gl.depthMask(depthMask); + currentDepthMask = depthMask; + } + }, + setFunc: function(depthFunc) { + if (currentDepthFunc !== depthFunc) { + switch (depthFunc) { + case NeverDepth: + gl.depthFunc(gl.NEVER); + break; + case AlwaysDepth: + gl.depthFunc(gl.ALWAYS); + break; + case LessDepth: + gl.depthFunc(gl.LESS); + break; + case LessEqualDepth: + gl.depthFunc(gl.LEQUAL); + break; + case EqualDepth: + gl.depthFunc(gl.EQUAL); + break; + case GreaterEqualDepth: + gl.depthFunc(gl.GEQUAL); + break; + case GreaterDepth: + gl.depthFunc(gl.GREATER); + break; + case NotEqualDepth: + gl.depthFunc(gl.NOTEQUAL); + break; + default: + gl.depthFunc(gl.LEQUAL); + } + currentDepthFunc = depthFunc; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(depth) { + if (currentDepthClear !== depth) { + gl.clearDepth(depth); + currentDepthClear = depth; + } + }, + reset: function() { + locked = false; + currentDepthMask = null; + currentDepthFunc = null; + currentDepthClear = null; + } + }; + } + function StencilBuffer() { + let locked = false; + let currentStencilMask = null; + let currentStencilFunc = null; + let currentStencilRef = null; + let currentStencilFuncMask = null; + let currentStencilFail = null; + let currentStencilZFail = null; + let currentStencilZPass = null; + let currentStencilClear = null; + return { + setTest: function(stencilTest) { + if (!locked) { + if (stencilTest) { + enable(gl.STENCIL_TEST); + } else { + disable(gl.STENCIL_TEST); + } + } + }, + setMask: function(stencilMask) { + if (currentStencilMask !== stencilMask && !locked) { + gl.stencilMask(stencilMask); + currentStencilMask = stencilMask; + } + }, + setFunc: function(stencilFunc, stencilRef, stencilMask) { + if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) { + gl.stencilFunc(stencilFunc, stencilRef, stencilMask); + currentStencilFunc = stencilFunc; + currentStencilRef = stencilRef; + currentStencilFuncMask = stencilMask; + } + }, + setOp: function(stencilFail, stencilZFail, stencilZPass) { + if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) { + gl.stencilOp(stencilFail, stencilZFail, stencilZPass); + currentStencilFail = stencilFail; + currentStencilZFail = stencilZFail; + currentStencilZPass = stencilZPass; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(stencil) { + if (currentStencilClear !== stencil) { + gl.clearStencil(stencil); + currentStencilClear = stencil; + } + }, + reset: function() { + locked = false; + currentStencilMask = null; + currentStencilFunc = null; + currentStencilRef = null; + currentStencilFuncMask = null; + currentStencilFail = null; + currentStencilZFail = null; + currentStencilZPass = null; + currentStencilClear = null; + } + }; + } + const colorBuffer = new ColorBuffer(); + const depthBuffer = new DepthBuffer(); + const stencilBuffer = new StencilBuffer(); + const uboBindings = /* @__PURE__ */ new WeakMap(); + const uboProgramMap = /* @__PURE__ */ new WeakMap(); + let enabledCapabilities = {}; + let currentBoundFramebuffers = {}; + let currentDrawbuffers = /* @__PURE__ */ new WeakMap(); + let defaultDrawbuffers = []; + let currentProgram = null; + let currentBlendingEnabled = false; + let currentBlending = null; + let currentBlendEquation = null; + let currentBlendSrc = null; + let currentBlendDst = null; + let currentBlendEquationAlpha = null; + let currentBlendSrcAlpha = null; + let currentBlendDstAlpha = null; + let currentBlendColor = new Color(0, 0, 0); + let currentBlendAlpha = 0; + let currentPremultipledAlpha = false; + let currentFlipSided = null; + let currentCullFace = null; + let currentLineWidth = null; + let currentPolygonOffsetFactor = null; + let currentPolygonOffsetUnits = null; + const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS); + let lineWidthAvailable = false; + let version = 0; + const glVersion = gl.getParameter(gl.VERSION); + if (glVersion.indexOf("WebGL") !== -1) { + version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]); + lineWidthAvailable = version >= 1; + } else if (glVersion.indexOf("OpenGL ES") !== -1) { + version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]); + lineWidthAvailable = version >= 2; + } + let currentTextureSlot = null; + let currentBoundTextures = {}; + const scissorParam = gl.getParameter(gl.SCISSOR_BOX); + const viewportParam = gl.getParameter(gl.VIEWPORT); + const currentScissor = new Vector4().fromArray(scissorParam); + const currentViewport = new Vector4().fromArray(viewportParam); + function createTexture(type, target, count, dimensions) { + const data = new Uint8Array(4); + const texture = gl.createTexture(); + gl.bindTexture(type, texture); + gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + for (let i = 0; i < count; i++) { + if (isWebGL2 && (type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY)) { + gl.texImage3D(target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data); + } else { + gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data); + } + } + return texture; + } + const emptyTextures = {}; + emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1); + emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); + if (isWebGL2) { + emptyTextures[gl.TEXTURE_2D_ARRAY] = createTexture(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1); + emptyTextures[gl.TEXTURE_3D] = createTexture(gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1); + } + colorBuffer.setClear(0, 0, 0, 1); + depthBuffer.setClear(1); + stencilBuffer.setClear(0); + enable(gl.DEPTH_TEST); + depthBuffer.setFunc(LessEqualDepth); + setFlipSided(false); + setCullFace(CullFaceBack); + enable(gl.CULL_FACE); + setBlending(NoBlending); + function enable(id) { + if (enabledCapabilities[id] !== true) { + gl.enable(id); + enabledCapabilities[id] = true; + } + } + function disable(id) { + if (enabledCapabilities[id] !== false) { + gl.disable(id); + enabledCapabilities[id] = false; + } + } + function bindFramebuffer(target, framebuffer) { + if (currentBoundFramebuffers[target] !== framebuffer) { + gl.bindFramebuffer(target, framebuffer); + currentBoundFramebuffers[target] = framebuffer; + if (isWebGL2) { + if (target === gl.DRAW_FRAMEBUFFER) { + currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer; + } + if (target === gl.FRAMEBUFFER) { + currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer; + } + } + return true; + } + return false; + } + function drawBuffers(renderTarget, framebuffer) { + let drawBuffers2 = defaultDrawbuffers; + let needsUpdate = false; + if (renderTarget) { + drawBuffers2 = currentDrawbuffers.get(framebuffer); + if (drawBuffers2 === void 0) { + drawBuffers2 = []; + currentDrawbuffers.set(framebuffer, drawBuffers2); + } + if (renderTarget.isWebGLMultipleRenderTargets) { + const textures = renderTarget.texture; + if (drawBuffers2.length !== textures.length || drawBuffers2[0] !== gl.COLOR_ATTACHMENT0) { + for (let i = 0, il = textures.length; i < il; i++) { + drawBuffers2[i] = gl.COLOR_ATTACHMENT0 + i; + } + drawBuffers2.length = textures.length; + needsUpdate = true; + } + } else { + if (drawBuffers2[0] !== gl.COLOR_ATTACHMENT0) { + drawBuffers2[0] = gl.COLOR_ATTACHMENT0; + needsUpdate = true; + } + } + } else { + if (drawBuffers2[0] !== gl.BACK) { + drawBuffers2[0] = gl.BACK; + needsUpdate = true; + } + } + if (needsUpdate) { + if (capabilities.isWebGL2) { + gl.drawBuffers(drawBuffers2); + } else { + extensions.get("WEBGL_draw_buffers").drawBuffersWEBGL(drawBuffers2); + } + } + } + function useProgram(program) { + if (currentProgram !== program) { + gl.useProgram(program); + currentProgram = program; + return true; + } + return false; + } + const equationToGL = { + [AddEquation]: gl.FUNC_ADD, + [SubtractEquation]: gl.FUNC_SUBTRACT, + [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT + }; + if (isWebGL2) { + equationToGL[MinEquation] = gl.MIN; + equationToGL[MaxEquation] = gl.MAX; + } else { + const extension = extensions.get("EXT_blend_minmax"); + if (extension !== null) { + equationToGL[MinEquation] = extension.MIN_EXT; + equationToGL[MaxEquation] = extension.MAX_EXT; + } + } + const factorToGL = { + [ZeroFactor]: gl.ZERO, + [OneFactor]: gl.ONE, + [SrcColorFactor]: gl.SRC_COLOR, + [SrcAlphaFactor]: gl.SRC_ALPHA, + [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE, + [DstColorFactor]: gl.DST_COLOR, + [DstAlphaFactor]: gl.DST_ALPHA, + [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR, + [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA, + [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR, + [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA, + [ConstantColorFactor]: gl.CONSTANT_COLOR, + [OneMinusConstantColorFactor]: gl.ONE_MINUS_CONSTANT_COLOR, + [ConstantAlphaFactor]: gl.CONSTANT_ALPHA, + [OneMinusConstantAlphaFactor]: gl.ONE_MINUS_CONSTANT_ALPHA + }; + function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha) { + if (blending === NoBlending) { + if (currentBlendingEnabled === true) { + disable(gl.BLEND); + currentBlendingEnabled = false; + } + return; + } + if (currentBlendingEnabled === false) { + enable(gl.BLEND); + currentBlendingEnabled = true; + } + if (blending !== CustomBlending) { + if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) { + if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) { + gl.blendEquation(gl.FUNC_ADD); + currentBlendEquation = AddEquation; + currentBlendEquationAlpha = AddEquation; + } + if (premultipliedAlpha) { + switch (blending) { + case NormalBlending: + gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case AdditiveBlending: + gl.blendFunc(gl.ONE, gl.ONE); + break; + case SubtractiveBlending: + gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE); + break; + case MultiplyBlending: + gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA); + break; + default: + console.error("THREE.WebGLState: Invalid blending: ", blending); + break; + } + } else { + switch (blending) { + case NormalBlending: + gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case AdditiveBlending: + gl.blendFunc(gl.SRC_ALPHA, gl.ONE); + break; + case SubtractiveBlending: + gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE); + break; + case MultiplyBlending: + gl.blendFunc(gl.ZERO, gl.SRC_COLOR); + break; + default: + console.error("THREE.WebGLState: Invalid blending: ", blending); + break; + } + } + currentBlendSrc = null; + currentBlendDst = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor.set(0, 0, 0); + currentBlendAlpha = 0; + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; + } + return; + } + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; + if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) { + gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]); + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; + } + if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) { + gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]); + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; + } + if (blendColor.equals(currentBlendColor) === false || blendAlpha !== currentBlendAlpha) { + gl.blendColor(blendColor.r, blendColor.g, blendColor.b, blendAlpha); + currentBlendColor.copy(blendColor); + currentBlendAlpha = blendAlpha; + } + currentBlending = blending; + currentPremultipledAlpha = false; + } + function setMaterial(material, frontFaceCW) { + material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE); + let flipSided = material.side === BackSide; + if (frontFaceCW) flipSided = !flipSided; + setFlipSided(flipSided); + material.blending === NormalBlending && material.transparent === false ? setBlending(NoBlending) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha); + depthBuffer.setFunc(material.depthFunc); + depthBuffer.setTest(material.depthTest); + depthBuffer.setMask(material.depthWrite); + colorBuffer.setMask(material.colorWrite); + const stencilWrite = material.stencilWrite; + stencilBuffer.setTest(stencilWrite); + if (stencilWrite) { + stencilBuffer.setMask(material.stencilWriteMask); + stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask); + stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass); + } + setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits); + material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE); + } + function setFlipSided(flipSided) { + if (currentFlipSided !== flipSided) { + if (flipSided) { + gl.frontFace(gl.CW); + } else { + gl.frontFace(gl.CCW); + } + currentFlipSided = flipSided; + } + } + function setCullFace(cullFace) { + if (cullFace !== CullFaceNone) { + enable(gl.CULL_FACE); + if (cullFace !== currentCullFace) { + if (cullFace === CullFaceBack) { + gl.cullFace(gl.BACK); + } else if (cullFace === CullFaceFront) { + gl.cullFace(gl.FRONT); + } else { + gl.cullFace(gl.FRONT_AND_BACK); + } + } + } else { + disable(gl.CULL_FACE); + } + currentCullFace = cullFace; + } + function setLineWidth(width) { + if (width !== currentLineWidth) { + if (lineWidthAvailable) gl.lineWidth(width); + currentLineWidth = width; + } + } + function setPolygonOffset(polygonOffset, factor, units) { + if (polygonOffset) { + enable(gl.POLYGON_OFFSET_FILL); + if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) { + gl.polygonOffset(factor, units); + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; + } + } else { + disable(gl.POLYGON_OFFSET_FILL); + } + } + function setScissorTest(scissorTest) { + if (scissorTest) { + enable(gl.SCISSOR_TEST); + } else { + disable(gl.SCISSOR_TEST); + } + } + function activeTexture(webglSlot) { + if (webglSlot === void 0) webglSlot = gl.TEXTURE0 + maxTextures - 1; + if (currentTextureSlot !== webglSlot) { + gl.activeTexture(webglSlot); + currentTextureSlot = webglSlot; + } + } + function bindTexture(webglType, webglTexture, webglSlot) { + if (webglSlot === void 0) { + if (currentTextureSlot === null) { + webglSlot = gl.TEXTURE0 + maxTextures - 1; + } else { + webglSlot = currentTextureSlot; + } + } + let boundTexture = currentBoundTextures[webglSlot]; + if (boundTexture === void 0) { + boundTexture = { type: void 0, texture: void 0 }; + currentBoundTextures[webglSlot] = boundTexture; + } + if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) { + if (currentTextureSlot !== webglSlot) { + gl.activeTexture(webglSlot); + currentTextureSlot = webglSlot; + } + gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]); + boundTexture.type = webglType; + boundTexture.texture = webglTexture; + } + } + function unbindTexture() { + const boundTexture = currentBoundTextures[currentTextureSlot]; + if (boundTexture !== void 0 && boundTexture.type !== void 0) { + gl.bindTexture(boundTexture.type, null); + boundTexture.type = void 0; + boundTexture.texture = void 0; + } + } + function compressedTexImage2D() { + try { + gl.compressedTexImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexImage3D() { + try { + gl.compressedTexImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texSubImage2D() { + try { + gl.texSubImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texSubImage3D() { + try { + gl.texSubImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexSubImage2D() { + try { + gl.compressedTexSubImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexSubImage3D() { + try { + gl.compressedTexSubImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texStorage2D() { + try { + gl.texStorage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texStorage3D() { + try { + gl.texStorage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texImage2D() { + try { + gl.texImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texImage3D() { + try { + gl.texImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function scissor(scissor2) { + if (currentScissor.equals(scissor2) === false) { + gl.scissor(scissor2.x, scissor2.y, scissor2.z, scissor2.w); + currentScissor.copy(scissor2); + } + } + function viewport(viewport2) { + if (currentViewport.equals(viewport2) === false) { + gl.viewport(viewport2.x, viewport2.y, viewport2.z, viewport2.w); + currentViewport.copy(viewport2); + } + } + function updateUBOMapping(uniformsGroup, program) { + let mapping = uboProgramMap.get(program); + if (mapping === void 0) { + mapping = /* @__PURE__ */ new WeakMap(); + uboProgramMap.set(program, mapping); + } + let blockIndex = mapping.get(uniformsGroup); + if (blockIndex === void 0) { + blockIndex = gl.getUniformBlockIndex(program, uniformsGroup.name); + mapping.set(uniformsGroup, blockIndex); + } + } + function uniformBlockBinding(uniformsGroup, program) { + const mapping = uboProgramMap.get(program); + const blockIndex = mapping.get(uniformsGroup); + if (uboBindings.get(program) !== blockIndex) { + gl.uniformBlockBinding(program, blockIndex, uniformsGroup.__bindingPointIndex); + uboBindings.set(program, blockIndex); + } + } + function reset() { + gl.disable(gl.BLEND); + gl.disable(gl.CULL_FACE); + gl.disable(gl.DEPTH_TEST); + gl.disable(gl.POLYGON_OFFSET_FILL); + gl.disable(gl.SCISSOR_TEST); + gl.disable(gl.STENCIL_TEST); + gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE); + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ZERO); + gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO); + gl.blendColor(0, 0, 0, 0); + gl.colorMask(true, true, true, true); + gl.clearColor(0, 0, 0, 0); + gl.depthMask(true); + gl.depthFunc(gl.LESS); + gl.clearDepth(1); + gl.stencilMask(4294967295); + gl.stencilFunc(gl.ALWAYS, 0, 4294967295); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + gl.clearStencil(0); + gl.cullFace(gl.BACK); + gl.frontFace(gl.CCW); + gl.polygonOffset(0, 0); + gl.activeTexture(gl.TEXTURE0); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + if (isWebGL2 === true) { + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null); + } + gl.useProgram(null); + gl.lineWidth(1); + gl.scissor(0, 0, gl.canvas.width, gl.canvas.height); + gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); + enabledCapabilities = {}; + currentTextureSlot = null; + currentBoundTextures = {}; + currentBoundFramebuffers = {}; + currentDrawbuffers = /* @__PURE__ */ new WeakMap(); + defaultDrawbuffers = []; + currentProgram = null; + currentBlendingEnabled = false; + currentBlending = null; + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor = new Color(0, 0, 0); + currentBlendAlpha = 0; + currentPremultipledAlpha = false; + currentFlipSided = null; + currentCullFace = null; + currentLineWidth = null; + currentPolygonOffsetFactor = null; + currentPolygonOffsetUnits = null; + currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height); + currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height); + colorBuffer.reset(); + depthBuffer.reset(); + stencilBuffer.reset(); + } + return { + buffers: { + color: colorBuffer, + depth: depthBuffer, + stencil: stencilBuffer + }, + enable, + disable, + bindFramebuffer, + drawBuffers, + useProgram, + setBlending, + setMaterial, + setFlipSided, + setCullFace, + setLineWidth, + setPolygonOffset, + setScissorTest, + activeTexture, + bindTexture, + unbindTexture, + compressedTexImage2D, + compressedTexImage3D, + texImage2D, + texImage3D, + updateUBOMapping, + uniformBlockBinding, + texStorage2D, + texStorage3D, + texSubImage2D, + texSubImage3D, + compressedTexSubImage2D, + compressedTexSubImage3D, + scissor, + viewport, + reset + }; + } + function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) { + const isWebGL2 = capabilities.isWebGL2; + const multisampledRTTExt = extensions.has("WEBGL_multisampled_render_to_texture") ? extensions.get("WEBGL_multisampled_render_to_texture") : null; + const supportsInvalidateFramebuffer = typeof navigator === "undefined" ? false : /OculusBrowser/g.test(navigator.userAgent); + const _videoTextures = /* @__PURE__ */ new WeakMap(); + let _canvas2; + const _sources = /* @__PURE__ */ new WeakMap(); + let useOffscreenCanvas = false; + try { + useOffscreenCanvas = typeof OffscreenCanvas !== "undefined" && new OffscreenCanvas(1, 1).getContext("2d") !== null; + } catch (err) { + } + function createCanvas(width, height) { + return useOffscreenCanvas ? ( + // eslint-disable-next-line compat/compat + new OffscreenCanvas(width, height) + ) : createElementNS("canvas"); + } + function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) { + let scale = 1; + if (image.width > maxSize || image.height > maxSize) { + scale = maxSize / Math.max(image.width, image.height); + } + if (scale < 1 || needsPowerOfTwo === true) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { + const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor; + const width = floor(scale * image.width); + const height = floor(scale * image.height); + if (_canvas2 === void 0) _canvas2 = createCanvas(width, height); + const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas2; + canvas.width = width; + canvas.height = height; + const context = canvas.getContext("2d"); + context.drawImage(image, 0, 0, width, height); + console.warn("THREE.WebGLRenderer: Texture has been resized from (" + image.width + "x" + image.height + ") to (" + width + "x" + height + ")."); + return canvas; + } else { + if ("data" in image) { + console.warn("THREE.WebGLRenderer: Image in DataTexture is too big (" + image.width + "x" + image.height + ")."); + } + return image; + } + } + return image; + } + function isPowerOfTwo$1(image) { + return isPowerOfTwo(image.width) && isPowerOfTwo(image.height); + } + function textureNeedsPowerOfTwo(texture) { + if (isWebGL2) return false; + return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; + } + function textureNeedsGenerateMipmaps(texture, supportsMips) { + return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; + } + function generateMipmap(target) { + _gl.generateMipmap(target); + } + function getInternalFormat(internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false) { + if (isWebGL2 === false) return glFormat; + if (internalFormatName !== null) { + if (_gl[internalFormatName] !== void 0) return _gl[internalFormatName]; + console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '" + internalFormatName + "'"); + } + let internalFormat = glFormat; + if (glFormat === _gl.RED) { + if (glType === _gl.FLOAT) internalFormat = _gl.R32F; + if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F; + if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8; + } + if (glFormat === _gl.RED_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8UI; + if (glType === _gl.UNSIGNED_SHORT) internalFormat = _gl.R16UI; + if (glType === _gl.UNSIGNED_INT) internalFormat = _gl.R32UI; + if (glType === _gl.BYTE) internalFormat = _gl.R8I; + if (glType === _gl.SHORT) internalFormat = _gl.R16I; + if (glType === _gl.INT) internalFormat = _gl.R32I; + } + if (glFormat === _gl.RG) { + if (glType === _gl.FLOAT) internalFormat = _gl.RG32F; + if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RG16F; + if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RG8; + } + if (glFormat === _gl.RGBA) { + const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer(colorSpace); + if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F; + if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F; + if (glType === _gl.UNSIGNED_BYTE) internalFormat = transfer === SRGBTransfer ? _gl.SRGB8_ALPHA8 : _gl.RGBA8; + if (glType === _gl.UNSIGNED_SHORT_4_4_4_4) internalFormat = _gl.RGBA4; + if (glType === _gl.UNSIGNED_SHORT_5_5_5_1) internalFormat = _gl.RGB5_A1; + } + if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) { + extensions.get("EXT_color_buffer_float"); + } + return internalFormat; + } + function getMipLevels(texture, image, supportsMips) { + if (textureNeedsGenerateMipmaps(texture, supportsMips) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) { + return Math.log2(Math.max(image.width, image.height)) + 1; + } else if (texture.mipmaps !== void 0 && texture.mipmaps.length > 0) { + return texture.mipmaps.length; + } else if (texture.isCompressedTexture && Array.isArray(texture.image)) { + return image.mipmaps.length; + } else { + return 1; + } + } + function filterFallback(f) { + if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) { + return _gl.NEAREST; + } + return _gl.LINEAR; + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + deallocateTexture(texture); + if (texture.isVideoTexture) { + _videoTextures.delete(texture); + } + } + function onRenderTargetDispose(event) { + const renderTarget = event.target; + renderTarget.removeEventListener("dispose", onRenderTargetDispose); + deallocateRenderTarget(renderTarget); + } + function deallocateTexture(texture) { + const textureProperties = properties.get(texture); + if (textureProperties.__webglInit === void 0) return; + const source = texture.source; + const webglTextures = _sources.get(source); + if (webglTextures) { + const webglTexture = webglTextures[textureProperties.__cacheKey]; + webglTexture.usedTimes--; + if (webglTexture.usedTimes === 0) { + deleteTexture(texture); + } + if (Object.keys(webglTextures).length === 0) { + _sources.delete(source); + } + } + properties.remove(texture); + } + function deleteTexture(texture) { + const textureProperties = properties.get(texture); + _gl.deleteTexture(textureProperties.__webglTexture); + const source = texture.source; + const webglTextures = _sources.get(source); + delete webglTextures[textureProperties.__cacheKey]; + info.memory.textures--; + } + function deallocateRenderTarget(renderTarget) { + const texture = renderTarget.texture; + const renderTargetProperties = properties.get(renderTarget); + const textureProperties = properties.get(texture); + if (textureProperties.__webglTexture !== void 0) { + _gl.deleteTexture(textureProperties.__webglTexture); + info.memory.textures--; + } + if (renderTarget.depthTexture) { + renderTarget.depthTexture.dispose(); + } + if (renderTarget.isWebGLCubeRenderTarget) { + for (let i = 0; i < 6; i++) { + if (Array.isArray(renderTargetProperties.__webglFramebuffer[i])) { + for (let level = 0; level < renderTargetProperties.__webglFramebuffer[i].length; level++) _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i][level]); + } else { + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]); + } + if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]); + } + } else { + if (Array.isArray(renderTargetProperties.__webglFramebuffer)) { + for (let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level++) _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[level]); + } else { + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer); + } + if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer); + if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer); + if (renderTargetProperties.__webglColorRenderbuffer) { + for (let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i++) { + if (renderTargetProperties.__webglColorRenderbuffer[i]) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer[i]); + } + } + if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer); + } + if (renderTarget.isWebGLMultipleRenderTargets) { + for (let i = 0, il = texture.length; i < il; i++) { + const attachmentProperties = properties.get(texture[i]); + if (attachmentProperties.__webglTexture) { + _gl.deleteTexture(attachmentProperties.__webglTexture); + info.memory.textures--; + } + properties.remove(texture[i]); + } + } + properties.remove(texture); + properties.remove(renderTarget); + } + let textureUnits = 0; + function resetTextureUnits() { + textureUnits = 0; + } + function allocateTextureUnit() { + const textureUnit = textureUnits; + if (textureUnit >= capabilities.maxTextures) { + console.warn("THREE.WebGLTextures: Trying to use " + textureUnit + " texture units while this GPU supports only " + capabilities.maxTextures); + } + textureUnits += 1; + return textureUnit; + } + function getTextureCacheKey(texture) { + const array = []; + array.push(texture.wrapS); + array.push(texture.wrapT); + array.push(texture.wrapR || 0); + array.push(texture.magFilter); + array.push(texture.minFilter); + array.push(texture.anisotropy); + array.push(texture.internalFormat); + array.push(texture.format); + array.push(texture.type); + array.push(texture.generateMipmaps); + array.push(texture.premultiplyAlpha); + array.push(texture.flipY); + array.push(texture.unpackAlignment); + array.push(texture.colorSpace); + return array.join(); + } + function setTexture2D(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.isVideoTexture) updateVideoTexture(texture); + if (texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version) { + const image = texture.image; + if (image === null) { + console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found."); + } else if (image.complete === false) { + console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete"); + } else { + uploadTexture(textureProperties, texture, slot); + return; + } + } + state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTexture2DArray(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTexture3D(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTextureCube(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadCubeTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + const wrappingToGL = { + [RepeatWrapping]: _gl.REPEAT, + [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE, + [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT + }; + const filterToGL = { + [NearestFilter]: _gl.NEAREST, + [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST, + [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR, + [LinearFilter]: _gl.LINEAR, + [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST, + [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR + }; + const compareToGL = { + [NeverCompare]: _gl.NEVER, + [AlwaysCompare]: _gl.ALWAYS, + [LessCompare]: _gl.LESS, + [LessEqualCompare]: _gl.LEQUAL, + [EqualCompare]: _gl.EQUAL, + [GreaterEqualCompare]: _gl.GEQUAL, + [GreaterCompare]: _gl.GREATER, + [NotEqualCompare]: _gl.NOTEQUAL + }; + function setTextureParameters(textureType, texture, supportsMips) { + if (supportsMips) { + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]); + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]); + if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) { + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]); + } + _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]); + _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]); + } else { + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE); + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE); + if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) { + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE); + } + if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) { + console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."); + } + _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter)); + _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter)); + if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) { + console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter."); + } + } + if (texture.compareFunction) { + _gl.texParameteri(textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE); + _gl.texParameteri(textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[texture.compareFunction]); + } + if (extensions.has("EXT_texture_filter_anisotropic") === true) { + const extension = extensions.get("EXT_texture_filter_anisotropic"); + if (texture.magFilter === NearestFilter) return; + if (texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter) return; + if (texture.type === FloatType && extensions.has("OES_texture_float_linear") === false) return; + if (isWebGL2 === false && (texture.type === HalfFloatType && extensions.has("OES_texture_half_float_linear") === false)) return; + if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) { + _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy())); + properties.get(texture).__currentAnisotropy = texture.anisotropy; + } + } + } + function initTexture(textureProperties, texture) { + let forceUpload = false; + if (textureProperties.__webglInit === void 0) { + textureProperties.__webglInit = true; + texture.addEventListener("dispose", onTextureDispose); + } + const source = texture.source; + let webglTextures = _sources.get(source); + if (webglTextures === void 0) { + webglTextures = {}; + _sources.set(source, webglTextures); + } + const textureCacheKey = getTextureCacheKey(texture); + if (textureCacheKey !== textureProperties.__cacheKey) { + if (webglTextures[textureCacheKey] === void 0) { + webglTextures[textureCacheKey] = { + texture: _gl.createTexture(), + usedTimes: 0 + }; + info.memory.textures++; + forceUpload = true; + } + webglTextures[textureCacheKey].usedTimes++; + const webglTexture = webglTextures[textureProperties.__cacheKey]; + if (webglTexture !== void 0) { + webglTextures[textureProperties.__cacheKey].usedTimes--; + if (webglTexture.usedTimes === 0) { + deleteTexture(texture); + } + } + textureProperties.__cacheKey = textureCacheKey; + textureProperties.__webglTexture = webglTextures[textureCacheKey].texture; + } + return forceUpload; + } + function uploadTexture(textureProperties, texture, slot) { + let textureType = _gl.TEXTURE_2D; + if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) textureType = _gl.TEXTURE_2D_ARRAY; + if (texture.isData3DTexture) textureType = _gl.TEXTURE_3D; + const forceUpload = initTexture(textureProperties, texture); + const source = texture.source; + state.bindTexture(textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + const sourceProperties = properties.get(source); + if (source.version !== sourceProperties.__version || forceUpload === true) { + state.activeTexture(_gl.TEXTURE0 + slot); + const workingPrimaries = ColorManagement.getPrimaries(ColorManagement.workingColorSpace); + const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries(texture.colorSpace); + const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment); + _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion); + const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false; + let image = resizeImage(texture.image, needsPowerOfTwo, false, capabilities.maxTextureSize); + image = verifyColorSpace(texture, image); + const supportsMips = isPowerOfTwo$1(image) || isWebGL2, glFormat = utils.convert(texture.format, texture.colorSpace); + let glType = utils.convert(texture.type), glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture); + setTextureParameters(textureType, texture, supportsMips); + let mipmap; + const mipmaps = texture.mipmaps; + const useTexStorage = isWebGL2 && texture.isVideoTexture !== true && glInternalFormat !== RGB_ETC1_Format; + const allocateMemory = sourceProperties.__version === void 0 || forceUpload === true; + const levels = getMipLevels(texture, image, supportsMips); + if (texture.isDepthTexture) { + glInternalFormat = _gl.DEPTH_COMPONENT; + if (isWebGL2) { + if (texture.type === FloatType) { + glInternalFormat = _gl.DEPTH_COMPONENT32F; + } else if (texture.type === UnsignedIntType) { + glInternalFormat = _gl.DEPTH_COMPONENT24; + } else if (texture.type === UnsignedInt248Type) { + glInternalFormat = _gl.DEPTH24_STENCIL8; + } else { + glInternalFormat = _gl.DEPTH_COMPONENT16; + } + } else { + if (texture.type === FloatType) { + console.error("WebGLRenderer: Floating point depth texture requires WebGL2."); + } + } + if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) { + if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) { + console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."); + texture.type = UnsignedIntType; + glType = utils.convert(texture.type); + } + } + if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) { + glInternalFormat = _gl.DEPTH_STENCIL; + if (texture.type !== UnsignedInt248Type) { + console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."); + texture.type = UnsignedInt248Type; + glType = utils.convert(texture.type); + } + } + if (allocateMemory) { + if (useTexStorage) { + state.texStorage2D(_gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height); + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null); + } + } + } else if (texture.isDataTexture) { + if (mipmaps.length > 0 && supportsMips) { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); + } + for (let i = 0, il = mipmaps.length; i < il; i++) { + mipmap = mipmaps[i]; + if (useTexStorage) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + texture.generateMipmaps = false; + } else { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); + } + state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data); + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data); + } + } + } else if (texture.isCompressedTexture) { + if (texture.isCompressedArrayTexture) { + if (useTexStorage && allocateMemory) { + state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height, image.depth); + } + for (let i = 0, il = mipmaps.length; i < il; i++) { + mipmap = mipmaps[i]; + if (texture.format !== RGBAFormat) { + if (glFormat !== null) { + if (useTexStorage) { + state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0); + } else { + state.compressedTexImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); + } + } else { + if (useTexStorage) { + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data); + } else { + state.texImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data); + } + } + } + } else { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); + } + for (let i = 0, il = mipmaps.length; i < il; i++) { + mipmap = mipmaps[i]; + if (texture.format !== RGBAFormat) { + if (glFormat !== null) { + if (useTexStorage) { + state.compressedTexSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); + } else { + state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); + } + } else { + if (useTexStorage) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + } + } + } else if (texture.isDataArrayTexture) { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth); + } + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); + } else { + state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); + } + } else if (texture.isData3DTexture) { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth); + } + state.texSubImage3D(_gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); + } else { + state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); + } + } else if (texture.isFramebufferTexture) { + if (allocateMemory) { + if (useTexStorage) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); + } else { + let width = image.width, height = image.height; + for (let i = 0; i < levels; i++) { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null); + width >>= 1; + height >>= 1; + } + } + } + } else { + if (mipmaps.length > 0 && supportsMips) { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); + } + for (let i = 0, il = mipmaps.length; i < il; i++) { + mipmap = mipmaps[i]; + if (useTexStorage) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap); + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap); + } + } + texture.generateMipmaps = false; + } else { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); + } + state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image); + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image); + } + } + } + if (textureNeedsGenerateMipmaps(texture, supportsMips)) { + generateMipmap(textureType); + } + sourceProperties.__version = source.version; + if (texture.onUpdate) texture.onUpdate(texture); + } + textureProperties.__version = texture.version; + } + function uploadCubeTexture(textureProperties, texture, slot) { + if (texture.image.length !== 6) return; + const forceUpload = initTexture(textureProperties, texture); + const source = texture.source; + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + const sourceProperties = properties.get(source); + if (source.version !== sourceProperties.__version || forceUpload === true) { + state.activeTexture(_gl.TEXTURE0 + slot); + const workingPrimaries = ColorManagement.getPrimaries(ColorManagement.workingColorSpace); + const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries(texture.colorSpace); + const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment); + _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion); + const isCompressed = texture.isCompressedTexture || texture.image[0].isCompressedTexture; + const isDataTexture = texture.image[0] && texture.image[0].isDataTexture; + const cubeImage = []; + for (let i = 0; i < 6; i++) { + if (!isCompressed && !isDataTexture) { + cubeImage[i] = resizeImage(texture.image[i], false, true, capabilities.maxCubemapSize); + } else { + cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i]; + } + cubeImage[i] = verifyColorSpace(texture, cubeImage[i]); + } + const image = cubeImage[0], supportsMips = isPowerOfTwo$1(image) || isWebGL2, glFormat = utils.convert(texture.format, texture.colorSpace), glType = utils.convert(texture.type), glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const useTexStorage = isWebGL2 && texture.isVideoTexture !== true; + const allocateMemory = sourceProperties.__version === void 0 || forceUpload === true; + let levels = getMipLevels(texture, image, supportsMips); + setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips); + let mipmaps; + if (isCompressed) { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height); + } + for (let i = 0; i < 6; i++) { + mipmaps = cubeImage[i].mipmaps; + for (let j = 0; j < mipmaps.length; j++) { + const mipmap = mipmaps[j]; + if (texture.format !== RGBAFormat) { + if (glFormat !== null) { + if (useTexStorage) { + state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); + } else { + state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"); + } + } else { + if (useTexStorage) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + } + } + } else { + mipmaps = texture.mipmaps; + if (useTexStorage && allocateMemory) { + if (mipmaps.length > 0) levels++; + state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[0].width, cubeImage[0].height); + } + for (let i = 0; i < 6; i++) { + if (isDataTexture) { + if (useTexStorage) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[i].width, cubeImage[i].height, glFormat, glType, cubeImage[i].data); + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data); + } + for (let j = 0; j < mipmaps.length; j++) { + const mipmap = mipmaps[j]; + const mipmapImage = mipmap.image[i].image; + if (useTexStorage) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data); + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data); + } + } + } else { + if (useTexStorage) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[i]); + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]); + } + for (let j = 0; j < mipmaps.length; j++) { + const mipmap = mipmaps[j]; + if (useTexStorage) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[i]); + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]); + } + } + } + } + } + if (textureNeedsGenerateMipmaps(texture, supportsMips)) { + generateMipmap(_gl.TEXTURE_CUBE_MAP); + } + sourceProperties.__version = source.version; + if (texture.onUpdate) texture.onUpdate(texture); + } + textureProperties.__version = texture.version; + } + function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget, level) { + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const renderTargetProperties = properties.get(renderTarget); + if (!renderTargetProperties.__hasExternalTextures) { + const width = Math.max(1, renderTarget.width >> level); + const height = Math.max(1, renderTarget.height >> level); + if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) { + state.texImage3D(textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null); + } else { + state.texImage2D(textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null); + } + } + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0, getRenderTargetSamples(renderTarget)); + } else if (textureTarget === _gl.TEXTURE_2D || textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z) { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, level); + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) { + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) { + let glInternalFormat = isWebGL2 === true ? _gl.DEPTH_COMPONENT24 : _gl.DEPTH_COMPONENT16; + if (isMultisample || useMultisampledRTT(renderTarget)) { + const depthTexture = renderTarget.depthTexture; + if (depthTexture && depthTexture.isDepthTexture) { + if (depthTexture.type === FloatType) { + glInternalFormat = _gl.DEPTH_COMPONENT32F; + } else if (depthTexture.type === UnsignedIntType) { + glInternalFormat = _gl.DEPTH_COMPONENT24; + } + } + const samples = getRenderTargetSamples(renderTarget); + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else { + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } + } else { + _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height); + } + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer); + } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) { + const samples = getRenderTargetSamples(renderTarget); + if (isMultisample && useMultisampledRTT(renderTarget) === false) { + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height); + } else if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height); + } else { + _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height); + } + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer); + } else { + const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture]; + for (let i = 0; i < textures.length; i++) { + const texture = textures[i]; + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const samples = getRenderTargetSamples(renderTarget); + if (isMultisample && useMultisampledRTT(renderTarget) === false) { + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else { + _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height); + } + } + } + _gl.bindRenderbuffer(_gl.RENDERBUFFER, null); + } + function setupDepthTexture(framebuffer, renderTarget) { + const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget; + if (isCube) throw new Error("Depth Texture with cube render targets is not supported"); + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) { + throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture"); + } + if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) { + renderTarget.depthTexture.image.width = renderTarget.width; + renderTarget.depthTexture.image.height = renderTarget.height; + renderTarget.depthTexture.needsUpdate = true; + } + setTexture2D(renderTarget.depthTexture, 0); + const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture; + const samples = getRenderTargetSamples(renderTarget); + if (renderTarget.depthTexture.format === DepthFormat) { + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples); + } else { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0); + } + } else if (renderTarget.depthTexture.format === DepthStencilFormat) { + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples); + } else { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0); + } + } else { + throw new Error("Unknown depthTexture format"); + } + } + function setupDepthRenderbuffer(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) { + if (isCube) throw new Error("target.depthTexture not supported in Cube render targets"); + setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget); + } else { + if (isCube) { + renderTargetProperties.__webglDepthbuffer = []; + for (let i = 0; i < 6; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]); + renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false); + } + } else { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false); + } + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + function rebindTextures(renderTarget, colorTexture, depthTexture) { + const renderTargetProperties = properties.get(renderTarget); + if (colorTexture !== void 0) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0); + } + if (depthTexture !== void 0) { + setupDepthRenderbuffer(renderTarget); + } + } + function setupRenderTarget(renderTarget) { + const texture = renderTarget.texture; + const renderTargetProperties = properties.get(renderTarget); + const textureProperties = properties.get(texture); + renderTarget.addEventListener("dispose", onRenderTargetDispose); + if (renderTarget.isWebGLMultipleRenderTargets !== true) { + if (textureProperties.__webglTexture === void 0) { + textureProperties.__webglTexture = _gl.createTexture(); + } + textureProperties.__version = texture.version; + info.memory.textures++; + } + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true; + const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; + if (isCube) { + renderTargetProperties.__webglFramebuffer = []; + for (let i = 0; i < 6; i++) { + if (isWebGL2 && texture.mipmaps && texture.mipmaps.length > 0) { + renderTargetProperties.__webglFramebuffer[i] = []; + for (let level = 0; level < texture.mipmaps.length; level++) { + renderTargetProperties.__webglFramebuffer[i][level] = _gl.createFramebuffer(); + } + } else { + renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer(); + } + } + } else { + if (isWebGL2 && texture.mipmaps && texture.mipmaps.length > 0) { + renderTargetProperties.__webglFramebuffer = []; + for (let level = 0; level < texture.mipmaps.length; level++) { + renderTargetProperties.__webglFramebuffer[level] = _gl.createFramebuffer(); + } + } else { + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + } + if (isMultipleRenderTargets) { + if (capabilities.drawBuffers) { + const textures = renderTarget.texture; + for (let i = 0, il = textures.length; i < il; i++) { + const attachmentProperties = properties.get(textures[i]); + if (attachmentProperties.__webglTexture === void 0) { + attachmentProperties.__webglTexture = _gl.createTexture(); + info.memory.textures++; + } + } + } else { + console.warn("THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension."); + } + } + if (isWebGL2 && renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) { + const textures = isMultipleRenderTargets ? texture : [texture]; + renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); + renderTargetProperties.__webglColorRenderbuffer = []; + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + for (let i = 0; i < textures.length; i++) { + const texture2 = textures[i]; + renderTargetProperties.__webglColorRenderbuffer[i] = _gl.createRenderbuffer(); + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const glFormat = utils.convert(texture2.format, texture2.colorSpace); + const glType = utils.convert(texture2.type); + const glInternalFormat = getInternalFormat(texture2.internalFormat, glFormat, glType, texture2.colorSpace, renderTarget.isXRRenderTarget === true); + const samples = getRenderTargetSamples(renderTarget); + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + } + _gl.bindRenderbuffer(_gl.RENDERBUFFER, null); + if (renderTarget.depthBuffer) { + renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true); + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + } + if (isCube) { + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture); + setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips); + for (let i = 0; i < 6; i++) { + if (isWebGL2 && texture.mipmaps && texture.mipmaps.length > 0) { + for (let level = 0; level < texture.mipmaps.length; level++) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i][level], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level); + } + } else { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0); + } + } + if (textureNeedsGenerateMipmaps(texture, supportsMips)) { + generateMipmap(_gl.TEXTURE_CUBE_MAP); + } + state.unbindTexture(); + } else if (isMultipleRenderTargets) { + const textures = renderTarget.texture; + for (let i = 0, il = textures.length; i < il; i++) { + const attachment = textures[i]; + const attachmentProperties = properties.get(attachment); + state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture); + setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips); + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0); + if (textureNeedsGenerateMipmaps(attachment, supportsMips)) { + generateMipmap(_gl.TEXTURE_2D); + } + } + state.unbindTexture(); + } else { + let glTextureType = _gl.TEXTURE_2D; + if (renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) { + if (isWebGL2) { + glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY; + } else { + console.error("THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2."); + } + } + state.bindTexture(glTextureType, textureProperties.__webglTexture); + setTextureParameters(glTextureType, texture, supportsMips); + if (isWebGL2 && texture.mipmaps && texture.mipmaps.length > 0) { + for (let level = 0; level < texture.mipmaps.length; level++) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[level], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level); + } + } else { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0); + } + if (textureNeedsGenerateMipmaps(texture, supportsMips)) { + generateMipmap(glTextureType); + } + state.unbindTexture(); + } + if (renderTarget.depthBuffer) { + setupDepthRenderbuffer(renderTarget); + } + } + function updateRenderTargetMipmap(renderTarget) { + const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; + const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture]; + for (let i = 0, il = textures.length; i < il; i++) { + const texture = textures[i]; + if (textureNeedsGenerateMipmaps(texture, supportsMips)) { + const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; + const webglTexture = properties.get(texture).__webglTexture; + state.bindTexture(target, webglTexture); + generateMipmap(target); + state.unbindTexture(); + } + } + } + function updateMultisampleRenderTarget(renderTarget) { + if (isWebGL2 && renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) { + const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [renderTarget.texture]; + const width = renderTarget.width; + const height = renderTarget.height; + let mask = _gl.COLOR_BUFFER_BIT; + const invalidationArray = []; + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderTargetProperties = properties.get(renderTarget); + const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true; + if (isMultipleRenderTargets) { + for (let i = 0; i < textures.length; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null); + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + for (let i = 0; i < textures.length; i++) { + invalidationArray.push(_gl.COLOR_ATTACHMENT0 + i); + if (renderTarget.depthBuffer) { + invalidationArray.push(depthStyle); + } + const ignoreDepthValues = renderTargetProperties.__ignoreDepthValues !== void 0 ? renderTargetProperties.__ignoreDepthValues : false; + if (ignoreDepthValues === false) { + if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT; + if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT; + } + if (isMultipleRenderTargets) { + _gl.framebufferRenderbuffer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + } + if (ignoreDepthValues === true) { + _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, [depthStyle]); + _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]); + } + if (isMultipleRenderTargets) { + const webglTexture = properties.get(textures[i]).__webglTexture; + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0); + } + _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST); + if (supportsInvalidateFramebuffer) { + _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArray); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + if (isMultipleRenderTargets) { + for (let i = 0; i < textures.length; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const webglTexture = properties.get(textures[i]).__webglTexture; + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0); + } + } + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + } + } + function getRenderTargetSamples(renderTarget) { + return Math.min(capabilities.maxSamples, renderTarget.samples); + } + function useMultisampledRTT(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + return isWebGL2 && renderTarget.samples > 0 && extensions.has("WEBGL_multisampled_render_to_texture") === true && renderTargetProperties.__useRenderToTexture !== false; + } + function updateVideoTexture(texture) { + const frame = info.render.frame; + if (_videoTextures.get(texture) !== frame) { + _videoTextures.set(texture, frame); + texture.update(); + } + } + function verifyColorSpace(texture, image) { + const colorSpace = texture.colorSpace; + const format = texture.format; + const type = texture.type; + if (texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat) return image; + if (colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace) { + if (ColorManagement.getTransfer(colorSpace) === SRGBTransfer) { + if (isWebGL2 === false) { + if (extensions.has("EXT_sRGB") === true && format === RGBAFormat) { + texture.format = _SRGBAFormat; + texture.minFilter = LinearFilter; + texture.generateMipmaps = false; + } else { + image = ImageUtils.sRGBToLinear(image); + } + } else { + if (format !== RGBAFormat || type !== UnsignedByteType) { + console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."); + } + } + } else { + console.error("THREE.WebGLTextures: Unsupported texture color space:", colorSpace); + } + } + return image; + } + this.allocateTextureUnit = allocateTextureUnit; + this.resetTextureUnits = resetTextureUnits; + this.setTexture2D = setTexture2D; + this.setTexture2DArray = setTexture2DArray; + this.setTexture3D = setTexture3D; + this.setTextureCube = setTextureCube; + this.rebindTextures = rebindTextures; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; + this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; + this.setupDepthRenderbuffer = setupDepthRenderbuffer; + this.setupFrameBufferTexture = setupFrameBufferTexture; + this.useMultisampledRTT = useMultisampledRTT; + } + function WebGLUtils(gl, extensions, capabilities) { + const isWebGL2 = capabilities.isWebGL2; + function convert(p, colorSpace = NoColorSpace) { + let extension; + const transfer = ColorManagement.getTransfer(colorSpace); + if (p === UnsignedByteType) return gl.UNSIGNED_BYTE; + if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4; + if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1; + if (p === ByteType) return gl.BYTE; + if (p === ShortType) return gl.SHORT; + if (p === UnsignedShortType) return gl.UNSIGNED_SHORT; + if (p === IntType) return gl.INT; + if (p === UnsignedIntType) return gl.UNSIGNED_INT; + if (p === FloatType) return gl.FLOAT; + if (p === HalfFloatType) { + if (isWebGL2) return gl.HALF_FLOAT; + extension = extensions.get("OES_texture_half_float"); + if (extension !== null) { + return extension.HALF_FLOAT_OES; + } else { + return null; + } + } + if (p === AlphaFormat) return gl.ALPHA; + if (p === RGBAFormat) return gl.RGBA; + if (p === LuminanceFormat) return gl.LUMINANCE; + if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA; + if (p === DepthFormat) return gl.DEPTH_COMPONENT; + if (p === DepthStencilFormat) return gl.DEPTH_STENCIL; + if (p === _SRGBAFormat) { + extension = extensions.get("EXT_sRGB"); + if (extension !== null) { + return extension.SRGB_ALPHA_EXT; + } else { + return null; + } + } + if (p === RedFormat) return gl.RED; + if (p === RedIntegerFormat) return gl.RED_INTEGER; + if (p === RGFormat) return gl.RG; + if (p === RGIntegerFormat) return gl.RG_INTEGER; + if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER; + if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) { + if (transfer === SRGBTransfer) { + extension = extensions.get("WEBGL_compressed_texture_s3tc_srgb"); + if (extension !== null) { + if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + } else { + return null; + } + } else { + extension = extensions.get("WEBGL_compressed_texture_s3tc"); + if (extension !== null) { + if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; + } else { + return null; + } + } + } + if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) { + extension = extensions.get("WEBGL_compressed_texture_pvrtc"); + if (extension !== null) { + if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + } else { + return null; + } + } + if (p === RGB_ETC1_Format) { + extension = extensions.get("WEBGL_compressed_texture_etc1"); + if (extension !== null) { + return extension.COMPRESSED_RGB_ETC1_WEBGL; + } else { + return null; + } + } + if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) { + extension = extensions.get("WEBGL_compressed_texture_etc"); + if (extension !== null) { + if (p === RGB_ETC2_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2; + if (p === RGBA_ETC2_EAC_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC; + } else { + return null; + } + } + if (p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format) { + extension = extensions.get("WEBGL_compressed_texture_astc"); + if (extension !== null) { + if (p === RGBA_ASTC_4x4_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR; + if (p === RGBA_ASTC_5x4_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR; + if (p === RGBA_ASTC_5x5_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR; + if (p === RGBA_ASTC_6x5_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR; + if (p === RGBA_ASTC_6x6_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR; + if (p === RGBA_ASTC_8x5_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR; + if (p === RGBA_ASTC_8x6_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR; + if (p === RGBA_ASTC_8x8_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR; + if (p === RGBA_ASTC_10x5_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR; + if (p === RGBA_ASTC_10x6_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR; + if (p === RGBA_ASTC_10x8_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR; + if (p === RGBA_ASTC_10x10_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR; + if (p === RGBA_ASTC_12x10_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR; + if (p === RGBA_ASTC_12x12_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR; + } else { + return null; + } + } + if (p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format) { + extension = extensions.get("EXT_texture_compression_bptc"); + if (extension !== null) { + if (p === RGBA_BPTC_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT; + if (p === RGB_BPTC_SIGNED_Format) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT; + if (p === RGB_BPTC_UNSIGNED_Format) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT; + } else { + return null; + } + } + if (p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format) { + extension = extensions.get("EXT_texture_compression_rgtc"); + if (extension !== null) { + if (p === RGBA_BPTC_Format) return extension.COMPRESSED_RED_RGTC1_EXT; + if (p === SIGNED_RED_RGTC1_Format) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT; + if (p === RED_GREEN_RGTC2_Format) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT; + if (p === SIGNED_RED_GREEN_RGTC2_Format) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT; + } else { + return null; + } + } + if (p === UnsignedInt248Type) { + if (isWebGL2) return gl.UNSIGNED_INT_24_8; + extension = extensions.get("WEBGL_depth_texture"); + if (extension !== null) { + return extension.UNSIGNED_INT_24_8_WEBGL; + } else { + return null; + } + } + return gl[p] !== void 0 ? gl[p] : null; + } + return { convert }; + } + var ArrayCamera = class extends PerspectiveCamera { + constructor(array = []) { + super(); + this.isArrayCamera = true; + this.cameras = array; + } + }; + var Group = class extends Object3D { + constructor() { + super(); + this.isGroup = true; + this.type = "Group"; + } + }; + var _moveEvent = { type: "move" }; + var WebXRController = class { + constructor() { + this._targetRay = null; + this._grip = null; + this._hand = null; + } + getHandSpace() { + if (this._hand === null) { + this._hand = new Group(); + this._hand.matrixAutoUpdate = false; + this._hand.visible = false; + this._hand.joints = {}; + this._hand.inputState = { pinching: false }; + } + return this._hand; + } + getTargetRaySpace() { + if (this._targetRay === null) { + this._targetRay = new Group(); + this._targetRay.matrixAutoUpdate = false; + this._targetRay.visible = false; + this._targetRay.hasLinearVelocity = false; + this._targetRay.linearVelocity = new Vector3(); + this._targetRay.hasAngularVelocity = false; + this._targetRay.angularVelocity = new Vector3(); + } + return this._targetRay; + } + getGripSpace() { + if (this._grip === null) { + this._grip = new Group(); + this._grip.matrixAutoUpdate = false; + this._grip.visible = false; + this._grip.hasLinearVelocity = false; + this._grip.linearVelocity = new Vector3(); + this._grip.hasAngularVelocity = false; + this._grip.angularVelocity = new Vector3(); + } + return this._grip; + } + dispatchEvent(event) { + if (this._targetRay !== null) { + this._targetRay.dispatchEvent(event); + } + if (this._grip !== null) { + this._grip.dispatchEvent(event); + } + if (this._hand !== null) { + this._hand.dispatchEvent(event); + } + return this; + } + connect(inputSource) { + if (inputSource && inputSource.hand) { + const hand = this._hand; + if (hand) { + for (const inputjoint of inputSource.hand.values()) { + this._getHandJoint(hand, inputjoint); + } + } + } + this.dispatchEvent({ type: "connected", data: inputSource }); + return this; + } + disconnect(inputSource) { + this.dispatchEvent({ type: "disconnected", data: inputSource }); + if (this._targetRay !== null) { + this._targetRay.visible = false; + } + if (this._grip !== null) { + this._grip.visible = false; + } + if (this._hand !== null) { + this._hand.visible = false; + } + return this; + } + update(inputSource, frame, referenceSpace) { + let inputPose = null; + let gripPose = null; + let handPose = null; + const targetRay = this._targetRay; + const grip = this._grip; + const hand = this._hand; + if (inputSource && frame.session.visibilityState !== "visible-blurred") { + if (hand && inputSource.hand) { + handPose = true; + for (const inputjoint of inputSource.hand.values()) { + const jointPose = frame.getJointPose(inputjoint, referenceSpace); + const joint = this._getHandJoint(hand, inputjoint); + if (jointPose !== null) { + joint.matrix.fromArray(jointPose.transform.matrix); + joint.matrix.decompose(joint.position, joint.rotation, joint.scale); + joint.matrixWorldNeedsUpdate = true; + joint.jointRadius = jointPose.radius; + } + joint.visible = jointPose !== null; + } + const indexTip = hand.joints["index-finger-tip"]; + const thumbTip = hand.joints["thumb-tip"]; + const distance = indexTip.position.distanceTo(thumbTip.position); + const distanceToPinch = 0.02; + const threshold = 5e-3; + if (hand.inputState.pinching && distance > distanceToPinch + threshold) { + hand.inputState.pinching = false; + this.dispatchEvent({ + type: "pinchend", + handedness: inputSource.handedness, + target: this + }); + } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) { + hand.inputState.pinching = true; + this.dispatchEvent({ + type: "pinchstart", + handedness: inputSource.handedness, + target: this + }); + } + } else { + if (grip !== null && inputSource.gripSpace) { + gripPose = frame.getPose(inputSource.gripSpace, referenceSpace); + if (gripPose !== null) { + grip.matrix.fromArray(gripPose.transform.matrix); + grip.matrix.decompose(grip.position, grip.rotation, grip.scale); + grip.matrixWorldNeedsUpdate = true; + if (gripPose.linearVelocity) { + grip.hasLinearVelocity = true; + grip.linearVelocity.copy(gripPose.linearVelocity); + } else { + grip.hasLinearVelocity = false; + } + if (gripPose.angularVelocity) { + grip.hasAngularVelocity = true; + grip.angularVelocity.copy(gripPose.angularVelocity); + } else { + grip.hasAngularVelocity = false; + } + } + } + } + if (targetRay !== null) { + inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace); + if (inputPose === null && gripPose !== null) { + inputPose = gripPose; + } + if (inputPose !== null) { + targetRay.matrix.fromArray(inputPose.transform.matrix); + targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale); + targetRay.matrixWorldNeedsUpdate = true; + if (inputPose.linearVelocity) { + targetRay.hasLinearVelocity = true; + targetRay.linearVelocity.copy(inputPose.linearVelocity); + } else { + targetRay.hasLinearVelocity = false; + } + if (inputPose.angularVelocity) { + targetRay.hasAngularVelocity = true; + targetRay.angularVelocity.copy(inputPose.angularVelocity); + } else { + targetRay.hasAngularVelocity = false; + } + this.dispatchEvent(_moveEvent); + } + } + } + if (targetRay !== null) { + targetRay.visible = inputPose !== null; + } + if (grip !== null) { + grip.visible = gripPose !== null; + } + if (hand !== null) { + hand.visible = handPose !== null; + } + return this; + } + // private method + _getHandJoint(hand, inputjoint) { + if (hand.joints[inputjoint.jointName] === void 0) { + const joint = new Group(); + joint.matrixAutoUpdate = false; + joint.visible = false; + hand.joints[inputjoint.jointName] = joint; + hand.add(joint); + } + return hand.joints[inputjoint.jointName]; + } + }; + var WebXRManager = class extends EventDispatcher { + constructor(renderer, gl) { + super(); + const scope = this; + let session = null; + let framebufferScaleFactor = 1; + let referenceSpace = null; + let referenceSpaceType = "local-floor"; + let foveation = 1; + let customReferenceSpace = null; + let pose = null; + let glBinding = null; + let glProjLayer = null; + let glBaseLayer = null; + let xrFrame = null; + const attributes = gl.getContextAttributes(); + let initialRenderTarget = null; + let newRenderTarget = null; + const controllers = []; + const controllerInputSources = []; + const currentSize = new Vector2(); + let currentPixelRatio = null; + const cameraL = new PerspectiveCamera(); + cameraL.layers.enable(1); + cameraL.viewport = new Vector4(); + const cameraR = new PerspectiveCamera(); + cameraR.layers.enable(2); + cameraR.viewport = new Vector4(); + const cameras = [cameraL, cameraR]; + const cameraXR = new ArrayCamera(); + cameraXR.layers.enable(1); + cameraXR.layers.enable(2); + let _currentDepthNear = null; + let _currentDepthFar = null; + this.cameraAutoUpdate = true; + this.enabled = false; + this.isPresenting = false; + this.getController = function(index) { + let controller = controllers[index]; + if (controller === void 0) { + controller = new WebXRController(); + controllers[index] = controller; + } + return controller.getTargetRaySpace(); + }; + this.getControllerGrip = function(index) { + let controller = controllers[index]; + if (controller === void 0) { + controller = new WebXRController(); + controllers[index] = controller; + } + return controller.getGripSpace(); + }; + this.getHand = function(index) { + let controller = controllers[index]; + if (controller === void 0) { + controller = new WebXRController(); + controllers[index] = controller; + } + return controller.getHandSpace(); + }; + function onSessionEvent(event) { + const controllerIndex = controllerInputSources.indexOf(event.inputSource); + if (controllerIndex === -1) { + return; + } + const controller = controllers[controllerIndex]; + if (controller !== void 0) { + controller.update(event.inputSource, event.frame, customReferenceSpace || referenceSpace); + controller.dispatchEvent({ type: event.type, data: event.inputSource }); + } + } + function onSessionEnd() { + session.removeEventListener("select", onSessionEvent); + session.removeEventListener("selectstart", onSessionEvent); + session.removeEventListener("selectend", onSessionEvent); + session.removeEventListener("squeeze", onSessionEvent); + session.removeEventListener("squeezestart", onSessionEvent); + session.removeEventListener("squeezeend", onSessionEvent); + session.removeEventListener("end", onSessionEnd); + session.removeEventListener("inputsourceschange", onInputSourcesChange); + for (let i = 0; i < controllers.length; i++) { + const inputSource = controllerInputSources[i]; + if (inputSource === null) continue; + controllerInputSources[i] = null; + controllers[i].disconnect(inputSource); + } + _currentDepthNear = null; + _currentDepthFar = null; + renderer.setRenderTarget(initialRenderTarget); + glBaseLayer = null; + glProjLayer = null; + glBinding = null; + session = null; + newRenderTarget = null; + animation.stop(); + scope.isPresenting = false; + renderer.setPixelRatio(currentPixelRatio); + renderer.setSize(currentSize.width, currentSize.height, false); + scope.dispatchEvent({ type: "sessionend" }); + } + this.setFramebufferScaleFactor = function(value) { + framebufferScaleFactor = value; + if (scope.isPresenting === true) { + console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting."); + } + }; + this.setReferenceSpaceType = function(value) { + referenceSpaceType = value; + if (scope.isPresenting === true) { + console.warn("THREE.WebXRManager: Cannot change reference space type while presenting."); + } + }; + this.getReferenceSpace = function() { + return customReferenceSpace || referenceSpace; + }; + this.setReferenceSpace = function(space) { + customReferenceSpace = space; + }; + this.getBaseLayer = function() { + return glProjLayer !== null ? glProjLayer : glBaseLayer; + }; + this.getBinding = function() { + return glBinding; + }; + this.getFrame = function() { + return xrFrame; + }; + this.getSession = function() { + return session; + }; + this.setSession = async function(value) { + session = value; + if (session !== null) { + initialRenderTarget = renderer.getRenderTarget(); + session.addEventListener("select", onSessionEvent); + session.addEventListener("selectstart", onSessionEvent); + session.addEventListener("selectend", onSessionEvent); + session.addEventListener("squeeze", onSessionEvent); + session.addEventListener("squeezestart", onSessionEvent); + session.addEventListener("squeezeend", onSessionEvent); + session.addEventListener("end", onSessionEnd); + session.addEventListener("inputsourceschange", onInputSourcesChange); + if (attributes.xrCompatible !== true) { + await gl.makeXRCompatible(); + } + currentPixelRatio = renderer.getPixelRatio(); + renderer.getSize(currentSize); + if (session.renderState.layers === void 0 || renderer.capabilities.isWebGL2 === false) { + const layerInit = { + antialias: session.renderState.layers === void 0 ? attributes.antialias : true, + alpha: true, + depth: attributes.depth, + stencil: attributes.stencil, + framebufferScaleFactor + }; + glBaseLayer = new XRWebGLLayer(session, gl, layerInit); + session.updateRenderState({ baseLayer: glBaseLayer }); + renderer.setPixelRatio(1); + renderer.setSize(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false); + newRenderTarget = new WebGLRenderTarget( + glBaseLayer.framebufferWidth, + glBaseLayer.framebufferHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + colorSpace: renderer.outputColorSpace, + stencilBuffer: attributes.stencil + } + ); + } else { + let depthFormat = null; + let depthType = null; + let glDepthFormat = null; + if (attributes.depth) { + glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24; + depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat; + depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType; + } + const projectionlayerInit = { + colorFormat: gl.RGBA8, + depthFormat: glDepthFormat, + scaleFactor: framebufferScaleFactor + }; + glBinding = new XRWebGLBinding(session, gl); + glProjLayer = glBinding.createProjectionLayer(projectionlayerInit); + session.updateRenderState({ layers: [glProjLayer] }); + renderer.setPixelRatio(1); + renderer.setSize(glProjLayer.textureWidth, glProjLayer.textureHeight, false); + newRenderTarget = new WebGLRenderTarget( + glProjLayer.textureWidth, + glProjLayer.textureHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, void 0, void 0, void 0, void 0, void 0, void 0, depthFormat), + stencilBuffer: attributes.stencil, + colorSpace: renderer.outputColorSpace, + samples: attributes.antialias ? 4 : 0 + } + ); + const renderTargetProperties = renderer.properties.get(newRenderTarget); + renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues; + } + newRenderTarget.isXRRenderTarget = true; + this.setFoveation(foveation); + customReferenceSpace = null; + referenceSpace = await session.requestReferenceSpace(referenceSpaceType); + animation.setContext(session); + animation.start(); + scope.isPresenting = true; + scope.dispatchEvent({ type: "sessionstart" }); + } + }; + this.getEnvironmentBlendMode = function() { + if (session !== null) { + return session.environmentBlendMode; + } + }; + function onInputSourcesChange(event) { + for (let i = 0; i < event.removed.length; i++) { + const inputSource = event.removed[i]; + const index = controllerInputSources.indexOf(inputSource); + if (index >= 0) { + controllerInputSources[index] = null; + controllers[index].disconnect(inputSource); + } + } + for (let i = 0; i < event.added.length; i++) { + const inputSource = event.added[i]; + let controllerIndex = controllerInputSources.indexOf(inputSource); + if (controllerIndex === -1) { + for (let i2 = 0; i2 < controllers.length; i2++) { + if (i2 >= controllerInputSources.length) { + controllerInputSources.push(inputSource); + controllerIndex = i2; + break; + } else if (controllerInputSources[i2] === null) { + controllerInputSources[i2] = inputSource; + controllerIndex = i2; + break; + } + } + if (controllerIndex === -1) break; + } + const controller = controllers[controllerIndex]; + if (controller) { + controller.connect(inputSource); + } + } + } + const cameraLPos = new Vector3(); + const cameraRPos = new Vector3(); + function setProjectionFromUnion(camera, cameraL2, cameraR2) { + cameraLPos.setFromMatrixPosition(cameraL2.matrixWorld); + cameraRPos.setFromMatrixPosition(cameraR2.matrixWorld); + const ipd = cameraLPos.distanceTo(cameraRPos); + const projL = cameraL2.projectionMatrix.elements; + const projR = cameraR2.projectionMatrix.elements; + const near = projL[14] / (projL[10] - 1); + const far = projL[14] / (projL[10] + 1); + const topFov = (projL[9] + 1) / projL[5]; + const bottomFov = (projL[9] - 1) / projL[5]; + const leftFov = (projL[8] - 1) / projL[0]; + const rightFov = (projR[8] + 1) / projR[0]; + const left = near * leftFov; + const right = near * rightFov; + const zOffset = ipd / (-leftFov + rightFov); + const xOffset = zOffset * -leftFov; + cameraL2.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale); + camera.translateX(xOffset); + camera.translateZ(zOffset); + camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale); + camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); + const near2 = near + zOffset; + const far2 = far + zOffset; + const left2 = left - xOffset; + const right2 = right + (ipd - xOffset); + const top2 = topFov * far / far2 * near2; + const bottom2 = bottomFov * far / far2 * near2; + camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2); + camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert(); + } + function updateCamera(camera, parent) { + if (parent === null) { + camera.matrixWorld.copy(camera.matrix); + } else { + camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix); + } + camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); + } + this.updateCamera = function(camera) { + if (session === null) return; + cameraXR.near = cameraR.near = cameraL.near = camera.near; + cameraXR.far = cameraR.far = cameraL.far = camera.far; + if (_currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far) { + session.updateRenderState({ + depthNear: cameraXR.near, + depthFar: cameraXR.far + }); + _currentDepthNear = cameraXR.near; + _currentDepthFar = cameraXR.far; + } + const parent = camera.parent; + const cameras2 = cameraXR.cameras; + updateCamera(cameraXR, parent); + for (let i = 0; i < cameras2.length; i++) { + updateCamera(cameras2[i], parent); + } + if (cameras2.length === 2) { + setProjectionFromUnion(cameraXR, cameraL, cameraR); + } else { + cameraXR.projectionMatrix.copy(cameraL.projectionMatrix); + } + updateUserCamera(camera, cameraXR, parent); + }; + function updateUserCamera(camera, cameraXR2, parent) { + if (parent === null) { + camera.matrix.copy(cameraXR2.matrixWorld); + } else { + camera.matrix.copy(parent.matrixWorld); + camera.matrix.invert(); + camera.matrix.multiply(cameraXR2.matrixWorld); + } + camera.matrix.decompose(camera.position, camera.quaternion, camera.scale); + camera.updateMatrixWorld(true); + camera.projectionMatrix.copy(cameraXR2.projectionMatrix); + camera.projectionMatrixInverse.copy(cameraXR2.projectionMatrixInverse); + if (camera.isPerspectiveCamera) { + camera.fov = RAD2DEG * 2 * Math.atan(1 / camera.projectionMatrix.elements[5]); + camera.zoom = 1; + } + } + this.getCamera = function() { + return cameraXR; + }; + this.getFoveation = function() { + if (glProjLayer === null && glBaseLayer === null) { + return void 0; + } + return foveation; + }; + this.setFoveation = function(value) { + foveation = value; + if (glProjLayer !== null) { + glProjLayer.fixedFoveation = value; + } + if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== void 0) { + glBaseLayer.fixedFoveation = value; + } + }; + let onAnimationFrameCallback = null; + function onAnimationFrame(time, frame) { + pose = frame.getViewerPose(customReferenceSpace || referenceSpace); + xrFrame = frame; + if (pose !== null) { + const views = pose.views; + if (glBaseLayer !== null) { + renderer.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer); + renderer.setRenderTarget(newRenderTarget); + } + let cameraXRNeedsUpdate = false; + if (views.length !== cameraXR.cameras.length) { + cameraXR.cameras.length = 0; + cameraXRNeedsUpdate = true; + } + for (let i = 0; i < views.length; i++) { + const view = views[i]; + let viewport = null; + if (glBaseLayer !== null) { + viewport = glBaseLayer.getViewport(view); + } else { + const glSubImage = glBinding.getViewSubImage(glProjLayer, view); + viewport = glSubImage.viewport; + if (i === 0) { + renderer.setRenderTargetTextures( + newRenderTarget, + glSubImage.colorTexture, + glProjLayer.ignoreDepthValues ? void 0 : glSubImage.depthStencilTexture + ); + renderer.setRenderTarget(newRenderTarget); + } + } + let camera = cameras[i]; + if (camera === void 0) { + camera = new PerspectiveCamera(); + camera.layers.enable(i); + camera.viewport = new Vector4(); + cameras[i] = camera; + } + camera.matrix.fromArray(view.transform.matrix); + camera.matrix.decompose(camera.position, camera.quaternion, camera.scale); + camera.projectionMatrix.fromArray(view.projectionMatrix); + camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert(); + camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height); + if (i === 0) { + cameraXR.matrix.copy(camera.matrix); + cameraXR.matrix.decompose(cameraXR.position, cameraXR.quaternion, cameraXR.scale); + } + if (cameraXRNeedsUpdate === true) { + cameraXR.cameras.push(camera); + } + } + } + for (let i = 0; i < controllers.length; i++) { + const inputSource = controllerInputSources[i]; + const controller = controllers[i]; + if (inputSource !== null && controller !== void 0) { + controller.update(inputSource, frame, customReferenceSpace || referenceSpace); + } + } + if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame); + if (frame.detectedPlanes) { + scope.dispatchEvent({ type: "planesdetected", data: frame }); + } + xrFrame = null; + } + const animation = new WebGLAnimation(); + animation.setAnimationLoop(onAnimationFrame); + this.setAnimationLoop = function(callback) { + onAnimationFrameCallback = callback; + }; + this.dispose = function() { + }; + } + }; + function WebGLMaterials(renderer, properties) { + function refreshTransformUniform(map, uniform) { + if (map.matrixAutoUpdate === true) { + map.updateMatrix(); + } + uniform.value.copy(map.matrix); + } + function refreshFogUniforms(uniforms, fog) { + fog.color.getRGB(uniforms.fogColor.value, getUnlitUniformColorSpace(renderer)); + if (fog.isFog) { + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; + } else if (fog.isFogExp2) { + uniforms.fogDensity.value = fog.density; + } + } + function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) { + if (material.isMeshBasicMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshLambertMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshToonMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsToon(uniforms, material); + } else if (material.isMeshPhongMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsPhong(uniforms, material); + } else if (material.isMeshStandardMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsStandard(uniforms, material); + if (material.isMeshPhysicalMaterial) { + refreshUniformsPhysical(uniforms, material, transmissionRenderTarget); + } + } else if (material.isMeshMatcapMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsMatcap(uniforms, material); + } else if (material.isMeshDepthMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshDistanceMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsDistance(uniforms, material); + } else if (material.isMeshNormalMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isLineBasicMaterial) { + refreshUniformsLine(uniforms, material); + if (material.isLineDashedMaterial) { + refreshUniformsDash(uniforms, material); + } + } else if (material.isPointsMaterial) { + refreshUniformsPoints(uniforms, material, pixelRatio, height); + } else if (material.isSpriteMaterial) { + refreshUniformsSprites(uniforms, material); + } else if (material.isShadowMaterial) { + uniforms.color.value.copy(material.color); + uniforms.opacity.value = material.opacity; + } else if (material.isShaderMaterial) { + material.uniformsNeedUpdate = false; + } + } + function refreshUniformsCommon(uniforms, material) { + uniforms.opacity.value = material.opacity; + if (material.color) { + uniforms.diffuse.value.copy(material.color); + } + if (material.emissive) { + uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity); + } + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.bumpMap) { + uniforms.bumpMap.value = material.bumpMap; + refreshTransformUniform(material.bumpMap, uniforms.bumpMapTransform); + uniforms.bumpScale.value = material.bumpScale; + if (material.side === BackSide) { + uniforms.bumpScale.value *= -1; + } + } + if (material.normalMap) { + uniforms.normalMap.value = material.normalMap; + refreshTransformUniform(material.normalMap, uniforms.normalMapTransform); + uniforms.normalScale.value.copy(material.normalScale); + if (material.side === BackSide) { + uniforms.normalScale.value.negate(); + } + } + if (material.displacementMap) { + uniforms.displacementMap.value = material.displacementMap; + refreshTransformUniform(material.displacementMap, uniforms.displacementMapTransform); + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; + } + if (material.emissiveMap) { + uniforms.emissiveMap.value = material.emissiveMap; + refreshTransformUniform(material.emissiveMap, uniforms.emissiveMapTransform); + } + if (material.specularMap) { + uniforms.specularMap.value = material.specularMap; + refreshTransformUniform(material.specularMap, uniforms.specularMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + const envMap = properties.get(material).envMap; + if (envMap) { + uniforms.envMap.value = envMap; + uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1; + uniforms.reflectivity.value = material.reflectivity; + uniforms.ior.value = material.ior; + uniforms.refractionRatio.value = material.refractionRatio; + } + if (material.lightMap) { + uniforms.lightMap.value = material.lightMap; + const scaleFactor = renderer._useLegacyLights === true ? Math.PI : 1; + uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor; + refreshTransformUniform(material.lightMap, uniforms.lightMapTransform); + } + if (material.aoMap) { + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; + refreshTransformUniform(material.aoMap, uniforms.aoMapTransform); + } + } + function refreshUniformsLine(uniforms, material) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + } + function refreshUniformsDash(uniforms, material) { + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; + } + function refreshUniformsPoints(uniforms, material, pixelRatio, height) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * pixelRatio; + uniforms.scale.value = height * 0.5; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.uvTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + } + function refreshUniformsSprites(uniforms, material) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + uniforms.rotation.value = material.rotation; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + } + function refreshUniformsPhong(uniforms, material) { + uniforms.specular.value.copy(material.specular); + uniforms.shininess.value = Math.max(material.shininess, 1e-4); + } + function refreshUniformsToon(uniforms, material) { + if (material.gradientMap) { + uniforms.gradientMap.value = material.gradientMap; + } + } + function refreshUniformsStandard(uniforms, material) { + uniforms.metalness.value = material.metalness; + if (material.metalnessMap) { + uniforms.metalnessMap.value = material.metalnessMap; + refreshTransformUniform(material.metalnessMap, uniforms.metalnessMapTransform); + } + uniforms.roughness.value = material.roughness; + if (material.roughnessMap) { + uniforms.roughnessMap.value = material.roughnessMap; + refreshTransformUniform(material.roughnessMap, uniforms.roughnessMapTransform); + } + const envMap = properties.get(material).envMap; + if (envMap) { + uniforms.envMapIntensity.value = material.envMapIntensity; + } + } + function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) { + uniforms.ior.value = material.ior; + if (material.sheen > 0) { + uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen); + uniforms.sheenRoughness.value = material.sheenRoughness; + if (material.sheenColorMap) { + uniforms.sheenColorMap.value = material.sheenColorMap; + refreshTransformUniform(material.sheenColorMap, uniforms.sheenColorMapTransform); + } + if (material.sheenRoughnessMap) { + uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap; + refreshTransformUniform(material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform); + } + } + if (material.clearcoat > 0) { + uniforms.clearcoat.value = material.clearcoat; + uniforms.clearcoatRoughness.value = material.clearcoatRoughness; + if (material.clearcoatMap) { + uniforms.clearcoatMap.value = material.clearcoatMap; + refreshTransformUniform(material.clearcoatMap, uniforms.clearcoatMapTransform); + } + if (material.clearcoatRoughnessMap) { + uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; + refreshTransformUniform(material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform); + } + if (material.clearcoatNormalMap) { + uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; + refreshTransformUniform(material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform); + uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale); + if (material.side === BackSide) { + uniforms.clearcoatNormalScale.value.negate(); + } + } + } + if (material.iridescence > 0) { + uniforms.iridescence.value = material.iridescence; + uniforms.iridescenceIOR.value = material.iridescenceIOR; + uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[0]; + uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[1]; + if (material.iridescenceMap) { + uniforms.iridescenceMap.value = material.iridescenceMap; + refreshTransformUniform(material.iridescenceMap, uniforms.iridescenceMapTransform); + } + if (material.iridescenceThicknessMap) { + uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap; + refreshTransformUniform(material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform); + } + } + if (material.transmission > 0) { + uniforms.transmission.value = material.transmission; + uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture; + uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height); + if (material.transmissionMap) { + uniforms.transmissionMap.value = material.transmissionMap; + refreshTransformUniform(material.transmissionMap, uniforms.transmissionMapTransform); + } + uniforms.thickness.value = material.thickness; + if (material.thicknessMap) { + uniforms.thicknessMap.value = material.thicknessMap; + refreshTransformUniform(material.thicknessMap, uniforms.thicknessMapTransform); + } + uniforms.attenuationDistance.value = material.attenuationDistance; + uniforms.attenuationColor.value.copy(material.attenuationColor); + } + if (material.anisotropy > 0) { + uniforms.anisotropyVector.value.set(material.anisotropy * Math.cos(material.anisotropyRotation), material.anisotropy * Math.sin(material.anisotropyRotation)); + if (material.anisotropyMap) { + uniforms.anisotropyMap.value = material.anisotropyMap; + refreshTransformUniform(material.anisotropyMap, uniforms.anisotropyMapTransform); + } + } + uniforms.specularIntensity.value = material.specularIntensity; + uniforms.specularColor.value.copy(material.specularColor); + if (material.specularColorMap) { + uniforms.specularColorMap.value = material.specularColorMap; + refreshTransformUniform(material.specularColorMap, uniforms.specularColorMapTransform); + } + if (material.specularIntensityMap) { + uniforms.specularIntensityMap.value = material.specularIntensityMap; + refreshTransformUniform(material.specularIntensityMap, uniforms.specularIntensityMapTransform); + } + } + function refreshUniformsMatcap(uniforms, material) { + if (material.matcap) { + uniforms.matcap.value = material.matcap; + } + } + function refreshUniformsDistance(uniforms, material) { + const light = properties.get(material).light; + uniforms.referencePosition.value.setFromMatrixPosition(light.matrixWorld); + uniforms.nearDistance.value = light.shadow.camera.near; + uniforms.farDistance.value = light.shadow.camera.far; + } + return { + refreshFogUniforms, + refreshMaterialUniforms + }; + } + function WebGLUniformsGroups(gl, info, capabilities, state) { + let buffers = {}; + let updateList = {}; + let allocatedBindingPoints = []; + const maxBindingPoints = capabilities.isWebGL2 ? gl.getParameter(gl.MAX_UNIFORM_BUFFER_BINDINGS) : 0; + function bind(uniformsGroup, program) { + const webglProgram = program.program; + state.uniformBlockBinding(uniformsGroup, webglProgram); + } + function update(uniformsGroup, program) { + let buffer = buffers[uniformsGroup.id]; + if (buffer === void 0) { + prepareUniformsGroup(uniformsGroup); + buffer = createBuffer(uniformsGroup); + buffers[uniformsGroup.id] = buffer; + uniformsGroup.addEventListener("dispose", onUniformsGroupsDispose); + } + const webglProgram = program.program; + state.updateUBOMapping(uniformsGroup, webglProgram); + const frame = info.render.frame; + if (updateList[uniformsGroup.id] !== frame) { + updateBufferData(uniformsGroup); + updateList[uniformsGroup.id] = frame; + } + } + function createBuffer(uniformsGroup) { + const bindingPointIndex = allocateBindingPointIndex(); + uniformsGroup.__bindingPointIndex = bindingPointIndex; + const buffer = gl.createBuffer(); + const size = uniformsGroup.__size; + const usage = uniformsGroup.usage; + gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); + gl.bufferData(gl.UNIFORM_BUFFER, size, usage); + gl.bindBuffer(gl.UNIFORM_BUFFER, null); + gl.bindBufferBase(gl.UNIFORM_BUFFER, bindingPointIndex, buffer); + return buffer; + } + function allocateBindingPointIndex() { + for (let i = 0; i < maxBindingPoints; i++) { + if (allocatedBindingPoints.indexOf(i) === -1) { + allocatedBindingPoints.push(i); + return i; + } + } + console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."); + return 0; + } + function updateBufferData(uniformsGroup) { + const buffer = buffers[uniformsGroup.id]; + const uniforms = uniformsGroup.uniforms; + const cache = uniformsGroup.__cache; + gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); + for (let i = 0, il = uniforms.length; i < il; i++) { + const uniformArray = Array.isArray(uniforms[i]) ? uniforms[i] : [uniforms[i]]; + for (let j = 0, jl = uniformArray.length; j < jl; j++) { + const uniform = uniformArray[j]; + if (hasUniformChanged(uniform, i, j, cache) === true) { + const offset = uniform.__offset; + const values = Array.isArray(uniform.value) ? uniform.value : [uniform.value]; + let arrayOffset = 0; + for (let k = 0; k < values.length; k++) { + const value = values[k]; + const info2 = getUniformSize(value); + if (typeof value === "number" || typeof value === "boolean") { + uniform.__data[0] = value; + gl.bufferSubData(gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data); + } else if (value.isMatrix3) { + uniform.__data[0] = value.elements[0]; + uniform.__data[1] = value.elements[1]; + uniform.__data[2] = value.elements[2]; + uniform.__data[3] = 0; + uniform.__data[4] = value.elements[3]; + uniform.__data[5] = value.elements[4]; + uniform.__data[6] = value.elements[5]; + uniform.__data[7] = 0; + uniform.__data[8] = value.elements[6]; + uniform.__data[9] = value.elements[7]; + uniform.__data[10] = value.elements[8]; + uniform.__data[11] = 0; + } else { + value.toArray(uniform.__data, arrayOffset); + arrayOffset += info2.storage / Float32Array.BYTES_PER_ELEMENT; + } + } + gl.bufferSubData(gl.UNIFORM_BUFFER, offset, uniform.__data); + } + } + } + gl.bindBuffer(gl.UNIFORM_BUFFER, null); + } + function hasUniformChanged(uniform, index, indexArray, cache) { + const value = uniform.value; + const indexString = index + "_" + indexArray; + if (cache[indexString] === void 0) { + if (typeof value === "number" || typeof value === "boolean") { + cache[indexString] = value; + } else { + cache[indexString] = value.clone(); + } + return true; + } else { + const cachedObject = cache[indexString]; + if (typeof value === "number" || typeof value === "boolean") { + if (cachedObject !== value) { + cache[indexString] = value; + return true; + } + } else { + if (cachedObject.equals(value) === false) { + cachedObject.copy(value); + return true; + } + } + } + return false; + } + function prepareUniformsGroup(uniformsGroup) { + const uniforms = uniformsGroup.uniforms; + let offset = 0; + const chunkSize = 16; + for (let i = 0, l = uniforms.length; i < l; i++) { + const uniformArray = Array.isArray(uniforms[i]) ? uniforms[i] : [uniforms[i]]; + for (let j = 0, jl = uniformArray.length; j < jl; j++) { + const uniform = uniformArray[j]; + const values = Array.isArray(uniform.value) ? uniform.value : [uniform.value]; + for (let k = 0, kl = values.length; k < kl; k++) { + const value = values[k]; + const info2 = getUniformSize(value); + const chunkOffsetUniform = offset % chunkSize; + if (chunkOffsetUniform !== 0 && chunkSize - chunkOffsetUniform < info2.boundary) { + offset += chunkSize - chunkOffsetUniform; + } + uniform.__data = new Float32Array(info2.storage / Float32Array.BYTES_PER_ELEMENT); + uniform.__offset = offset; + offset += info2.storage; + } + } + } + const chunkOffset = offset % chunkSize; + if (chunkOffset > 0) offset += chunkSize - chunkOffset; + uniformsGroup.__size = offset; + uniformsGroup.__cache = {}; + return this; + } + function getUniformSize(value) { + const info2 = { + boundary: 0, + // bytes + storage: 0 + // bytes + }; + if (typeof value === "number" || typeof value === "boolean") { + info2.boundary = 4; + info2.storage = 4; + } else if (value.isVector2) { + info2.boundary = 8; + info2.storage = 8; + } else if (value.isVector3 || value.isColor) { + info2.boundary = 16; + info2.storage = 12; + } else if (value.isVector4) { + info2.boundary = 16; + info2.storage = 16; + } else if (value.isMatrix3) { + info2.boundary = 48; + info2.storage = 48; + } else if (value.isMatrix4) { + info2.boundary = 64; + info2.storage = 64; + } else if (value.isTexture) { + console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."); + } else { + console.warn("THREE.WebGLRenderer: Unsupported uniform value type.", value); + } + return info2; + } + function onUniformsGroupsDispose(event) { + const uniformsGroup = event.target; + uniformsGroup.removeEventListener("dispose", onUniformsGroupsDispose); + const index = allocatedBindingPoints.indexOf(uniformsGroup.__bindingPointIndex); + allocatedBindingPoints.splice(index, 1); + gl.deleteBuffer(buffers[uniformsGroup.id]); + delete buffers[uniformsGroup.id]; + delete updateList[uniformsGroup.id]; + } + function dispose() { + for (const id in buffers) { + gl.deleteBuffer(buffers[id]); + } + allocatedBindingPoints = []; + buffers = {}; + updateList = {}; + } + return { + bind, + update, + dispose + }; + } + var WebGLRenderer = class { + constructor(parameters = {}) { + const { + canvas = createCanvasElement(), + context = null, + depth = true, + stencil = true, + alpha = false, + antialias = false, + premultipliedAlpha = true, + preserveDrawingBuffer = false, + powerPreference = "default", + failIfMajorPerformanceCaveat = false + } = parameters; + this.isWebGLRenderer = true; + let _alpha; + if (context !== null) { + _alpha = context.getContextAttributes().alpha; + } else { + _alpha = alpha; + } + const uintClearColor = new Uint32Array(4); + const intClearColor = new Int32Array(4); + let currentRenderList = null; + let currentRenderState = null; + const renderListStack = []; + const renderStateStack = []; + this.domElement = canvas; + this.debug = { + /** + * Enables error checking and reporting when shader programs are being compiled + * @type {boolean} + */ + checkShaderErrors: true, + /** + * Callback for custom error reporting. + * @type {?Function} + */ + onShaderError: null + }; + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; + this.sortObjects = true; + this.clippingPlanes = []; + this.localClippingEnabled = false; + this._outputColorSpace = SRGBColorSpace; + this._useLegacyLights = false; + this.toneMapping = NoToneMapping; + this.toneMappingExposure = 1; + const _this = this; + let _isContextLost = false; + let _currentActiveCubeFace = 0; + let _currentActiveMipmapLevel = 0; + let _currentRenderTarget = null; + let _currentMaterialId = -1; + let _currentCamera = null; + const _currentViewport = new Vector4(); + const _currentScissor = new Vector4(); + let _currentScissorTest = null; + const _currentClearColor = new Color(0); + let _currentClearAlpha = 0; + let _width = canvas.width; + let _height = canvas.height; + let _pixelRatio = 1; + let _opaqueSort = null; + let _transparentSort = null; + const _viewport = new Vector4(0, 0, _width, _height); + const _scissor = new Vector4(0, 0, _width, _height); + let _scissorTest = false; + const _frustum2 = new Frustum(); + let _clippingEnabled = false; + let _localClippingEnabled = false; + let _transmissionRenderTarget = null; + const _projScreenMatrix2 = new Matrix4(); + const _vector22 = new Vector2(); + const _vector32 = new Vector3(); + const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true }; + function getTargetPixelRatio() { + return _currentRenderTarget === null ? _pixelRatio : 1; + } + let _gl = context; + function getContext(contextNames, contextAttributes) { + for (let i = 0; i < contextNames.length; i++) { + const contextName = contextNames[i]; + const context2 = canvas.getContext(contextName, contextAttributes); + if (context2 !== null) return context2; + } + return null; + } + try { + const contextAttributes = { + alpha: true, + depth, + stencil, + antialias, + premultipliedAlpha, + preserveDrawingBuffer, + powerPreference, + failIfMajorPerformanceCaveat + }; + if ("setAttribute" in canvas) canvas.setAttribute("data-engine", `three.js r${REVISION}`); + canvas.addEventListener("webglcontextlost", onContextLost, false); + canvas.addEventListener("webglcontextrestored", onContextRestore, false); + canvas.addEventListener("webglcontextcreationerror", onContextCreationError, false); + if (_gl === null) { + const contextNames = ["webgl2", "webgl", "experimental-webgl"]; + if (_this.isWebGL1Renderer === true) { + contextNames.shift(); + } + _gl = getContext(contextNames, contextAttributes); + if (_gl === null) { + if (getContext(contextNames)) { + throw new Error("Error creating WebGL context with your selected attributes."); + } else { + throw new Error("Error creating WebGL context."); + } + } + } + if (typeof WebGLRenderingContext !== "undefined" && _gl instanceof WebGLRenderingContext) { + console.warn("THREE.WebGLRenderer: WebGL 1 support was deprecated in r153 and will be removed in r163."); + } + if (_gl.getShaderPrecisionFormat === void 0) { + _gl.getShaderPrecisionFormat = function() { + return { "rangeMin": 1, "rangeMax": 1, "precision": 1 }; + }; + } + } catch (error) { + console.error("THREE.WebGLRenderer: " + error.message); + throw error; + } + let extensions, capabilities, state, info; + let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects; + let programCache, materials, renderLists, renderStates, clipping, shadowMap; + let background, morphtargets, bufferRenderer, indexedBufferRenderer; + let utils, bindingStates, uniformsGroups; + function initGLContext() { + extensions = new WebGLExtensions(_gl); + capabilities = new WebGLCapabilities(_gl, extensions, parameters); + extensions.init(capabilities); + utils = new WebGLUtils(_gl, extensions, capabilities); + state = new WebGLState(_gl, extensions, capabilities); + info = new WebGLInfo(_gl); + properties = new WebGLProperties(); + textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info); + cubemaps = new WebGLCubeMaps(_this); + cubeuvmaps = new WebGLCubeUVMaps(_this); + attributes = new WebGLAttributes(_gl, capabilities); + bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities); + geometries = new WebGLGeometries(_gl, attributes, info, bindingStates); + objects = new WebGLObjects(_gl, geometries, attributes, info); + morphtargets = new WebGLMorphtargets(_gl, capabilities, textures); + clipping = new WebGLClipping(properties); + programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping); + materials = new WebGLMaterials(_this, properties); + renderLists = new WebGLRenderLists(); + renderStates = new WebGLRenderStates(extensions, capabilities); + background = new WebGLBackground(_this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha); + shadowMap = new WebGLShadowMap(_this, objects, capabilities); + uniformsGroups = new WebGLUniformsGroups(_gl, info, capabilities, state); + bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities); + indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities); + info.programs = programCache.programs; + _this.capabilities = capabilities; + _this.extensions = extensions; + _this.properties = properties; + _this.renderLists = renderLists; + _this.shadowMap = shadowMap; + _this.state = state; + _this.info = info; + } + initGLContext(); + const xr = new WebXRManager(_this, _gl); + this.xr = xr; + this.getContext = function() { + return _gl; + }; + this.getContextAttributes = function() { + return _gl.getContextAttributes(); + }; + this.forceContextLoss = function() { + const extension = extensions.get("WEBGL_lose_context"); + if (extension) extension.loseContext(); + }; + this.forceContextRestore = function() { + const extension = extensions.get("WEBGL_lose_context"); + if (extension) extension.restoreContext(); + }; + this.getPixelRatio = function() { + return _pixelRatio; + }; + this.setPixelRatio = function(value) { + if (value === void 0) return; + _pixelRatio = value; + this.setSize(_width, _height, false); + }; + this.getSize = function(target) { + return target.set(_width, _height); + }; + this.setSize = function(width, height, updateStyle = true) { + if (xr.isPresenting) { + console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."); + return; + } + _width = width; + _height = height; + canvas.width = Math.floor(width * _pixelRatio); + canvas.height = Math.floor(height * _pixelRatio); + if (updateStyle === true) { + canvas.style.width = width + "px"; + canvas.style.height = height + "px"; + } + this.setViewport(0, 0, width, height); + }; + this.getDrawingBufferSize = function(target) { + return target.set(_width * _pixelRatio, _height * _pixelRatio).floor(); + }; + this.setDrawingBufferSize = function(width, height, pixelRatio) { + _width = width; + _height = height; + _pixelRatio = pixelRatio; + canvas.width = Math.floor(width * pixelRatio); + canvas.height = Math.floor(height * pixelRatio); + this.setViewport(0, 0, width, height); + }; + this.getCurrentViewport = function(target) { + return target.copy(_currentViewport); + }; + this.getViewport = function(target) { + return target.copy(_viewport); + }; + this.setViewport = function(x, y, width, height) { + if (x.isVector4) { + _viewport.set(x.x, x.y, x.z, x.w); + } else { + _viewport.set(x, y, width, height); + } + state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor()); + }; + this.getScissor = function(target) { + return target.copy(_scissor); + }; + this.setScissor = function(x, y, width, height) { + if (x.isVector4) { + _scissor.set(x.x, x.y, x.z, x.w); + } else { + _scissor.set(x, y, width, height); + } + state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor()); + }; + this.getScissorTest = function() { + return _scissorTest; + }; + this.setScissorTest = function(boolean) { + state.setScissorTest(_scissorTest = boolean); + }; + this.setOpaqueSort = function(method) { + _opaqueSort = method; + }; + this.setTransparentSort = function(method) { + _transparentSort = method; + }; + this.getClearColor = function(target) { + return target.copy(background.getClearColor()); + }; + this.setClearColor = function() { + background.setClearColor.apply(background, arguments); + }; + this.getClearAlpha = function() { + return background.getClearAlpha(); + }; + this.setClearAlpha = function() { + background.setClearAlpha.apply(background, arguments); + }; + this.clear = function(color = true, depth2 = true, stencil2 = true) { + let bits2 = 0; + if (color) { + let isIntegerFormat = false; + if (_currentRenderTarget !== null) { + const targetFormat = _currentRenderTarget.texture.format; + isIntegerFormat = targetFormat === RGBAIntegerFormat || targetFormat === RGIntegerFormat || targetFormat === RedIntegerFormat; + } + if (isIntegerFormat) { + const targetType = _currentRenderTarget.texture.type; + const isUnsignedType = targetType === UnsignedByteType || targetType === UnsignedIntType || targetType === UnsignedShortType || targetType === UnsignedInt248Type || targetType === UnsignedShort4444Type || targetType === UnsignedShort5551Type; + const clearColor = background.getClearColor(); + const a = background.getClearAlpha(); + const r = clearColor.r; + const g = clearColor.g; + const b = clearColor.b; + if (isUnsignedType) { + uintClearColor[0] = r; + uintClearColor[1] = g; + uintClearColor[2] = b; + uintClearColor[3] = a; + _gl.clearBufferuiv(_gl.COLOR, 0, uintClearColor); + } else { + intClearColor[0] = r; + intClearColor[1] = g; + intClearColor[2] = b; + intClearColor[3] = a; + _gl.clearBufferiv(_gl.COLOR, 0, intClearColor); + } + } else { + bits2 |= _gl.COLOR_BUFFER_BIT; + } + } + if (depth2) bits2 |= _gl.DEPTH_BUFFER_BIT; + if (stencil2) { + bits2 |= _gl.STENCIL_BUFFER_BIT; + this.state.buffers.stencil.setMask(4294967295); + } + _gl.clear(bits2); + }; + this.clearColor = function() { + this.clear(true, false, false); + }; + this.clearDepth = function() { + this.clear(false, true, false); + }; + this.clearStencil = function() { + this.clear(false, false, true); + }; + this.dispose = function() { + canvas.removeEventListener("webglcontextlost", onContextLost, false); + canvas.removeEventListener("webglcontextrestored", onContextRestore, false); + canvas.removeEventListener("webglcontextcreationerror", onContextCreationError, false); + renderLists.dispose(); + renderStates.dispose(); + properties.dispose(); + cubemaps.dispose(); + cubeuvmaps.dispose(); + objects.dispose(); + bindingStates.dispose(); + uniformsGroups.dispose(); + programCache.dispose(); + xr.dispose(); + xr.removeEventListener("sessionstart", onXRSessionStart); + xr.removeEventListener("sessionend", onXRSessionEnd); + if (_transmissionRenderTarget) { + _transmissionRenderTarget.dispose(); + _transmissionRenderTarget = null; + } + animation.stop(); + }; + function onContextLost(event) { + event.preventDefault(); + console.log("THREE.WebGLRenderer: Context Lost."); + _isContextLost = true; + } + function onContextRestore() { + console.log("THREE.WebGLRenderer: Context Restored."); + _isContextLost = false; + const infoAutoReset = info.autoReset; + const shadowMapEnabled = shadowMap.enabled; + const shadowMapAutoUpdate = shadowMap.autoUpdate; + const shadowMapNeedsUpdate = shadowMap.needsUpdate; + const shadowMapType = shadowMap.type; + initGLContext(); + info.autoReset = infoAutoReset; + shadowMap.enabled = shadowMapEnabled; + shadowMap.autoUpdate = shadowMapAutoUpdate; + shadowMap.needsUpdate = shadowMapNeedsUpdate; + shadowMap.type = shadowMapType; + } + function onContextCreationError(event) { + console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ", event.statusMessage); + } + function onMaterialDispose(event) { + const material = event.target; + material.removeEventListener("dispose", onMaterialDispose); + deallocateMaterial(material); + } + function deallocateMaterial(material) { + releaseMaterialProgramReferences(material); + properties.remove(material); + } + function releaseMaterialProgramReferences(material) { + const programs = properties.get(material).programs; + if (programs !== void 0) { + programs.forEach(function(program) { + programCache.releaseProgram(program); + }); + if (material.isShaderMaterial) { + programCache.releaseShaderCache(material); + } + } + } + this.renderBufferDirect = function(camera, scene, geometry, material, object, group) { + if (scene === null) scene = _emptyScene; + const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0; + const program = setProgram(camera, scene, geometry, material, object); + state.setMaterial(material, frontFaceCW); + let index = geometry.index; + let rangeFactor = 1; + if (material.wireframe === true) { + index = geometries.getWireframeAttribute(geometry); + if (index === void 0) return; + rangeFactor = 2; + } + const drawRange = geometry.drawRange; + const position = geometry.attributes.position; + let drawStart = drawRange.start * rangeFactor; + let drawEnd = (drawRange.start + drawRange.count) * rangeFactor; + if (group !== null) { + drawStart = Math.max(drawStart, group.start * rangeFactor); + drawEnd = Math.min(drawEnd, (group.start + group.count) * rangeFactor); + } + if (index !== null) { + drawStart = Math.max(drawStart, 0); + drawEnd = Math.min(drawEnd, index.count); + } else if (position !== void 0 && position !== null) { + drawStart = Math.max(drawStart, 0); + drawEnd = Math.min(drawEnd, position.count); + } + const drawCount = drawEnd - drawStart; + if (drawCount < 0 || drawCount === Infinity) return; + bindingStates.setup(object, material, program, geometry, index); + let attribute; + let renderer = bufferRenderer; + if (index !== null) { + attribute = attributes.get(index); + renderer = indexedBufferRenderer; + renderer.setIndex(attribute); + } + if (object.isMesh) { + if (material.wireframe === true) { + state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio()); + renderer.setMode(_gl.LINES); + } else { + renderer.setMode(_gl.TRIANGLES); + } + } else if (object.isLine) { + let lineWidth = material.linewidth; + if (lineWidth === void 0) lineWidth = 1; + state.setLineWidth(lineWidth * getTargetPixelRatio()); + if (object.isLineSegments) { + renderer.setMode(_gl.LINES); + } else if (object.isLineLoop) { + renderer.setMode(_gl.LINE_LOOP); + } else { + renderer.setMode(_gl.LINE_STRIP); + } + } else if (object.isPoints) { + renderer.setMode(_gl.POINTS); + } else if (object.isSprite) { + renderer.setMode(_gl.TRIANGLES); + } + if (object.isBatchedMesh) { + renderer.renderMultiDraw(object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount); + } else if (object.isInstancedMesh) { + renderer.renderInstances(drawStart, drawCount, object.count); + } else if (geometry.isInstancedBufferGeometry) { + const maxInstanceCount = geometry._maxInstanceCount !== void 0 ? geometry._maxInstanceCount : Infinity; + const instanceCount = Math.min(geometry.instanceCount, maxInstanceCount); + renderer.renderInstances(drawStart, drawCount, instanceCount); + } else { + renderer.render(drawStart, drawCount); + } + }; + function prepareMaterial(material, scene, object) { + if (material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false) { + material.side = BackSide; + material.needsUpdate = true; + getProgram(material, scene, object); + material.side = FrontSide; + material.needsUpdate = true; + getProgram(material, scene, object); + material.side = DoubleSide; + } else { + getProgram(material, scene, object); + } + } + this.compile = function(scene, camera, targetScene = null) { + if (targetScene === null) targetScene = scene; + currentRenderState = renderStates.get(targetScene); + currentRenderState.init(); + renderStateStack.push(currentRenderState); + targetScene.traverseVisible(function(object) { + if (object.isLight && object.layers.test(camera.layers)) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } + }); + if (scene !== targetScene) { + scene.traverseVisible(function(object) { + if (object.isLight && object.layers.test(camera.layers)) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } + }); + } + currentRenderState.setupLights(_this._useLegacyLights); + const materials2 = /* @__PURE__ */ new Set(); + scene.traverse(function(object) { + const material = object.material; + if (material) { + if (Array.isArray(material)) { + for (let i = 0; i < material.length; i++) { + const material2 = material[i]; + prepareMaterial(material2, targetScene, object); + materials2.add(material2); + } + } else { + prepareMaterial(material, targetScene, object); + materials2.add(material); + } + } + }); + renderStateStack.pop(); + currentRenderState = null; + return materials2; + }; + this.compileAsync = function(scene, camera, targetScene = null) { + const materials2 = this.compile(scene, camera, targetScene); + return new Promise((resolve) => { + function checkMaterialsReady() { + materials2.forEach(function(material) { + const materialProperties = properties.get(material); + const program = materialProperties.currentProgram; + if (program.isReady()) { + materials2.delete(material); + } + }); + if (materials2.size === 0) { + resolve(scene); + return; + } + setTimeout(checkMaterialsReady, 10); + } + if (extensions.get("KHR_parallel_shader_compile") !== null) { + checkMaterialsReady(); + } else { + setTimeout(checkMaterialsReady, 10); + } + }); + }; + let onAnimationFrameCallback = null; + function onAnimationFrame(time) { + if (onAnimationFrameCallback) onAnimationFrameCallback(time); + } + function onXRSessionStart() { + animation.stop(); + } + function onXRSessionEnd() { + animation.start(); + } + const animation = new WebGLAnimation(); + animation.setAnimationLoop(onAnimationFrame); + if (typeof self !== "undefined") animation.setContext(self); + this.setAnimationLoop = function(callback) { + onAnimationFrameCallback = callback; + xr.setAnimationLoop(callback); + callback === null ? animation.stop() : animation.start(); + }; + xr.addEventListener("sessionstart", onXRSessionStart); + xr.addEventListener("sessionend", onXRSessionEnd); + this.render = function(scene, camera) { + if (camera !== void 0 && camera.isCamera !== true) { + console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera."); + return; + } + if (_isContextLost === true) return; + if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld(); + if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld(); + if (xr.enabled === true && xr.isPresenting === true) { + if (xr.cameraAutoUpdate === true) xr.updateCamera(camera); + camera = xr.getCamera(); + } + if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget); + currentRenderState = renderStates.get(scene, renderStateStack.length); + currentRenderState.init(); + renderStateStack.push(currentRenderState); + _projScreenMatrix2.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); + _frustum2.setFromProjectionMatrix(_projScreenMatrix2); + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled); + currentRenderList = renderLists.get(scene, renderListStack.length); + currentRenderList.init(); + renderListStack.push(currentRenderList); + projectObject(scene, camera, 0, _this.sortObjects); + currentRenderList.finish(); + if (_this.sortObjects === true) { + currentRenderList.sort(_opaqueSort, _transparentSort); + } + this.info.render.frame++; + if (_clippingEnabled === true) clipping.beginShadows(); + const shadowsArray = currentRenderState.state.shadowsArray; + shadowMap.render(shadowsArray, scene, camera); + if (_clippingEnabled === true) clipping.endShadows(); + if (this.info.autoReset === true) this.info.reset(); + background.render(currentRenderList, scene); + currentRenderState.setupLights(_this._useLegacyLights); + if (camera.isArrayCamera) { + const cameras = camera.cameras; + for (let i = 0, l = cameras.length; i < l; i++) { + const camera2 = cameras[i]; + renderScene(currentRenderList, scene, camera2, camera2.viewport); + } + } else { + renderScene(currentRenderList, scene, camera); + } + if (_currentRenderTarget !== null) { + textures.updateMultisampleRenderTarget(_currentRenderTarget); + textures.updateRenderTargetMipmap(_currentRenderTarget); + } + if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); + bindingStates.resetDefaultState(); + _currentMaterialId = -1; + _currentCamera = null; + renderStateStack.pop(); + if (renderStateStack.length > 0) { + currentRenderState = renderStateStack[renderStateStack.length - 1]; + } else { + currentRenderState = null; + } + renderListStack.pop(); + if (renderListStack.length > 0) { + currentRenderList = renderListStack[renderListStack.length - 1]; + } else { + currentRenderList = null; + } + }; + function projectObject(object, camera, groupOrder, sortObjects) { + if (object.visible === false) return; + const visible = object.layers.test(camera.layers); + if (visible) { + if (object.isGroup) { + groupOrder = object.renderOrder; + } else if (object.isLOD) { + if (object.autoUpdate === true) object.update(camera); + } else if (object.isLight) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } else if (object.isSprite) { + if (!object.frustumCulled || _frustum2.intersectsSprite(object)) { + if (sortObjects) { + _vector32.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix2); + } + const geometry = objects.update(object); + const material = object.material; + if (material.visible) { + currentRenderList.push(object, geometry, material, groupOrder, _vector32.z, null); + } + } + } else if (object.isMesh || object.isLine || object.isPoints) { + if (!object.frustumCulled || _frustum2.intersectsObject(object)) { + const geometry = objects.update(object); + const material = object.material; + if (sortObjects) { + if (object.boundingSphere !== void 0) { + if (object.boundingSphere === null) object.computeBoundingSphere(); + _vector32.copy(object.boundingSphere.center); + } else { + if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); + _vector32.copy(geometry.boundingSphere.center); + } + _vector32.applyMatrix4(object.matrixWorld).applyMatrix4(_projScreenMatrix2); + } + if (Array.isArray(material)) { + const groups = geometry.groups; + for (let i = 0, l = groups.length; i < l; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + if (groupMaterial && groupMaterial.visible) { + currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector32.z, group); + } + } + } else if (material.visible) { + currentRenderList.push(object, geometry, material, groupOrder, _vector32.z, null); + } + } + } + } + const children = object.children; + for (let i = 0, l = children.length; i < l; i++) { + projectObject(children[i], camera, groupOrder, sortObjects); + } + } + function renderScene(currentRenderList2, scene, camera, viewport) { + const opaqueObjects = currentRenderList2.opaque; + const transmissiveObjects = currentRenderList2.transmissive; + const transparentObjects = currentRenderList2.transparent; + currentRenderState.setupLightsView(camera); + if (_clippingEnabled === true) clipping.setGlobalState(_this.clippingPlanes, camera); + if (transmissiveObjects.length > 0) renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera); + if (viewport) state.viewport(_currentViewport.copy(viewport)); + if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera); + if (transmissiveObjects.length > 0) renderObjects(transmissiveObjects, scene, camera); + if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); + state.buffers.depth.setTest(true); + state.buffers.depth.setMask(true); + state.buffers.color.setMask(true); + state.setPolygonOffset(false); + } + function renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera) { + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + if (overrideMaterial !== null) { + return; + } + const isWebGL2 = capabilities.isWebGL2; + if (_transmissionRenderTarget === null) { + _transmissionRenderTarget = new WebGLRenderTarget(1, 1, { + generateMipmaps: true, + type: extensions.has("EXT_color_buffer_half_float") ? HalfFloatType : UnsignedByteType, + minFilter: LinearMipmapLinearFilter, + samples: isWebGL2 ? 4 : 0 + }); + } + _this.getDrawingBufferSize(_vector22); + if (isWebGL2) { + _transmissionRenderTarget.setSize(_vector22.x, _vector22.y); + } else { + _transmissionRenderTarget.setSize(floorPowerOfTwo(_vector22.x), floorPowerOfTwo(_vector22.y)); + } + const currentRenderTarget = _this.getRenderTarget(); + _this.setRenderTarget(_transmissionRenderTarget); + _this.getClearColor(_currentClearColor); + _currentClearAlpha = _this.getClearAlpha(); + if (_currentClearAlpha < 1) _this.setClearColor(16777215, 0.5); + _this.clear(); + const currentToneMapping = _this.toneMapping; + _this.toneMapping = NoToneMapping; + renderObjects(opaqueObjects, scene, camera); + textures.updateMultisampleRenderTarget(_transmissionRenderTarget); + textures.updateRenderTargetMipmap(_transmissionRenderTarget); + let renderTargetNeedsUpdate = false; + for (let i = 0, l = transmissiveObjects.length; i < l; i++) { + const renderItem = transmissiveObjects[i]; + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = renderItem.material; + const group = renderItem.group; + if (material.side === DoubleSide && object.layers.test(camera.layers)) { + const currentSide = material.side; + material.side = BackSide; + material.needsUpdate = true; + renderObject(object, scene, camera, geometry, material, group); + material.side = currentSide; + material.needsUpdate = true; + renderTargetNeedsUpdate = true; + } + } + if (renderTargetNeedsUpdate === true) { + textures.updateMultisampleRenderTarget(_transmissionRenderTarget); + textures.updateRenderTargetMipmap(_transmissionRenderTarget); + } + _this.setRenderTarget(currentRenderTarget); + _this.setClearColor(_currentClearColor, _currentClearAlpha); + _this.toneMapping = currentToneMapping; + } + function renderObjects(renderList, scene, camera) { + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + for (let i = 0, l = renderList.length; i < l; i++) { + const renderItem = renderList[i]; + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = overrideMaterial === null ? renderItem.material : overrideMaterial; + const group = renderItem.group; + if (object.layers.test(camera.layers)) { + renderObject(object, scene, camera, geometry, material, group); + } + } + } + function renderObject(object, scene, camera, geometry, material, group) { + object.onBeforeRender(_this, scene, camera, geometry, material, group); + object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld); + object.normalMatrix.getNormalMatrix(object.modelViewMatrix); + material.onBeforeRender(_this, scene, camera, geometry, object, group); + if (material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false) { + material.side = BackSide; + material.needsUpdate = true; + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + material.side = FrontSide; + material.needsUpdate = true; + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + material.side = DoubleSide; + } else { + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + } + object.onAfterRender(_this, scene, camera, geometry, material, group); + } + function getProgram(material, scene, object) { + if (scene.isScene !== true) scene = _emptyScene; + const materialProperties = properties.get(material); + const lights = currentRenderState.state.lights; + const shadowsArray = currentRenderState.state.shadowsArray; + const lightsStateVersion = lights.state.version; + const parameters2 = programCache.getParameters(material, lights.state, shadowsArray, scene, object); + const programCacheKey = programCache.getProgramCacheKey(parameters2); + let programs = materialProperties.programs; + materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; + materialProperties.fog = scene.fog; + materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment); + if (programs === void 0) { + material.addEventListener("dispose", onMaterialDispose); + programs = /* @__PURE__ */ new Map(); + materialProperties.programs = programs; + } + let program = programs.get(programCacheKey); + if (program !== void 0) { + if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) { + updateCommonMaterialProperties(material, parameters2); + return program; + } + } else { + parameters2.uniforms = programCache.getUniforms(material); + material.onBuild(object, parameters2, _this); + material.onBeforeCompile(parameters2, _this); + program = programCache.acquireProgram(parameters2, programCacheKey); + programs.set(programCacheKey, program); + materialProperties.uniforms = parameters2.uniforms; + } + const uniforms = materialProperties.uniforms; + if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) { + uniforms.clippingPlanes = clipping.uniform; + } + updateCommonMaterialProperties(material, parameters2); + materialProperties.needsLights = materialNeedsLights(material); + materialProperties.lightsStateVersion = lightsStateVersion; + if (materialProperties.needsLights) { + uniforms.ambientLightColor.value = lights.state.ambient; + uniforms.lightProbe.value = lights.state.probe; + uniforms.directionalLights.value = lights.state.directional; + uniforms.directionalLightShadows.value = lights.state.directionalShadow; + uniforms.spotLights.value = lights.state.spot; + uniforms.spotLightShadows.value = lights.state.spotShadow; + uniforms.rectAreaLights.value = lights.state.rectArea; + uniforms.ltc_1.value = lights.state.rectAreaLTC1; + uniforms.ltc_2.value = lights.state.rectAreaLTC2; + uniforms.pointLights.value = lights.state.point; + uniforms.pointLightShadows.value = lights.state.pointShadow; + uniforms.hemisphereLights.value = lights.state.hemi; + uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; + uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; + uniforms.spotShadowMap.value = lights.state.spotShadowMap; + uniforms.spotLightMatrix.value = lights.state.spotLightMatrix; + uniforms.spotLightMap.value = lights.state.spotLightMap; + uniforms.pointShadowMap.value = lights.state.pointShadowMap; + uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; + } + materialProperties.currentProgram = program; + materialProperties.uniformsList = null; + return program; + } + function getUniformList(materialProperties) { + if (materialProperties.uniformsList === null) { + const progUniforms = materialProperties.currentProgram.getUniforms(); + materialProperties.uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, materialProperties.uniforms); + } + return materialProperties.uniformsList; + } + function updateCommonMaterialProperties(material, parameters2) { + const materialProperties = properties.get(material); + materialProperties.outputColorSpace = parameters2.outputColorSpace; + materialProperties.batching = parameters2.batching; + materialProperties.instancing = parameters2.instancing; + materialProperties.instancingColor = parameters2.instancingColor; + materialProperties.skinning = parameters2.skinning; + materialProperties.morphTargets = parameters2.morphTargets; + materialProperties.morphNormals = parameters2.morphNormals; + materialProperties.morphColors = parameters2.morphColors; + materialProperties.morphTargetsCount = parameters2.morphTargetsCount; + materialProperties.numClippingPlanes = parameters2.numClippingPlanes; + materialProperties.numIntersection = parameters2.numClipIntersection; + materialProperties.vertexAlphas = parameters2.vertexAlphas; + materialProperties.vertexTangents = parameters2.vertexTangents; + materialProperties.toneMapping = parameters2.toneMapping; + } + function setProgram(camera, scene, geometry, material, object) { + if (scene.isScene !== true) scene = _emptyScene; + textures.resetTextureUnits(); + const fog = scene.fog; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const colorSpace = _currentRenderTarget === null ? _this.outputColorSpace : _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace; + const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment); + const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4; + const vertexTangents = !!geometry.attributes.tangent && (!!material.normalMap || material.anisotropy > 0); + const morphTargets = !!geometry.morphAttributes.position; + const morphNormals = !!geometry.morphAttributes.normal; + const morphColors = !!geometry.morphAttributes.color; + let toneMapping = NoToneMapping; + if (material.toneMapped) { + if (_currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true) { + toneMapping = _this.toneMapping; + } + } + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== void 0 ? morphAttribute.length : 0; + const materialProperties = properties.get(material); + const lights = currentRenderState.state.lights; + if (_clippingEnabled === true) { + if (_localClippingEnabled === true || camera !== _currentCamera) { + const useCache = camera === _currentCamera && material.id === _currentMaterialId; + clipping.setState(material, camera, useCache); + } + } + let needsProgramChange = false; + if (material.version === materialProperties.__version) { + if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) { + needsProgramChange = true; + } else if (materialProperties.outputColorSpace !== colorSpace) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batching === false) { + needsProgramChange = true; + } else if (!object.isBatchedMesh && materialProperties.batching === true) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancing === false) { + needsProgramChange = true; + } else if (!object.isInstancedMesh && materialProperties.instancing === true) { + needsProgramChange = true; + } else if (object.isSkinnedMesh && materialProperties.skinning === false) { + needsProgramChange = true; + } else if (!object.isSkinnedMesh && materialProperties.skinning === true) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null) { + needsProgramChange = true; + } else if (materialProperties.envMap !== envMap) { + needsProgramChange = true; + } else if (material.fog === true && materialProperties.fog !== fog) { + needsProgramChange = true; + } else if (materialProperties.numClippingPlanes !== void 0 && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) { + needsProgramChange = true; + } else if (materialProperties.vertexAlphas !== vertexAlphas) { + needsProgramChange = true; + } else if (materialProperties.vertexTangents !== vertexTangents) { + needsProgramChange = true; + } else if (materialProperties.morphTargets !== morphTargets) { + needsProgramChange = true; + } else if (materialProperties.morphNormals !== morphNormals) { + needsProgramChange = true; + } else if (materialProperties.morphColors !== morphColors) { + needsProgramChange = true; + } else if (materialProperties.toneMapping !== toneMapping) { + needsProgramChange = true; + } else if (capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount) { + needsProgramChange = true; + } + } else { + needsProgramChange = true; + materialProperties.__version = material.version; + } + let program = materialProperties.currentProgram; + if (needsProgramChange === true) { + program = getProgram(material, scene, object); + } + let refreshProgram = false; + let refreshMaterial = false; + let refreshLights = false; + const p_uniforms = program.getUniforms(), m_uniforms = materialProperties.uniforms; + if (state.useProgram(program.program)) { + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; + } + if (material.id !== _currentMaterialId) { + _currentMaterialId = material.id; + refreshMaterial = true; + } + if (refreshProgram || _currentCamera !== camera) { + p_uniforms.setValue(_gl, "projectionMatrix", camera.projectionMatrix); + p_uniforms.setValue(_gl, "viewMatrix", camera.matrixWorldInverse); + const uCamPos = p_uniforms.map.cameraPosition; + if (uCamPos !== void 0) { + uCamPos.setValue(_gl, _vector32.setFromMatrixPosition(camera.matrixWorld)); + } + if (capabilities.logarithmicDepthBuffer) { + p_uniforms.setValue( + _gl, + "logDepthBufFC", + 2 / (Math.log(camera.far + 1) / Math.LN2) + ); + } + if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) { + p_uniforms.setValue(_gl, "isOrthographic", camera.isOrthographicCamera === true); + } + if (_currentCamera !== camera) { + _currentCamera = camera; + refreshMaterial = true; + refreshLights = true; + } + } + if (object.isSkinnedMesh) { + p_uniforms.setOptional(_gl, object, "bindMatrix"); + p_uniforms.setOptional(_gl, object, "bindMatrixInverse"); + const skeleton = object.skeleton; + if (skeleton) { + if (capabilities.floatVertexTextures) { + if (skeleton.boneTexture === null) skeleton.computeBoneTexture(); + p_uniforms.setValue(_gl, "boneTexture", skeleton.boneTexture, textures); + } else { + console.warn("THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required."); + } + } + } + if (object.isBatchedMesh) { + p_uniforms.setOptional(_gl, object, "batchingTexture"); + p_uniforms.setValue(_gl, "batchingTexture", object._matricesTexture, textures); + } + const morphAttributes = geometry.morphAttributes; + if (morphAttributes.position !== void 0 || morphAttributes.normal !== void 0 || morphAttributes.color !== void 0 && capabilities.isWebGL2 === true) { + morphtargets.update(object, geometry, program); + } + if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) { + materialProperties.receiveShadow = object.receiveShadow; + p_uniforms.setValue(_gl, "receiveShadow", object.receiveShadow); + } + if (material.isMeshGouraudMaterial && material.envMap !== null) { + m_uniforms.envMap.value = envMap; + m_uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1; + } + if (refreshMaterial) { + p_uniforms.setValue(_gl, "toneMappingExposure", _this.toneMappingExposure); + if (materialProperties.needsLights) { + markUniformsLightsNeedsUpdate(m_uniforms, refreshLights); + } + if (fog && material.fog === true) { + materials.refreshFogUniforms(m_uniforms, fog); + } + materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget); + WebGLUniforms.upload(_gl, getUniformList(materialProperties), m_uniforms, textures); + } + if (material.isShaderMaterial && material.uniformsNeedUpdate === true) { + WebGLUniforms.upload(_gl, getUniformList(materialProperties), m_uniforms, textures); + material.uniformsNeedUpdate = false; + } + if (material.isSpriteMaterial) { + p_uniforms.setValue(_gl, "center", object.center); + } + p_uniforms.setValue(_gl, "modelViewMatrix", object.modelViewMatrix); + p_uniforms.setValue(_gl, "normalMatrix", object.normalMatrix); + p_uniforms.setValue(_gl, "modelMatrix", object.matrixWorld); + if (material.isShaderMaterial || material.isRawShaderMaterial) { + const groups = material.uniformsGroups; + for (let i = 0, l = groups.length; i < l; i++) { + if (capabilities.isWebGL2) { + const group = groups[i]; + uniformsGroups.update(group, program); + uniformsGroups.bind(group, program); + } else { + console.warn("THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2."); + } + } + } + return program; + } + function markUniformsLightsNeedsUpdate(uniforms, value) { + uniforms.ambientLightColor.needsUpdate = value; + uniforms.lightProbe.needsUpdate = value; + uniforms.directionalLights.needsUpdate = value; + uniforms.directionalLightShadows.needsUpdate = value; + uniforms.pointLights.needsUpdate = value; + uniforms.pointLightShadows.needsUpdate = value; + uniforms.spotLights.needsUpdate = value; + uniforms.spotLightShadows.needsUpdate = value; + uniforms.rectAreaLights.needsUpdate = value; + uniforms.hemisphereLights.needsUpdate = value; + } + function materialNeedsLights(material) { + return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true; + } + this.getActiveCubeFace = function() { + return _currentActiveCubeFace; + }; + this.getActiveMipmapLevel = function() { + return _currentActiveMipmapLevel; + }; + this.getRenderTarget = function() { + return _currentRenderTarget; + }; + this.setRenderTargetTextures = function(renderTarget, colorTexture, depthTexture) { + properties.get(renderTarget.texture).__webglTexture = colorTexture; + properties.get(renderTarget.depthTexture).__webglTexture = depthTexture; + const renderTargetProperties = properties.get(renderTarget); + renderTargetProperties.__hasExternalTextures = true; + if (renderTargetProperties.__hasExternalTextures) { + renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === void 0; + if (!renderTargetProperties.__autoAllocateDepthBuffer) { + if (extensions.has("WEBGL_multisampled_render_to_texture") === true) { + console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"); + renderTargetProperties.__useRenderToTexture = false; + } + } + } + }; + this.setRenderTargetFramebuffer = function(renderTarget, defaultFramebuffer) { + const renderTargetProperties = properties.get(renderTarget); + renderTargetProperties.__webglFramebuffer = defaultFramebuffer; + renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === void 0; + }; + this.setRenderTarget = function(renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) { + _currentRenderTarget = renderTarget; + _currentActiveCubeFace = activeCubeFace; + _currentActiveMipmapLevel = activeMipmapLevel; + let useDefaultFramebuffer = true; + let framebuffer = null; + let isCube = false; + let isRenderTarget3D = false; + if (renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + if (renderTargetProperties.__useDefaultFramebuffer !== void 0) { + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + useDefaultFramebuffer = false; + } else if (renderTargetProperties.__webglFramebuffer === void 0) { + textures.setupRenderTarget(renderTarget); + } else if (renderTargetProperties.__hasExternalTextures) { + textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture); + } + const texture = renderTarget.texture; + if (texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture) { + isRenderTarget3D = true; + } + const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget) { + if (Array.isArray(__webglFramebuffer[activeCubeFace])) { + framebuffer = __webglFramebuffer[activeCubeFace][activeMipmapLevel]; + } else { + framebuffer = __webglFramebuffer[activeCubeFace]; + } + isCube = true; + } else if (capabilities.isWebGL2 && renderTarget.samples > 0 && textures.useMultisampledRTT(renderTarget) === false) { + framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer; + } else { + if (Array.isArray(__webglFramebuffer)) { + framebuffer = __webglFramebuffer[activeMipmapLevel]; + } else { + framebuffer = __webglFramebuffer; + } + } + _currentViewport.copy(renderTarget.viewport); + _currentScissor.copy(renderTarget.scissor); + _currentScissorTest = renderTarget.scissorTest; + } else { + _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor(); + _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor(); + _currentScissorTest = _scissorTest; + } + const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer) { + state.drawBuffers(renderTarget, framebuffer); + } + state.viewport(_currentViewport); + state.scissor(_currentScissor); + state.setScissorTest(_currentScissorTest); + if (isCube) { + const textureProperties = properties.get(renderTarget.texture); + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel); + } else if (isRenderTarget3D) { + const textureProperties = properties.get(renderTarget.texture); + const layer = activeCubeFace || 0; + _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer); + } + _currentMaterialId = -1; + }; + this.readRenderTargetPixels = function(renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) { + if (!(renderTarget && renderTarget.isWebGLRenderTarget)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); + return; + } + let framebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== void 0) { + framebuffer = framebuffer[activeCubeFaceIndex]; + } + if (framebuffer) { + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + try { + const texture = renderTarget.texture; + const textureFormat = texture.format; + const textureType = texture.type; + if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."); + return; + } + const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has("EXT_color_buffer_half_float") || capabilities.isWebGL2 && extensions.has("EXT_color_buffer_float")); + if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513) + !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has("OES_texture_float") || extensions.has("WEBGL_color_buffer_float"))) && // Chrome Mac >= 52 and Firefox + !halfFloatSupportedByExt) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type."); + return; + } + if (x >= 0 && x <= renderTarget.width - width && (y >= 0 && y <= renderTarget.height - height)) { + _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer); + } + } finally { + const framebuffer2 = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null; + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer2); + } + } + }; + this.copyFramebufferToTexture = function(position, texture, level = 0) { + const levelScale = Math.pow(2, -level); + const width = Math.floor(texture.image.width * levelScale); + const height = Math.floor(texture.image.height * levelScale); + textures.setTexture2D(texture, 0); + _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height); + state.unbindTexture(); + }; + this.copyTextureToTexture = function(position, srcTexture, dstTexture, level = 0) { + const width = srcTexture.image.width; + const height = srcTexture.image.height; + const glFormat = utils.convert(dstTexture.format); + const glType = utils.convert(dstTexture.type); + textures.setTexture2D(dstTexture, 0); + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment); + if (srcTexture.isDataTexture) { + _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data); + } else { + if (srcTexture.isCompressedTexture) { + _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data); + } else { + _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image); + } + } + if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D); + state.unbindTexture(); + }; + this.copyTextureToTexture3D = function(sourceBox, position, srcTexture, dstTexture, level = 0) { + if (_this.isWebGL1Renderer) { + console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2."); + return; + } + const width = sourceBox.max.x - sourceBox.min.x + 1; + const height = sourceBox.max.y - sourceBox.min.y + 1; + const depth2 = sourceBox.max.z - sourceBox.min.z + 1; + const glFormat = utils.convert(dstTexture.format); + const glType = utils.convert(dstTexture.type); + let glTarget; + if (dstTexture.isData3DTexture) { + textures.setTexture3D(dstTexture, 0); + glTarget = _gl.TEXTURE_3D; + } else if (dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture) { + textures.setTexture2DArray(dstTexture, 0); + glTarget = _gl.TEXTURE_2D_ARRAY; + } else { + console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray."); + return; + } + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment); + const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH); + const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT); + const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS); + const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS); + const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES); + const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[level] : srcTexture.image; + _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width); + _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height); + _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x); + _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y); + _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z); + if (srcTexture.isDataTexture || srcTexture.isData3DTexture) { + _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth2, glFormat, glType, image.data); + } else { + if (srcTexture.isCompressedArrayTexture) { + console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."); + _gl.compressedTexSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth2, glFormat, image.data); + } else { + _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth2, glFormat, glType, image); + } + } + _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen); + _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight); + _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels); + _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows); + _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); + if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget); + state.unbindTexture(); + }; + this.initTexture = function(texture) { + if (texture.isCubeTexture) { + textures.setTextureCube(texture, 0); + } else if (texture.isData3DTexture) { + textures.setTexture3D(texture, 0); + } else if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) { + textures.setTexture2DArray(texture, 0); + } else { + textures.setTexture2D(texture, 0); + } + state.unbindTexture(); + }; + this.resetState = function() { + _currentActiveCubeFace = 0; + _currentActiveMipmapLevel = 0; + _currentRenderTarget = null; + state.reset(); + bindingStates.reset(); + }; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); + } + } + get coordinateSystem() { + return WebGLCoordinateSystem; + } + get outputColorSpace() { + return this._outputColorSpace; + } + set outputColorSpace(colorSpace) { + this._outputColorSpace = colorSpace; + const gl = this.getContext(); + gl.drawingBufferColorSpace = colorSpace === DisplayP3ColorSpace ? "display-p3" : "srgb"; + gl.unpackColorSpace = ColorManagement.workingColorSpace === LinearDisplayP3ColorSpace ? "display-p3" : "srgb"; + } + get outputEncoding() { + console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."); + return this.outputColorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding; + } + set outputEncoding(encoding) { + console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."); + this.outputColorSpace = encoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace; + } + get useLegacyLights() { + console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."); + return this._useLegacyLights; + } + set useLegacyLights(value) { + console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."); + this._useLegacyLights = value; + } + }; + var WebGL1Renderer = class extends WebGLRenderer { + }; + WebGL1Renderer.prototype.isWebGL1Renderer = true; + var FogExp2 = class _FogExp2 { + constructor(color, density = 25e-5) { + this.isFogExp2 = true; + this.name = ""; + this.color = new Color(color); + this.density = density; + } + clone() { + return new _FogExp2(this.color, this.density); + } + toJSON() { + return { + type: "FogExp2", + name: this.name, + color: this.color.getHex(), + density: this.density + }; + } + }; + var Fog = class _Fog { + constructor(color, near = 1, far = 1e3) { + this.isFog = true; + this.name = ""; + this.color = new Color(color); + this.near = near; + this.far = far; + } + clone() { + return new _Fog(this.color, this.near, this.far); + } + toJSON() { + return { + type: "Fog", + name: this.name, + color: this.color.getHex(), + near: this.near, + far: this.far + }; + } + }; + var Scene = class extends Object3D { + constructor() { + super(); + this.isScene = true; + this.type = "Scene"; + this.background = null; + this.environment = null; + this.fog = null; + this.backgroundBlurriness = 0; + this.backgroundIntensity = 1; + this.overrideMaterial = null; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); + } + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.background !== null) this.background = source.background.clone(); + if (source.environment !== null) this.environment = source.environment.clone(); + if (source.fog !== null) this.fog = source.fog.clone(); + this.backgroundBlurriness = source.backgroundBlurriness; + this.backgroundIntensity = source.backgroundIntensity; + if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone(); + this.matrixAutoUpdate = source.matrixAutoUpdate; + return this; + } + toJSON(meta) { + const data = super.toJSON(meta); + if (this.fog !== null) data.object.fog = this.fog.toJSON(); + if (this.backgroundBlurriness > 0) data.object.backgroundBlurriness = this.backgroundBlurriness; + if (this.backgroundIntensity !== 1) data.object.backgroundIntensity = this.backgroundIntensity; + return data; + } + }; + var InterleavedBuffer = class { + constructor(array, stride) { + this.isInterleavedBuffer = true; + this.array = array; + this.stride = stride; + this.count = array !== void 0 ? array.length / stride : 0; + this.usage = StaticDrawUsage; + this._updateRange = { offset: 0, count: -1 }; + this.updateRanges = []; + this.version = 0; + this.uuid = generateUUID(); + } + onUploadCallback() { + } + set needsUpdate(value) { + if (value === true) this.version++; + } + get updateRange() { + console.warn("THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead."); + return this._updateRange; + } + setUsage(value) { + this.usage = value; + return this; + } + addUpdateRange(start, count) { + this.updateRanges.push({ start, count }); + } + clearUpdateRanges() { + this.updateRanges.length = 0; + } + copy(source) { + this.array = new source.array.constructor(source.array); + this.count = source.count; + this.stride = source.stride; + this.usage = source.usage; + return this; + } + copyAt(index1, attribute, index2) { + index1 *= this.stride; + index2 *= attribute.stride; + for (let i = 0, l = this.stride; i < l; i++) { + this.array[index1 + i] = attribute.array[index2 + i]; + } + return this; + } + set(value, offset = 0) { + this.array.set(value, offset); + return this; + } + clone(data) { + if (data.arrayBuffers === void 0) { + data.arrayBuffers = {}; + } + if (this.array.buffer._uuid === void 0) { + this.array.buffer._uuid = generateUUID(); + } + if (data.arrayBuffers[this.array.buffer._uuid] === void 0) { + data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer; + } + const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]); + const ib = new this.constructor(array, this.stride); + ib.setUsage(this.usage); + return ib; + } + onUpload(callback) { + this.onUploadCallback = callback; + return this; + } + toJSON(data) { + if (data.arrayBuffers === void 0) { + data.arrayBuffers = {}; + } + if (this.array.buffer._uuid === void 0) { + this.array.buffer._uuid = generateUUID(); + } + if (data.arrayBuffers[this.array.buffer._uuid] === void 0) { + data.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer)); + } + return { + uuid: this.uuid, + buffer: this.array.buffer._uuid, + type: this.array.constructor.name, + stride: this.stride + }; + } + }; + var _vector$6 = /* @__PURE__ */ new Vector3(); + var InterleavedBufferAttribute = class _InterleavedBufferAttribute { + constructor(interleavedBuffer, itemSize, offset, normalized = false) { + this.isInterleavedBufferAttribute = true; + this.name = ""; + this.data = interleavedBuffer; + this.itemSize = itemSize; + this.offset = offset; + this.normalized = normalized; + } + get count() { + return this.data.count; + } + get array() { + return this.data.array; + } + set needsUpdate(value) { + this.data.needsUpdate = value; + } + applyMatrix4(m) { + for (let i = 0, l = this.data.count; i < l; i++) { + _vector$6.fromBufferAttribute(this, i); + _vector$6.applyMatrix4(m); + this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z); + } + return this; + } + applyNormalMatrix(m) { + for (let i = 0, l = this.count; i < l; i++) { + _vector$6.fromBufferAttribute(this, i); + _vector$6.applyNormalMatrix(m); + this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z); + } + return this; + } + transformDirection(m) { + for (let i = 0, l = this.count; i < l; i++) { + _vector$6.fromBufferAttribute(this, i); + _vector$6.transformDirection(m); + this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z); + } + return this; + } + setX(index, x) { + if (this.normalized) x = normalize(x, this.array); + this.data.array[index * this.data.stride + this.offset] = x; + return this; + } + setY(index, y) { + if (this.normalized) y = normalize(y, this.array); + this.data.array[index * this.data.stride + this.offset + 1] = y; + return this; + } + setZ(index, z) { + if (this.normalized) z = normalize(z, this.array); + this.data.array[index * this.data.stride + this.offset + 2] = z; + return this; + } + setW(index, w) { + if (this.normalized) w = normalize(w, this.array); + this.data.array[index * this.data.stride + this.offset + 3] = w; + return this; + } + getX(index) { + let x = this.data.array[index * this.data.stride + this.offset]; + if (this.normalized) x = denormalize(x, this.array); + return x; + } + getY(index) { + let y = this.data.array[index * this.data.stride + this.offset + 1]; + if (this.normalized) y = denormalize(y, this.array); + return y; + } + getZ(index) { + let z = this.data.array[index * this.data.stride + this.offset + 2]; + if (this.normalized) z = denormalize(z, this.array); + return z; + } + getW(index) { + let w = this.data.array[index * this.data.stride + this.offset + 3]; + if (this.normalized) w = denormalize(w, this.array); + return w; + } + setXY(index, x, y) { + index = index * this.data.stride + this.offset; + if (this.normalized) { + x = normalize(x, this.array); + y = normalize(y, this.array); + } + this.data.array[index + 0] = x; + this.data.array[index + 1] = y; + return this; + } + setXYZ(index, x, y, z) { + index = index * this.data.stride + this.offset; + if (this.normalized) { + x = normalize(x, this.array); + y = normalize(y, this.array); + z = normalize(z, this.array); + } + this.data.array[index + 0] = x; + this.data.array[index + 1] = y; + this.data.array[index + 2] = z; + return this; + } + setXYZW(index, x, y, z, w) { + index = index * this.data.stride + this.offset; + if (this.normalized) { + x = normalize(x, this.array); + y = normalize(y, this.array); + z = normalize(z, this.array); + w = normalize(w, this.array); + } + this.data.array[index + 0] = x; + this.data.array[index + 1] = y; + this.data.array[index + 2] = z; + this.data.array[index + 3] = w; + return this; + } + clone(data) { + if (data === void 0) { + console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data."); + const array = []; + for (let i = 0; i < this.count; i++) { + const index = i * this.data.stride + this.offset; + for (let j = 0; j < this.itemSize; j++) { + array.push(this.data.array[index + j]); + } + } + return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized); + } else { + if (data.interleavedBuffers === void 0) { + data.interleavedBuffers = {}; + } + if (data.interleavedBuffers[this.data.uuid] === void 0) { + data.interleavedBuffers[this.data.uuid] = this.data.clone(data); + } + return new _InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized); + } + } + toJSON(data) { + if (data === void 0) { + console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data."); + const array = []; + for (let i = 0; i < this.count; i++) { + const index = i * this.data.stride + this.offset; + for (let j = 0; j < this.itemSize; j++) { + array.push(this.data.array[index + j]); + } + } + return { + itemSize: this.itemSize, + type: this.array.constructor.name, + array, + normalized: this.normalized + }; + } else { + if (data.interleavedBuffers === void 0) { + data.interleavedBuffers = {}; + } + if (data.interleavedBuffers[this.data.uuid] === void 0) { + data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data); + } + return { + isInterleavedBufferAttribute: true, + itemSize: this.itemSize, + data: this.data.uuid, + offset: this.offset, + normalized: this.normalized + }; + } + } + }; + var SpriteMaterial = class extends Material { + constructor(parameters) { + super(); + this.isSpriteMaterial = true; + this.type = "SpriteMaterial"; + this.color = new Color(16777215); + this.map = null; + this.alphaMap = null; + this.rotation = 0; + this.sizeAttenuation = true; + this.transparent = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.rotation = source.rotation; + this.sizeAttenuation = source.sizeAttenuation; + this.fog = source.fog; + return this; + } + }; + var _geometry; + var _intersectPoint = /* @__PURE__ */ new Vector3(); + var _worldScale = /* @__PURE__ */ new Vector3(); + var _mvPosition = /* @__PURE__ */ new Vector3(); + var _alignedPosition = /* @__PURE__ */ new Vector2(); + var _rotatedPosition = /* @__PURE__ */ new Vector2(); + var _viewWorldMatrix = /* @__PURE__ */ new Matrix4(); + var _vA = /* @__PURE__ */ new Vector3(); + var _vB = /* @__PURE__ */ new Vector3(); + var _vC = /* @__PURE__ */ new Vector3(); + var _uvA = /* @__PURE__ */ new Vector2(); + var _uvB = /* @__PURE__ */ new Vector2(); + var _uvC = /* @__PURE__ */ new Vector2(); + var Sprite = class extends Object3D { + constructor(material = new SpriteMaterial()) { + super(); + this.isSprite = true; + this.type = "Sprite"; + if (_geometry === void 0) { + _geometry = new BufferGeometry(); + const float32Array = new Float32Array([ + -0.5, + -0.5, + 0, + 0, + 0, + 0.5, + -0.5, + 0, + 1, + 0, + 0.5, + 0.5, + 0, + 1, + 1, + -0.5, + 0.5, + 0, + 0, + 1 + ]); + const interleavedBuffer = new InterleavedBuffer(float32Array, 5); + _geometry.setIndex([0, 1, 2, 0, 2, 3]); + _geometry.setAttribute("position", new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false)); + _geometry.setAttribute("uv", new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false)); + } + this.geometry = _geometry; + this.material = material; + this.center = new Vector2(0.5, 0.5); + } + raycast(raycaster, intersects2) { + if (raycaster.camera === null) { + console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'); + } + _worldScale.setFromMatrixScale(this.matrixWorld); + _viewWorldMatrix.copy(raycaster.camera.matrixWorld); + this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld); + _mvPosition.setFromMatrixPosition(this.modelViewMatrix); + if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) { + _worldScale.multiplyScalar(-_mvPosition.z); + } + const rotation = this.material.rotation; + let sin, cos; + if (rotation !== 0) { + cos = Math.cos(rotation); + sin = Math.sin(rotation); + } + const center = this.center; + transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos); + transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos); + transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos); + _uvA.set(0, 0); + _uvB.set(1, 0); + _uvC.set(1, 1); + let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint); + if (intersect === null) { + transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos); + _uvB.set(0, 1); + intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint); + if (intersect === null) { + return; + } + } + const distance = raycaster.ray.origin.distanceTo(_intersectPoint); + if (distance < raycaster.near || distance > raycaster.far) return; + intersects2.push({ + distance, + point: _intersectPoint.clone(), + uv: Triangle.getInterpolation(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()), + face: null, + object: this + }); + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.center !== void 0) this.center.copy(source.center); + this.material = source.material; + return this; + } + }; + function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) { + _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); + if (sin !== void 0) { + _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y; + _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y; + } else { + _rotatedPosition.copy(_alignedPosition); + } + vertexPosition.copy(mvPosition); + vertexPosition.x += _rotatedPosition.x; + vertexPosition.y += _rotatedPosition.y; + vertexPosition.applyMatrix4(_viewWorldMatrix); + } + var _v1$2 = /* @__PURE__ */ new Vector3(); + var _v2$1 = /* @__PURE__ */ new Vector3(); + var LOD = class extends Object3D { + constructor() { + super(); + this._currentLevel = 0; + this.type = "LOD"; + Object.defineProperties(this, { + levels: { + enumerable: true, + value: [] + }, + isLOD: { + value: true + } + }); + this.autoUpdate = true; + } + copy(source) { + super.copy(source, false); + const levels = source.levels; + for (let i = 0, l = levels.length; i < l; i++) { + const level = levels[i]; + this.addLevel(level.object.clone(), level.distance, level.hysteresis); + } + this.autoUpdate = source.autoUpdate; + return this; + } + addLevel(object, distance = 0, hysteresis = 0) { + distance = Math.abs(distance); + const levels = this.levels; + let l; + for (l = 0; l < levels.length; l++) { + if (distance < levels[l].distance) { + break; + } + } + levels.splice(l, 0, { distance, hysteresis, object }); + this.add(object); + return this; + } + getCurrentLevel() { + return this._currentLevel; + } + getObjectForDistance(distance) { + const levels = this.levels; + if (levels.length > 0) { + let i, l; + for (i = 1, l = levels.length; i < l; i++) { + let levelDistance = levels[i].distance; + if (levels[i].object.visible) { + levelDistance -= levelDistance * levels[i].hysteresis; + } + if (distance < levelDistance) { + break; + } + } + return levels[i - 1].object; + } + return null; + } + raycast(raycaster, intersects2) { + const levels = this.levels; + if (levels.length > 0) { + _v1$2.setFromMatrixPosition(this.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_v1$2); + this.getObjectForDistance(distance).raycast(raycaster, intersects2); + } + } + update(camera) { + const levels = this.levels; + if (levels.length > 1) { + _v1$2.setFromMatrixPosition(camera.matrixWorld); + _v2$1.setFromMatrixPosition(this.matrixWorld); + const distance = _v1$2.distanceTo(_v2$1) / camera.zoom; + levels[0].object.visible = true; + let i, l; + for (i = 1, l = levels.length; i < l; i++) { + let levelDistance = levels[i].distance; + if (levels[i].object.visible) { + levelDistance -= levelDistance * levels[i].hysteresis; + } + if (distance >= levelDistance) { + levels[i - 1].object.visible = false; + levels[i].object.visible = true; + } else { + break; + } + } + this._currentLevel = i - 1; + for (; i < l; i++) { + levels[i].object.visible = false; + } + } + } + toJSON(meta) { + const data = super.toJSON(meta); + if (this.autoUpdate === false) data.object.autoUpdate = false; + data.object.levels = []; + const levels = this.levels; + for (let i = 0, l = levels.length; i < l; i++) { + const level = levels[i]; + data.object.levels.push({ + object: level.object.uuid, + distance: level.distance, + hysteresis: level.hysteresis + }); + } + return data; + } + }; + var _basePosition = /* @__PURE__ */ new Vector3(); + var _skinIndex = /* @__PURE__ */ new Vector4(); + var _skinWeight = /* @__PURE__ */ new Vector4(); + var _vector3 = /* @__PURE__ */ new Vector3(); + var _matrix4 = /* @__PURE__ */ new Matrix4(); + var _vertex = /* @__PURE__ */ new Vector3(); + var _sphere$4 = /* @__PURE__ */ new Sphere(); + var _inverseMatrix$2 = /* @__PURE__ */ new Matrix4(); + var _ray$2 = /* @__PURE__ */ new Ray(); + var SkinnedMesh = class extends Mesh { + constructor(geometry, material) { + super(geometry, material); + this.isSkinnedMesh = true; + this.type = "SkinnedMesh"; + this.bindMode = AttachedBindMode; + this.bindMatrix = new Matrix4(); + this.bindMatrixInverse = new Matrix4(); + this.boundingBox = null; + this.boundingSphere = null; + } + computeBoundingBox() { + const geometry = this.geometry; + if (this.boundingBox === null) { + this.boundingBox = new Box3(); + } + this.boundingBox.makeEmpty(); + const positionAttribute = geometry.getAttribute("position"); + for (let i = 0; i < positionAttribute.count; i++) { + this.getVertexPosition(i, _vertex); + this.boundingBox.expandByPoint(_vertex); + } + } + computeBoundingSphere() { + const geometry = this.geometry; + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere(); + } + this.boundingSphere.makeEmpty(); + const positionAttribute = geometry.getAttribute("position"); + for (let i = 0; i < positionAttribute.count; i++) { + this.getVertexPosition(i, _vertex); + this.boundingSphere.expandByPoint(_vertex); + } + } + copy(source, recursive) { + super.copy(source, recursive); + this.bindMode = source.bindMode; + this.bindMatrix.copy(source.bindMatrix); + this.bindMatrixInverse.copy(source.bindMatrixInverse); + this.skeleton = source.skeleton; + if (source.boundingBox !== null) this.boundingBox = source.boundingBox.clone(); + if (source.boundingSphere !== null) this.boundingSphere = source.boundingSphere.clone(); + return this; + } + raycast(raycaster, intersects2) { + const material = this.material; + const matrixWorld = this.matrixWorld; + if (material === void 0) return; + if (this.boundingSphere === null) this.computeBoundingSphere(); + _sphere$4.copy(this.boundingSphere); + _sphere$4.applyMatrix4(matrixWorld); + if (raycaster.ray.intersectsSphere(_sphere$4) === false) return; + _inverseMatrix$2.copy(matrixWorld).invert(); + _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); + if (this.boundingBox !== null) { + if (_ray$2.intersectsBox(this.boundingBox) === false) return; + } + this._computeIntersections(raycaster, intersects2, _ray$2); + } + getVertexPosition(index, target) { + super.getVertexPosition(index, target); + this.applyBoneTransform(index, target); + return target; + } + bind(skeleton, bindMatrix) { + this.skeleton = skeleton; + if (bindMatrix === void 0) { + this.updateMatrixWorld(true); + this.skeleton.calculateInverses(); + bindMatrix = this.matrixWorld; + } + this.bindMatrix.copy(bindMatrix); + this.bindMatrixInverse.copy(bindMatrix).invert(); + } + pose() { + this.skeleton.pose(); + } + normalizeSkinWeights() { + const vector = new Vector4(); + const skinWeight = this.geometry.attributes.skinWeight; + for (let i = 0, l = skinWeight.count; i < l; i++) { + vector.fromBufferAttribute(skinWeight, i); + const scale = 1 / vector.manhattanLength(); + if (scale !== Infinity) { + vector.multiplyScalar(scale); + } else { + vector.set(1, 0, 0, 0); + } + skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w); + } + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + if (this.bindMode === AttachedBindMode) { + this.bindMatrixInverse.copy(this.matrixWorld).invert(); + } else if (this.bindMode === DetachedBindMode) { + this.bindMatrixInverse.copy(this.bindMatrix).invert(); + } else { + console.warn("THREE.SkinnedMesh: Unrecognized bindMode: " + this.bindMode); + } + } + applyBoneTransform(index, vector) { + const skeleton = this.skeleton; + const geometry = this.geometry; + _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index); + _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index); + _basePosition.copy(vector).applyMatrix4(this.bindMatrix); + vector.set(0, 0, 0); + for (let i = 0; i < 4; i++) { + const weight = _skinWeight.getComponent(i); + if (weight !== 0) { + const boneIndex = _skinIndex.getComponent(i); + _matrix4.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]); + vector.addScaledVector(_vector3.copy(_basePosition).applyMatrix4(_matrix4), weight); + } + } + return vector.applyMatrix4(this.bindMatrixInverse); + } + boneTransform(index, vector) { + console.warn("THREE.SkinnedMesh: .boneTransform() was renamed to .applyBoneTransform() in r151."); + return this.applyBoneTransform(index, vector); + } + }; + var Bone = class extends Object3D { + constructor() { + super(); + this.isBone = true; + this.type = "Bone"; + } + }; + var DataTexture = class extends Texture { + constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace) { + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isDataTexture = true; + this.image = { data, width, height }; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + } + }; + var _offsetMatrix = /* @__PURE__ */ new Matrix4(); + var _identityMatrix$1 = /* @__PURE__ */ new Matrix4(); + var Skeleton = class _Skeleton { + constructor(bones = [], boneInverses = []) { + this.uuid = generateUUID(); + this.bones = bones.slice(0); + this.boneInverses = boneInverses; + this.boneMatrices = null; + this.boneTexture = null; + this.init(); + } + init() { + const bones = this.bones; + const boneInverses = this.boneInverses; + this.boneMatrices = new Float32Array(bones.length * 16); + if (boneInverses.length === 0) { + this.calculateInverses(); + } else { + if (bones.length !== boneInverses.length) { + console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones."); + this.boneInverses = []; + for (let i = 0, il = this.bones.length; i < il; i++) { + this.boneInverses.push(new Matrix4()); + } + } + } + } + calculateInverses() { + this.boneInverses.length = 0; + for (let i = 0, il = this.bones.length; i < il; i++) { + const inverse = new Matrix4(); + if (this.bones[i]) { + inverse.copy(this.bones[i].matrixWorld).invert(); + } + this.boneInverses.push(inverse); + } + } + pose() { + for (let i = 0, il = this.bones.length; i < il; i++) { + const bone = this.bones[i]; + if (bone) { + bone.matrixWorld.copy(this.boneInverses[i]).invert(); + } + } + for (let i = 0, il = this.bones.length; i < il; i++) { + const bone = this.bones[i]; + if (bone) { + if (bone.parent && bone.parent.isBone) { + bone.matrix.copy(bone.parent.matrixWorld).invert(); + bone.matrix.multiply(bone.matrixWorld); + } else { + bone.matrix.copy(bone.matrixWorld); + } + bone.matrix.decompose(bone.position, bone.quaternion, bone.scale); + } + } + } + update() { + const bones = this.bones; + const boneInverses = this.boneInverses; + const boneMatrices = this.boneMatrices; + const boneTexture = this.boneTexture; + for (let i = 0, il = bones.length; i < il; i++) { + const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix$1; + _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]); + _offsetMatrix.toArray(boneMatrices, i * 16); + } + if (boneTexture !== null) { + boneTexture.needsUpdate = true; + } + } + clone() { + return new _Skeleton(this.bones, this.boneInverses); + } + computeBoneTexture() { + let size = Math.sqrt(this.bones.length * 4); + size = Math.ceil(size / 4) * 4; + size = Math.max(size, 4); + const boneMatrices = new Float32Array(size * size * 4); + boneMatrices.set(this.boneMatrices); + const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType); + boneTexture.needsUpdate = true; + this.boneMatrices = boneMatrices; + this.boneTexture = boneTexture; + return this; + } + getBoneByName(name) { + for (let i = 0, il = this.bones.length; i < il; i++) { + const bone = this.bones[i]; + if (bone.name === name) { + return bone; + } + } + return void 0; + } + dispose() { + if (this.boneTexture !== null) { + this.boneTexture.dispose(); + this.boneTexture = null; + } + } + fromJSON(json, bones) { + this.uuid = json.uuid; + for (let i = 0, l = json.bones.length; i < l; i++) { + const uuid = json.bones[i]; + let bone = bones[uuid]; + if (bone === void 0) { + console.warn("THREE.Skeleton: No bone found with UUID:", uuid); + bone = new Bone(); + } + this.bones.push(bone); + this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i])); + } + this.init(); + return this; + } + toJSON() { + const data = { + metadata: { + version: 4.6, + type: "Skeleton", + generator: "Skeleton.toJSON" + }, + bones: [], + boneInverses: [] + }; + data.uuid = this.uuid; + const bones = this.bones; + const boneInverses = this.boneInverses; + for (let i = 0, l = bones.length; i < l; i++) { + const bone = bones[i]; + data.bones.push(bone.uuid); + const boneInverse = boneInverses[i]; + data.boneInverses.push(boneInverse.toArray()); + } + return data; + } + }; + var InstancedBufferAttribute = class extends BufferAttribute { + constructor(array, itemSize, normalized, meshPerAttribute = 1) { + super(array, itemSize, normalized); + this.isInstancedBufferAttribute = true; + this.meshPerAttribute = meshPerAttribute; + } + copy(source) { + super.copy(source); + this.meshPerAttribute = source.meshPerAttribute; + return this; + } + toJSON() { + const data = super.toJSON(); + data.meshPerAttribute = this.meshPerAttribute; + data.isInstancedBufferAttribute = true; + return data; + } + }; + var _instanceLocalMatrix = /* @__PURE__ */ new Matrix4(); + var _instanceWorldMatrix = /* @__PURE__ */ new Matrix4(); + var _instanceIntersects = []; + var _box3 = /* @__PURE__ */ new Box3(); + var _identity = /* @__PURE__ */ new Matrix4(); + var _mesh$1 = /* @__PURE__ */ new Mesh(); + var _sphere$3 = /* @__PURE__ */ new Sphere(); + var InstancedMesh = class extends Mesh { + constructor(geometry, material, count) { + super(geometry, material); + this.isInstancedMesh = true; + this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16); + this.instanceColor = null; + this.count = count; + this.boundingBox = null; + this.boundingSphere = null; + for (let i = 0; i < count; i++) { + this.setMatrixAt(i, _identity); + } + } + computeBoundingBox() { + const geometry = this.geometry; + const count = this.count; + if (this.boundingBox === null) { + this.boundingBox = new Box3(); + } + if (geometry.boundingBox === null) { + geometry.computeBoundingBox(); + } + this.boundingBox.makeEmpty(); + for (let i = 0; i < count; i++) { + this.getMatrixAt(i, _instanceLocalMatrix); + _box3.copy(geometry.boundingBox).applyMatrix4(_instanceLocalMatrix); + this.boundingBox.union(_box3); + } + } + computeBoundingSphere() { + const geometry = this.geometry; + const count = this.count; + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere(); + } + if (geometry.boundingSphere === null) { + geometry.computeBoundingSphere(); + } + this.boundingSphere.makeEmpty(); + for (let i = 0; i < count; i++) { + this.getMatrixAt(i, _instanceLocalMatrix); + _sphere$3.copy(geometry.boundingSphere).applyMatrix4(_instanceLocalMatrix); + this.boundingSphere.union(_sphere$3); + } + } + copy(source, recursive) { + super.copy(source, recursive); + this.instanceMatrix.copy(source.instanceMatrix); + if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone(); + this.count = source.count; + if (source.boundingBox !== null) this.boundingBox = source.boundingBox.clone(); + if (source.boundingSphere !== null) this.boundingSphere = source.boundingSphere.clone(); + return this; + } + getColorAt(index, color) { + color.fromArray(this.instanceColor.array, index * 3); + } + getMatrixAt(index, matrix) { + matrix.fromArray(this.instanceMatrix.array, index * 16); + } + raycast(raycaster, intersects2) { + const matrixWorld = this.matrixWorld; + const raycastTimes = this.count; + _mesh$1.geometry = this.geometry; + _mesh$1.material = this.material; + if (_mesh$1.material === void 0) return; + if (this.boundingSphere === null) this.computeBoundingSphere(); + _sphere$3.copy(this.boundingSphere); + _sphere$3.applyMatrix4(matrixWorld); + if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; + for (let instanceId = 0; instanceId < raycastTimes; instanceId++) { + this.getMatrixAt(instanceId, _instanceLocalMatrix); + _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); + _mesh$1.matrixWorld = _instanceWorldMatrix; + _mesh$1.raycast(raycaster, _instanceIntersects); + for (let i = 0, l = _instanceIntersects.length; i < l; i++) { + const intersect = _instanceIntersects[i]; + intersect.instanceId = instanceId; + intersect.object = this; + intersects2.push(intersect); + } + _instanceIntersects.length = 0; + } + } + setColorAt(index, color) { + if (this.instanceColor === null) { + this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3), 3); + } + color.toArray(this.instanceColor.array, index * 3); + } + setMatrixAt(index, matrix) { + matrix.toArray(this.instanceMatrix.array, index * 16); + } + updateMorphTargets() { + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + }; + function sortOpaque(a, b) { + return a.z - b.z; + } + function sortTransparent(a, b) { + return b.z - a.z; + } + var MultiDrawRenderList = class { + constructor() { + this.index = 0; + this.pool = []; + this.list = []; + } + push(drawRange, z) { + const pool = this.pool; + const list = this.list; + if (this.index >= pool.length) { + pool.push({ + start: -1, + count: -1, + z: -1 + }); + } + const item = pool[this.index]; + list.push(item); + this.index++; + item.start = drawRange.start; + item.count = drawRange.count; + item.z = z; + } + reset() { + this.list.length = 0; + this.index = 0; + } + }; + var ID_ATTR_NAME = "batchId"; + var _matrix = /* @__PURE__ */ new Matrix4(); + var _invMatrixWorld = /* @__PURE__ */ new Matrix4(); + var _identityMatrix = /* @__PURE__ */ new Matrix4(); + var _projScreenMatrix$2 = /* @__PURE__ */ new Matrix4(); + var _frustum = /* @__PURE__ */ new Frustum(); + var _box$1 = /* @__PURE__ */ new Box3(); + var _sphere$2 = /* @__PURE__ */ new Sphere(); + var _vector$5 = /* @__PURE__ */ new Vector3(); + var _renderList = /* @__PURE__ */ new MultiDrawRenderList(); + var _mesh = /* @__PURE__ */ new Mesh(); + var _batchIntersects = []; + function copyAttributeData(src, target, targetOffset = 0) { + const itemSize = target.itemSize; + if (src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor) { + const vertexCount = src.count; + for (let i = 0; i < vertexCount; i++) { + for (let c = 0; c < itemSize; c++) { + target.setComponent(i + targetOffset, c, src.getComponent(i, c)); + } + } + } else { + target.array.set(src.array, targetOffset * itemSize); + } + target.needsUpdate = true; + } + var BatchedMesh = class extends Mesh { + get maxGeometryCount() { + return this._maxGeometryCount; + } + constructor(maxGeometryCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material) { + super(new BufferGeometry(), material); + this.isBatchedMesh = true; + this.perObjectFrustumCulled = true; + this.sortObjects = true; + this.boundingBox = null; + this.boundingSphere = null; + this.customSort = null; + this._drawRanges = []; + this._reservedRanges = []; + this._visibility = []; + this._active = []; + this._bounds = []; + this._maxGeometryCount = maxGeometryCount; + this._maxVertexCount = maxVertexCount; + this._maxIndexCount = maxIndexCount; + this._geometryInitialized = false; + this._geometryCount = 0; + this._multiDrawCounts = new Int32Array(maxGeometryCount); + this._multiDrawStarts = new Int32Array(maxGeometryCount); + this._multiDrawCount = 0; + this._visibilityChanged = true; + this._matricesTexture = null; + this._initMatricesTexture(); + } + _initMatricesTexture() { + let size = Math.sqrt(this._maxGeometryCount * 4); + size = Math.ceil(size / 4) * 4; + size = Math.max(size, 4); + const matricesArray = new Float32Array(size * size * 4); + const matricesTexture = new DataTexture(matricesArray, size, size, RGBAFormat, FloatType); + this._matricesTexture = matricesTexture; + } + _initializeGeometry(reference) { + const geometry = this.geometry; + const maxVertexCount = this._maxVertexCount; + const maxGeometryCount = this._maxGeometryCount; + const maxIndexCount = this._maxIndexCount; + if (this._geometryInitialized === false) { + for (const attributeName in reference.attributes) { + const srcAttribute = reference.getAttribute(attributeName); + const { array, itemSize, normalized } = srcAttribute; + const dstArray = new array.constructor(maxVertexCount * itemSize); + const dstAttribute = new srcAttribute.constructor(dstArray, itemSize, normalized); + dstAttribute.setUsage(srcAttribute.usage); + geometry.setAttribute(attributeName, dstAttribute); + } + if (reference.getIndex() !== null) { + const indexArray = maxVertexCount > 65536 ? new Uint32Array(maxIndexCount) : new Uint16Array(maxIndexCount); + geometry.setIndex(new BufferAttribute(indexArray, 1)); + } + const idArray = maxGeometryCount > 65536 ? new Uint32Array(maxVertexCount) : new Uint16Array(maxVertexCount); + geometry.setAttribute(ID_ATTR_NAME, new BufferAttribute(idArray, 1)); + this._geometryInitialized = true; + } + } + // Make sure the geometry is compatible with the existing combined geometry atributes + _validateGeometry(geometry) { + if (geometry.getAttribute(ID_ATTR_NAME)) { + throw new Error(`BatchedMesh: Geometry cannot use attribute "${ID_ATTR_NAME}"`); + } + const batchGeometry = this.geometry; + if (Boolean(geometry.getIndex()) !== Boolean(batchGeometry.getIndex())) { + throw new Error('BatchedMesh: All geometries must consistently have "index".'); + } + for (const attributeName in batchGeometry.attributes) { + if (attributeName === ID_ATTR_NAME) { + continue; + } + if (!geometry.hasAttribute(attributeName)) { + throw new Error(`BatchedMesh: Added geometry missing "${attributeName}". All geometries must have consistent attributes.`); + } + const srcAttribute = geometry.getAttribute(attributeName); + const dstAttribute = batchGeometry.getAttribute(attributeName); + if (srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized) { + throw new Error("BatchedMesh: All attributes must have a consistent itemSize and normalized value."); + } + } + } + setCustomSort(func) { + this.customSort = func; + return this; + } + computeBoundingBox() { + if (this.boundingBox === null) { + this.boundingBox = new Box3(); + } + const geometryCount = this._geometryCount; + const boundingBox = this.boundingBox; + const active = this._active; + boundingBox.makeEmpty(); + for (let i = 0; i < geometryCount; i++) { + if (active[i] === false) continue; + this.getMatrixAt(i, _matrix); + this.getBoundingBoxAt(i, _box$1).applyMatrix4(_matrix); + boundingBox.union(_box$1); + } + } + computeBoundingSphere() { + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere(); + } + const geometryCount = this._geometryCount; + const boundingSphere = this.boundingSphere; + const active = this._active; + boundingSphere.makeEmpty(); + for (let i = 0; i < geometryCount; i++) { + if (active[i] === false) continue; + this.getMatrixAt(i, _matrix); + this.getBoundingSphereAt(i, _sphere$2).applyMatrix4(_matrix); + boundingSphere.union(_sphere$2); + } + } + addGeometry(geometry, vertexCount = -1, indexCount = -1) { + this._initializeGeometry(geometry); + this._validateGeometry(geometry); + if (this._geometryCount >= this._maxGeometryCount) { + throw new Error("BatchedMesh: Maximum geometry count reached."); + } + const reservedRange = { + vertexStart: -1, + vertexCount: -1, + indexStart: -1, + indexCount: -1 + }; + let lastRange = null; + const reservedRanges = this._reservedRanges; + const drawRanges = this._drawRanges; + const bounds = this._bounds; + if (this._geometryCount !== 0) { + lastRange = reservedRanges[reservedRanges.length - 1]; + } + if (vertexCount === -1) { + reservedRange.vertexCount = geometry.getAttribute("position").count; + } else { + reservedRange.vertexCount = vertexCount; + } + if (lastRange === null) { + reservedRange.vertexStart = 0; + } else { + reservedRange.vertexStart = lastRange.vertexStart + lastRange.vertexCount; + } + const index = geometry.getIndex(); + const hasIndex = index !== null; + if (hasIndex) { + if (indexCount === -1) { + reservedRange.indexCount = index.count; + } else { + reservedRange.indexCount = indexCount; + } + if (lastRange === null) { + reservedRange.indexStart = 0; + } else { + reservedRange.indexStart = lastRange.indexStart + lastRange.indexCount; + } + } + if (reservedRange.indexStart !== -1 && reservedRange.indexStart + reservedRange.indexCount > this._maxIndexCount || reservedRange.vertexStart + reservedRange.vertexCount > this._maxVertexCount) { + throw new Error("BatchedMesh: Reserved space request exceeds the maximum buffer size."); + } + const visibility = this._visibility; + const active = this._active; + const matricesTexture = this._matricesTexture; + const matricesArray = this._matricesTexture.image.data; + visibility.push(true); + active.push(true); + const geometryId = this._geometryCount; + this._geometryCount++; + _identityMatrix.toArray(matricesArray, geometryId * 16); + matricesTexture.needsUpdate = true; + reservedRanges.push(reservedRange); + drawRanges.push({ + start: hasIndex ? reservedRange.indexStart : reservedRange.vertexStart, + count: -1 + }); + bounds.push({ + boxInitialized: false, + box: new Box3(), + sphereInitialized: false, + sphere: new Sphere() + }); + const idAttribute = this.geometry.getAttribute(ID_ATTR_NAME); + for (let i = 0; i < reservedRange.vertexCount; i++) { + idAttribute.setX(reservedRange.vertexStart + i, geometryId); + } + idAttribute.needsUpdate = true; + this.setGeometryAt(geometryId, geometry); + return geometryId; + } + setGeometryAt(id, geometry) { + if (id >= this._geometryCount) { + throw new Error("BatchedMesh: Maximum geometry count reached."); + } + this._validateGeometry(geometry); + const batchGeometry = this.geometry; + const hasIndex = batchGeometry.getIndex() !== null; + const dstIndex = batchGeometry.getIndex(); + const srcIndex = geometry.getIndex(); + const reservedRange = this._reservedRanges[id]; + if (hasIndex && srcIndex.count > reservedRange.indexCount || geometry.attributes.position.count > reservedRange.vertexCount) { + throw new Error("BatchedMesh: Reserved space not large enough for provided geometry."); + } + const vertexStart = reservedRange.vertexStart; + const vertexCount = reservedRange.vertexCount; + for (const attributeName in batchGeometry.attributes) { + if (attributeName === ID_ATTR_NAME) { + continue; + } + const srcAttribute = geometry.getAttribute(attributeName); + const dstAttribute = batchGeometry.getAttribute(attributeName); + copyAttributeData(srcAttribute, dstAttribute, vertexStart); + const itemSize = srcAttribute.itemSize; + for (let i = srcAttribute.count, l = vertexCount; i < l; i++) { + const index = vertexStart + i; + for (let c = 0; c < itemSize; c++) { + dstAttribute.setComponent(index, c, 0); + } + } + dstAttribute.needsUpdate = true; + } + if (hasIndex) { + const indexStart = reservedRange.indexStart; + for (let i = 0; i < srcIndex.count; i++) { + dstIndex.setX(indexStart + i, vertexStart + srcIndex.getX(i)); + } + for (let i = srcIndex.count, l = reservedRange.indexCount; i < l; i++) { + dstIndex.setX(indexStart + i, vertexStart); + } + dstIndex.needsUpdate = true; + } + const bound = this._bounds[id]; + if (geometry.boundingBox !== null) { + bound.box.copy(geometry.boundingBox); + bound.boxInitialized = true; + } else { + bound.boxInitialized = false; + } + if (geometry.boundingSphere !== null) { + bound.sphere.copy(geometry.boundingSphere); + bound.sphereInitialized = true; + } else { + bound.sphereInitialized = false; + } + const drawRange = this._drawRanges[id]; + const posAttr = geometry.getAttribute("position"); + drawRange.count = hasIndex ? srcIndex.count : posAttr.count; + this._visibilityChanged = true; + return id; + } + deleteGeometry(geometryId) { + const active = this._active; + if (geometryId >= active.length || active[geometryId] === false) { + return this; + } + active[geometryId] = false; + this._visibilityChanged = true; + return this; + } + // get bounding box and compute it if it doesn't exist + getBoundingBoxAt(id, target) { + const active = this._active; + if (active[id] === false) { + return this; + } + const bound = this._bounds[id]; + const box = bound.box; + const geometry = this.geometry; + if (bound.boxInitialized === false) { + box.makeEmpty(); + const index = geometry.index; + const position = geometry.attributes.position; + const drawRange = this._drawRanges[id]; + for (let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i++) { + let iv = i; + if (index) { + iv = index.getX(iv); + } + box.expandByPoint(_vector$5.fromBufferAttribute(position, iv)); + } + bound.boxInitialized = true; + } + target.copy(box); + return target; + } + // get bounding sphere and compute it if it doesn't exist + getBoundingSphereAt(id, target) { + const active = this._active; + if (active[id] === false) { + return this; + } + const bound = this._bounds[id]; + const sphere = bound.sphere; + const geometry = this.geometry; + if (bound.sphereInitialized === false) { + sphere.makeEmpty(); + this.getBoundingBoxAt(id, _box$1); + _box$1.getCenter(sphere.center); + const index = geometry.index; + const position = geometry.attributes.position; + const drawRange = this._drawRanges[id]; + let maxRadiusSq = 0; + for (let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i++) { + let iv = i; + if (index) { + iv = index.getX(iv); + } + _vector$5.fromBufferAttribute(position, iv); + maxRadiusSq = Math.max(maxRadiusSq, sphere.center.distanceToSquared(_vector$5)); + } + sphere.radius = Math.sqrt(maxRadiusSq); + bound.sphereInitialized = true; + } + target.copy(sphere); + return target; + } + setMatrixAt(geometryId, matrix) { + const active = this._active; + const matricesTexture = this._matricesTexture; + const matricesArray = this._matricesTexture.image.data; + const geometryCount = this._geometryCount; + if (geometryId >= geometryCount || active[geometryId] === false) { + return this; + } + matrix.toArray(matricesArray, geometryId * 16); + matricesTexture.needsUpdate = true; + return this; + } + getMatrixAt(geometryId, matrix) { + const active = this._active; + const matricesArray = this._matricesTexture.image.data; + const geometryCount = this._geometryCount; + if (geometryId >= geometryCount || active[geometryId] === false) { + return null; + } + return matrix.fromArray(matricesArray, geometryId * 16); + } + setVisibleAt(geometryId, value) { + const visibility = this._visibility; + const active = this._active; + const geometryCount = this._geometryCount; + if (geometryId >= geometryCount || active[geometryId] === false || visibility[geometryId] === value) { + return this; + } + visibility[geometryId] = value; + this._visibilityChanged = true; + return this; + } + getVisibleAt(geometryId) { + const visibility = this._visibility; + const active = this._active; + const geometryCount = this._geometryCount; + if (geometryId >= geometryCount || active[geometryId] === false) { + return false; + } + return visibility[geometryId]; + } + raycast(raycaster, intersects2) { + const visibility = this._visibility; + const active = this._active; + const drawRanges = this._drawRanges; + const geometryCount = this._geometryCount; + const matrixWorld = this.matrixWorld; + const batchGeometry = this.geometry; + _mesh.material = this.material; + _mesh.geometry.index = batchGeometry.index; + _mesh.geometry.attributes = batchGeometry.attributes; + if (_mesh.geometry.boundingBox === null) { + _mesh.geometry.boundingBox = new Box3(); + } + if (_mesh.geometry.boundingSphere === null) { + _mesh.geometry.boundingSphere = new Sphere(); + } + for (let i = 0; i < geometryCount; i++) { + if (!visibility[i] || !active[i]) { + continue; + } + const drawRange = drawRanges[i]; + _mesh.geometry.setDrawRange(drawRange.start, drawRange.count); + this.getMatrixAt(i, _mesh.matrixWorld).premultiply(matrixWorld); + this.getBoundingBoxAt(i, _mesh.geometry.boundingBox); + this.getBoundingSphereAt(i, _mesh.geometry.boundingSphere); + _mesh.raycast(raycaster, _batchIntersects); + for (let j = 0, l = _batchIntersects.length; j < l; j++) { + const intersect = _batchIntersects[j]; + intersect.object = this; + intersect.batchId = i; + intersects2.push(intersect); + } + _batchIntersects.length = 0; + } + _mesh.material = null; + _mesh.geometry.index = null; + _mesh.geometry.attributes = {}; + _mesh.geometry.setDrawRange(0, Infinity); + } + copy(source) { + super.copy(source); + this.geometry = source.geometry.clone(); + this.perObjectFrustumCulled = source.perObjectFrustumCulled; + this.sortObjects = source.sortObjects; + this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null; + this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null; + this._drawRanges = source._drawRanges.map((range) => ({ ...range })); + this._reservedRanges = source._reservedRanges.map((range) => ({ ...range })); + this._visibility = source._visibility.slice(); + this._active = source._active.slice(); + this._bounds = source._bounds.map((bound) => ({ + boxInitialized: bound.boxInitialized, + box: bound.box.clone(), + sphereInitialized: bound.sphereInitialized, + sphere: bound.sphere.clone() + })); + this._maxGeometryCount = source._maxGeometryCount; + this._maxVertexCount = source._maxVertexCount; + this._maxIndexCount = source._maxIndexCount; + this._geometryInitialized = source._geometryInitialized; + this._geometryCount = source._geometryCount; + this._multiDrawCounts = source._multiDrawCounts.slice(); + this._multiDrawStarts = source._multiDrawStarts.slice(); + this._matricesTexture = source._matricesTexture.clone(); + this._matricesTexture.image.data = this._matricesTexture.image.slice(); + return this; + } + dispose() { + this.geometry.dispose(); + this._matricesTexture.dispose(); + this._matricesTexture = null; + return this; + } + onBeforeRender(renderer, scene, camera, geometry, material) { + if (!this._visibilityChanged && !this.perObjectFrustumCulled && !this.sortObjects) { + return; + } + const index = geometry.getIndex(); + const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT; + const visibility = this._visibility; + const multiDrawStarts = this._multiDrawStarts; + const multiDrawCounts = this._multiDrawCounts; + const drawRanges = this._drawRanges; + const perObjectFrustumCulled = this.perObjectFrustumCulled; + if (perObjectFrustumCulled) { + _projScreenMatrix$2.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse).multiply(this.matrixWorld); + _frustum.setFromProjectionMatrix( + _projScreenMatrix$2, + renderer.isWebGPURenderer ? WebGPUCoordinateSystem : WebGLCoordinateSystem + ); + } + let count = 0; + if (this.sortObjects) { + _invMatrixWorld.copy(this.matrixWorld).invert(); + _vector$5.setFromMatrixPosition(camera.matrixWorld).applyMatrix4(_invMatrixWorld); + for (let i = 0, l = visibility.length; i < l; i++) { + if (visibility[i]) { + this.getMatrixAt(i, _matrix); + this.getBoundingSphereAt(i, _sphere$2).applyMatrix4(_matrix); + let culled = false; + if (perObjectFrustumCulled) { + culled = !_frustum.intersectsSphere(_sphere$2); + } + if (!culled) { + const z = _vector$5.distanceTo(_sphere$2.center); + _renderList.push(drawRanges[i], z); + } + } + } + const list = _renderList.list; + const customSort = this.customSort; + if (customSort === null) { + list.sort(material.transparent ? sortTransparent : sortOpaque); + } else { + customSort.call(this, list, camera); + } + for (let i = 0, l = list.length; i < l; i++) { + const item = list[i]; + multiDrawStarts[count] = item.start * bytesPerElement; + multiDrawCounts[count] = item.count; + count++; + } + _renderList.reset(); + } else { + for (let i = 0, l = visibility.length; i < l; i++) { + if (visibility[i]) { + let culled = false; + if (perObjectFrustumCulled) { + this.getMatrixAt(i, _matrix); + this.getBoundingSphereAt(i, _sphere$2).applyMatrix4(_matrix); + culled = !_frustum.intersectsSphere(_sphere$2); + } + if (!culled) { + const range = drawRanges[i]; + multiDrawStarts[count] = range.start * bytesPerElement; + multiDrawCounts[count] = range.count; + count++; + } + } + } + } + this._multiDrawCount = count; + this._visibilityChanged = false; + } + onBeforeShadow(renderer, object, camera, shadowCamera, geometry, depthMaterial) { + this.onBeforeRender(renderer, null, shadowCamera, geometry, depthMaterial); + } + }; + var LineBasicMaterial = class extends Material { + constructor(parameters) { + super(); + this.isLineBasicMaterial = true; + this.type = "LineBasicMaterial"; + this.color = new Color(16777215); + this.map = null; + this.linewidth = 1; + this.linecap = "round"; + this.linejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.linewidth = source.linewidth; + this.linecap = source.linecap; + this.linejoin = source.linejoin; + this.fog = source.fog; + return this; + } + }; + var _start$1 = /* @__PURE__ */ new Vector3(); + var _end$1 = /* @__PURE__ */ new Vector3(); + var _inverseMatrix$1 = /* @__PURE__ */ new Matrix4(); + var _ray$1 = /* @__PURE__ */ new Ray(); + var _sphere$1 = /* @__PURE__ */ new Sphere(); + var Line = class extends Object3D { + constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) { + super(); + this.isLine = true; + this.type = "Line"; + this.geometry = geometry; + this.material = material; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + computeLineDistances() { + const geometry = this.geometry; + if (geometry.index === null) { + const positionAttribute = geometry.attributes.position; + const lineDistances = [0]; + for (let i = 1, l = positionAttribute.count; i < l; i++) { + _start$1.fromBufferAttribute(positionAttribute, i - 1); + _end$1.fromBufferAttribute(positionAttribute, i); + lineDistances[i] = lineDistances[i - 1]; + lineDistances[i] += _start$1.distanceTo(_end$1); + } + geometry.setAttribute("lineDistance", new Float32BufferAttribute(lineDistances, 1)); + } else { + console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry."); + } + return this; + } + raycast(raycaster, intersects2) { + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Line.threshold; + const drawRange = geometry.drawRange; + if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); + _sphere$1.copy(geometry.boundingSphere); + _sphere$1.applyMatrix4(matrixWorld); + _sphere$1.radius += threshold; + if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; + _inverseMatrix$1.copy(matrixWorld).invert(); + _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1); + const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3); + const localThresholdSq = localThreshold * localThreshold; + const vStart = new Vector3(); + const vEnd = new Vector3(); + const interSegment = new Vector3(); + const interRay = new Vector3(); + const step = this.isLineSegments ? 2 : 1; + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + if (index !== null) { + const start = Math.max(0, drawRange.start); + const end = Math.min(index.count, drawRange.start + drawRange.count); + for (let i = start, l = end - 1; i < l; i += step) { + const a = index.getX(i); + const b = index.getX(i + 1); + vStart.fromBufferAttribute(positionAttribute, a); + vEnd.fromBufferAttribute(positionAttribute, b); + const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment); + if (distSq > localThresholdSq) continue; + interRay.applyMatrix4(this.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(interRay); + if (distance < raycaster.near || distance > raycaster.far) continue; + intersects2.push({ + distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4(this.matrixWorld), + index: i, + face: null, + faceIndex: null, + object: this + }); + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count); + for (let i = start, l = end - 1; i < l; i += step) { + vStart.fromBufferAttribute(positionAttribute, i); + vEnd.fromBufferAttribute(positionAttribute, i + 1); + const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment); + if (distSq > localThresholdSq) continue; + interRay.applyMatrix4(this.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(interRay); + if (distance < raycaster.near || distance > raycaster.far) continue; + intersects2.push({ + distance, + // What do we want? intersection point on the ray or on the segment?? + // point: raycaster.ray.at( distance ), + point: interSegment.clone().applyMatrix4(this.matrixWorld), + index: i, + face: null, + faceIndex: null, + object: this + }); + } + } + } + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys(morphAttributes); + if (keys.length > 0) { + const morphAttribute = morphAttributes[keys[0]]; + if (morphAttribute !== void 0) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length; m < ml; m++) { + const name = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name] = m; + } + } + } + } + }; + var _start = /* @__PURE__ */ new Vector3(); + var _end = /* @__PURE__ */ new Vector3(); + var LineSegments = class extends Line { + constructor(geometry, material) { + super(geometry, material); + this.isLineSegments = true; + this.type = "LineSegments"; + } + computeLineDistances() { + const geometry = this.geometry; + if (geometry.index === null) { + const positionAttribute = geometry.attributes.position; + const lineDistances = []; + for (let i = 0, l = positionAttribute.count; i < l; i += 2) { + _start.fromBufferAttribute(positionAttribute, i); + _end.fromBufferAttribute(positionAttribute, i + 1); + lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1]; + lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end); + } + geometry.setAttribute("lineDistance", new Float32BufferAttribute(lineDistances, 1)); + } else { + console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry."); + } + return this; + } + }; + var LineLoop = class extends Line { + constructor(geometry, material) { + super(geometry, material); + this.isLineLoop = true; + this.type = "LineLoop"; + } + }; + var PointsMaterial = class extends Material { + constructor(parameters) { + super(); + this.isPointsMaterial = true; + this.type = "PointsMaterial"; + this.color = new Color(16777215); + this.map = null; + this.alphaMap = null; + this.size = 1; + this.sizeAttenuation = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.size = source.size; + this.sizeAttenuation = source.sizeAttenuation; + this.fog = source.fog; + return this; + } + }; + var _inverseMatrix = /* @__PURE__ */ new Matrix4(); + var _ray = /* @__PURE__ */ new Ray(); + var _sphere = /* @__PURE__ */ new Sphere(); + var _position$2 = /* @__PURE__ */ new Vector3(); + var Points = class extends Object3D { + constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) { + super(); + this.isPoints = true; + this.type = "Points"; + this.geometry = geometry; + this.material = material; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + raycast(raycaster, intersects2) { + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Points.threshold; + const drawRange = geometry.drawRange; + if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); + _sphere.copy(geometry.boundingSphere); + _sphere.applyMatrix4(matrixWorld); + _sphere.radius += threshold; + if (raycaster.ray.intersectsSphere(_sphere) === false) return; + _inverseMatrix.copy(matrixWorld).invert(); + _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); + const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3); + const localThresholdSq = localThreshold * localThreshold; + const index = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + if (index !== null) { + const start = Math.max(0, drawRange.start); + const end = Math.min(index.count, drawRange.start + drawRange.count); + for (let i = start, il = end; i < il; i++) { + const a = index.getX(i); + _position$2.fromBufferAttribute(positionAttribute, a); + testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects2, this); + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count); + for (let i = start, l = end; i < l; i++) { + _position$2.fromBufferAttribute(positionAttribute, i); + testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects2, this); + } + } + } + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys(morphAttributes); + if (keys.length > 0) { + const morphAttribute = morphAttributes[keys[0]]; + if (morphAttribute !== void 0) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length; m < ml; m++) { + const name = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name] = m; + } + } + } + } + }; + function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects2, object) { + const rayPointDistanceSq = _ray.distanceSqToPoint(point); + if (rayPointDistanceSq < localThresholdSq) { + const intersectPoint = new Vector3(); + _ray.closestPointToPoint(point, intersectPoint); + intersectPoint.applyMatrix4(matrixWorld); + const distance = raycaster.ray.origin.distanceTo(intersectPoint); + if (distance < raycaster.near || distance > raycaster.far) return; + intersects2.push({ + distance, + distanceToRay: Math.sqrt(rayPointDistanceSq), + point: intersectPoint, + index, + face: null, + object + }); + } + } + var VideoTexture = class extends Texture { + constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isVideoTexture = true; + this.minFilter = minFilter !== void 0 ? minFilter : LinearFilter; + this.magFilter = magFilter !== void 0 ? magFilter : LinearFilter; + this.generateMipmaps = false; + const scope = this; + function updateVideo() { + scope.needsUpdate = true; + video.requestVideoFrameCallback(updateVideo); + } + if ("requestVideoFrameCallback" in video) { + video.requestVideoFrameCallback(updateVideo); + } + } + clone() { + return new this.constructor(this.image).copy(this); + } + update() { + const video = this.image; + const hasVideoFrameCallback = "requestVideoFrameCallback" in video; + if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) { + this.needsUpdate = true; + } + } + }; + var FramebufferTexture = class extends Texture { + constructor(width, height) { + super({ width, height }); + this.isFramebufferTexture = true; + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + this.generateMipmaps = false; + this.needsUpdate = true; + } + }; + var CompressedTexture = class extends Texture { + constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace) { + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isCompressedTexture = true; + this.image = { width, height }; + this.mipmaps = mipmaps; + this.flipY = false; + this.generateMipmaps = false; + } + }; + var CompressedArrayTexture = class extends CompressedTexture { + constructor(mipmaps, width, height, depth, format, type) { + super(mipmaps, width, height, format, type); + this.isCompressedArrayTexture = true; + this.image.depth = depth; + this.wrapR = ClampToEdgeWrapping; + } + }; + var CompressedCubeTexture = class extends CompressedTexture { + constructor(images, format, type) { + super(void 0, images[0].width, images[0].height, format, type, CubeReflectionMapping); + this.isCompressedCubeTexture = true; + this.isCubeTexture = true; + this.image = images; + } + }; + var CanvasTexture = class extends Texture { + constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isCanvasTexture = true; + this.needsUpdate = true; + } + }; + var Curve = class { + constructor() { + this.type = "Curve"; + this.arcLengthDivisions = 200; + } + // Virtual base class method to overwrite and implement in subclasses + // - t [0 .. 1] + getPoint() { + console.warn("THREE.Curve: .getPoint() not implemented."); + return null; + } + // Get point at relative position in curve according to arc length + // - u [0 .. 1] + getPointAt(u, optionalTarget) { + const t = this.getUtoTmapping(u); + return this.getPoint(t, optionalTarget); + } + // Get sequence of points using getPoint( t ) + getPoints(divisions = 5) { + const points = []; + for (let d = 0; d <= divisions; d++) { + points.push(this.getPoint(d / divisions)); + } + return points; + } + // Get sequence of points using getPointAt( u ) + getSpacedPoints(divisions = 5) { + const points = []; + for (let d = 0; d <= divisions; d++) { + points.push(this.getPointAt(d / divisions)); + } + return points; + } + // Get total curve arc length + getLength() { + const lengths = this.getLengths(); + return lengths[lengths.length - 1]; + } + // Get list of cumulative segment lengths + getLengths(divisions = this.arcLengthDivisions) { + if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) { + return this.cacheArcLengths; + } + this.needsUpdate = false; + const cache = []; + let current, last = this.getPoint(0); + let sum = 0; + cache.push(0); + for (let p = 1; p <= divisions; p++) { + current = this.getPoint(p / divisions); + sum += current.distanceTo(last); + cache.push(sum); + last = current; + } + this.cacheArcLengths = cache; + return cache; + } + updateArcLengths() { + this.needsUpdate = true; + this.getLengths(); + } + // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant + getUtoTmapping(u, distance) { + const arcLengths = this.getLengths(); + let i = 0; + const il = arcLengths.length; + let targetArcLength; + if (distance) { + targetArcLength = distance; + } else { + targetArcLength = u * arcLengths[il - 1]; + } + let low = 0, high = il - 1, comparison; + while (low <= high) { + i = Math.floor(low + (high - low) / 2); + comparison = arcLengths[i] - targetArcLength; + if (comparison < 0) { + low = i + 1; + } else if (comparison > 0) { + high = i - 1; + } else { + high = i; + break; + } + } + i = high; + if (arcLengths[i] === targetArcLength) { + return i / (il - 1); + } + const lengthBefore = arcLengths[i]; + const lengthAfter = arcLengths[i + 1]; + const segmentLength = lengthAfter - lengthBefore; + const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; + const t = (i + segmentFraction) / (il - 1); + return t; + } + // Returns a unit vector tangent at t + // In case any sub curve does not implement its tangent derivation, + // 2 points a small delta apart will be used to find its gradient + // which seems to give a reasonable approximation + getTangent(t, optionalTarget) { + const delta = 1e-4; + let t1 = t - delta; + let t2 = t + delta; + if (t1 < 0) t1 = 0; + if (t2 > 1) t2 = 1; + const pt1 = this.getPoint(t1); + const pt2 = this.getPoint(t2); + const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3()); + tangent.copy(pt2).sub(pt1).normalize(); + return tangent; + } + getTangentAt(u, optionalTarget) { + const t = this.getUtoTmapping(u); + return this.getTangent(t, optionalTarget); + } + computeFrenetFrames(segments, closed) { + const normal = new Vector3(); + const tangents = []; + const normals = []; + const binormals = []; + const vec = new Vector3(); + const mat = new Matrix4(); + for (let i = 0; i <= segments; i++) { + const u = i / segments; + tangents[i] = this.getTangentAt(u, new Vector3()); + } + normals[0] = new Vector3(); + binormals[0] = new Vector3(); + let min = Number.MAX_VALUE; + const tx = Math.abs(tangents[0].x); + const ty = Math.abs(tangents[0].y); + const tz = Math.abs(tangents[0].z); + if (tx <= min) { + min = tx; + normal.set(1, 0, 0); + } + if (ty <= min) { + min = ty; + normal.set(0, 1, 0); + } + if (tz <= min) { + normal.set(0, 0, 1); + } + vec.crossVectors(tangents[0], normal).normalize(); + normals[0].crossVectors(tangents[0], vec); + binormals[0].crossVectors(tangents[0], normals[0]); + for (let i = 1; i <= segments; i++) { + normals[i] = normals[i - 1].clone(); + binormals[i] = binormals[i - 1].clone(); + vec.crossVectors(tangents[i - 1], tangents[i]); + if (vec.length() > Number.EPSILON) { + vec.normalize(); + const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); + normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta)); + } + binormals[i].crossVectors(tangents[i], normals[i]); + } + if (closed === true) { + let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1)); + theta /= segments; + if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) { + theta = -theta; + } + for (let i = 1; i <= segments; i++) { + normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i)); + binormals[i].crossVectors(tangents[i], normals[i]); + } + } + return { + tangents, + normals, + binormals + }; + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.arcLengthDivisions = source.arcLengthDivisions; + return this; + } + toJSON() { + const data = { + metadata: { + version: 4.6, + type: "Curve", + generator: "Curve.toJSON" + } + }; + data.arcLengthDivisions = this.arcLengthDivisions; + data.type = this.type; + return data; + } + fromJSON(json) { + this.arcLengthDivisions = json.arcLengthDivisions; + return this; + } + }; + var EllipseCurve = class extends Curve { + constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) { + super(); + this.isEllipseCurve = true; + this.type = "EllipseCurve"; + this.aX = aX; + this.aY = aY; + this.xRadius = xRadius; + this.yRadius = yRadius; + this.aStartAngle = aStartAngle; + this.aEndAngle = aEndAngle; + this.aClockwise = aClockwise; + this.aRotation = aRotation; + } + getPoint(t, optionalTarget) { + const point = optionalTarget || new Vector2(); + const twoPi = Math.PI * 2; + let deltaAngle = this.aEndAngle - this.aStartAngle; + const samePoints = Math.abs(deltaAngle) < Number.EPSILON; + while (deltaAngle < 0) deltaAngle += twoPi; + while (deltaAngle > twoPi) deltaAngle -= twoPi; + if (deltaAngle < Number.EPSILON) { + if (samePoints) { + deltaAngle = 0; + } else { + deltaAngle = twoPi; + } + } + if (this.aClockwise === true && !samePoints) { + if (deltaAngle === twoPi) { + deltaAngle = -twoPi; + } else { + deltaAngle = deltaAngle - twoPi; + } + } + const angle = this.aStartAngle + t * deltaAngle; + let x = this.aX + this.xRadius * Math.cos(angle); + let y = this.aY + this.yRadius * Math.sin(angle); + if (this.aRotation !== 0) { + const cos = Math.cos(this.aRotation); + const sin = Math.sin(this.aRotation); + const tx = x - this.aX; + const ty = y - this.aY; + x = tx * cos - ty * sin + this.aX; + y = tx * sin + ty * cos + this.aY; + } + return point.set(x, y); + } + copy(source) { + super.copy(source); + this.aX = source.aX; + this.aY = source.aY; + this.xRadius = source.xRadius; + this.yRadius = source.yRadius; + this.aStartAngle = source.aStartAngle; + this.aEndAngle = source.aEndAngle; + this.aClockwise = source.aClockwise; + this.aRotation = source.aRotation; + return this; + } + toJSON() { + const data = super.toJSON(); + data.aX = this.aX; + data.aY = this.aY; + data.xRadius = this.xRadius; + data.yRadius = this.yRadius; + data.aStartAngle = this.aStartAngle; + data.aEndAngle = this.aEndAngle; + data.aClockwise = this.aClockwise; + data.aRotation = this.aRotation; + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.aX = json.aX; + this.aY = json.aY; + this.xRadius = json.xRadius; + this.yRadius = json.yRadius; + this.aStartAngle = json.aStartAngle; + this.aEndAngle = json.aEndAngle; + this.aClockwise = json.aClockwise; + this.aRotation = json.aRotation; + return this; + } + }; + var ArcCurve = class extends EllipseCurve { + constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); + this.isArcCurve = true; + this.type = "ArcCurve"; + } + }; + function CubicPoly() { + let c0 = 0, c1 = 0, c2 = 0, c3 = 0; + function init(x0, x1, t0, t1) { + c0 = x0; + c1 = t0; + c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1; + c3 = 2 * x0 - 2 * x1 + t0 + t1; + } + return { + initCatmullRom: function(x0, x1, x2, x3, tension) { + init(x1, x2, tension * (x2 - x0), tension * (x3 - x1)); + }, + initNonuniformCatmullRom: function(x0, x1, x2, x3, dt0, dt1, dt2) { + let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1; + let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; + t1 *= dt1; + t2 *= dt1; + init(x1, x2, t1, t2); + }, + calc: function(t) { + const t2 = t * t; + const t3 = t2 * t; + return c0 + c1 * t + c2 * t2 + c3 * t3; + } + }; + } + var tmp = /* @__PURE__ */ new Vector3(); + var px = /* @__PURE__ */ new CubicPoly(); + var py = /* @__PURE__ */ new CubicPoly(); + var pz = /* @__PURE__ */ new CubicPoly(); + var CatmullRomCurve3 = class extends Curve { + constructor(points = [], closed = false, curveType = "centripetal", tension = 0.5) { + super(); + this.isCatmullRomCurve3 = true; + this.type = "CatmullRomCurve3"; + this.points = points; + this.closed = closed; + this.curveType = curveType; + this.tension = tension; + } + getPoint(t, optionalTarget = new Vector3()) { + const point = optionalTarget; + const points = this.points; + const l = points.length; + const p = (l - (this.closed ? 0 : 1)) * t; + let intPoint = Math.floor(p); + let weight = p - intPoint; + if (this.closed) { + intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l; + } else if (weight === 0 && intPoint === l - 1) { + intPoint = l - 2; + weight = 1; + } + let p0, p3; + if (this.closed || intPoint > 0) { + p0 = points[(intPoint - 1) % l]; + } else { + tmp.subVectors(points[0], points[1]).add(points[0]); + p0 = tmp; + } + const p1 = points[intPoint % l]; + const p2 = points[(intPoint + 1) % l]; + if (this.closed || intPoint + 2 < l) { + p3 = points[(intPoint + 2) % l]; + } else { + tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]); + p3 = tmp; + } + if (this.curveType === "centripetal" || this.curveType === "chordal") { + const pow = this.curveType === "chordal" ? 0.5 : 0.25; + let dt0 = Math.pow(p0.distanceToSquared(p1), pow); + let dt1 = Math.pow(p1.distanceToSquared(p2), pow); + let dt2 = Math.pow(p2.distanceToSquared(p3), pow); + if (dt1 < 1e-4) dt1 = 1; + if (dt0 < 1e-4) dt0 = dt1; + if (dt2 < 1e-4) dt2 = dt1; + px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2); + py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2); + pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2); + } else if (this.curveType === "catmullrom") { + px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension); + py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension); + pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension); + } + point.set( + px.calc(weight), + py.calc(weight), + pz.calc(weight) + ); + return point; + } + copy(source) { + super.copy(source); + this.points = []; + for (let i = 0, l = source.points.length; i < l; i++) { + const point = source.points[i]; + this.points.push(point.clone()); + } + this.closed = source.closed; + this.curveType = source.curveType; + this.tension = source.tension; + return this; + } + toJSON() { + const data = super.toJSON(); + data.points = []; + for (let i = 0, l = this.points.length; i < l; i++) { + const point = this.points[i]; + data.points.push(point.toArray()); + } + data.closed = this.closed; + data.curveType = this.curveType; + data.tension = this.tension; + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.points = []; + for (let i = 0, l = json.points.length; i < l; i++) { + const point = json.points[i]; + this.points.push(new Vector3().fromArray(point)); + } + this.closed = json.closed; + this.curveType = json.curveType; + this.tension = json.tension; + return this; + } + }; + function CatmullRom(t, p0, p1, p2, p3) { + const v0 = (p2 - p0) * 0.5; + const v1 = (p3 - p1) * 0.5; + const t2 = t * t; + const t3 = t * t2; + return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; + } + function QuadraticBezierP0(t, p) { + const k = 1 - t; + return k * k * p; + } + function QuadraticBezierP1(t, p) { + return 2 * (1 - t) * t * p; + } + function QuadraticBezierP2(t, p) { + return t * t * p; + } + function QuadraticBezier(t, p0, p1, p2) { + return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2); + } + function CubicBezierP0(t, p) { + const k = 1 - t; + return k * k * k * p; + } + function CubicBezierP1(t, p) { + const k = 1 - t; + return 3 * k * k * t * p; + } + function CubicBezierP2(t, p) { + return 3 * (1 - t) * t * t * p; + } + function CubicBezierP3(t, p) { + return t * t * t * p; + } + function CubicBezier(t, p0, p1, p2, p3) { + return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3); + } + var CubicBezierCurve = class extends Curve { + constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) { + super(); + this.isCubicBezierCurve = true; + this.type = "CubicBezierCurve"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + } + getPoint(t, optionalTarget = new Vector2()) { + const point = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + point.set( + CubicBezier(t, v0.x, v1.x, v2.x, v3.x), + CubicBezier(t, v0.y, v1.y, v2.y, v3.y) + ); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + this.v3.copy(source.v3); + return this; + } + toJSON() { + const data = super.toJSON(); + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + this.v3.fromArray(json.v3); + return this; + } + }; + var CubicBezierCurve3 = class extends Curve { + constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) { + super(); + this.isCubicBezierCurve3 = true; + this.type = "CubicBezierCurve3"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + } + getPoint(t, optionalTarget = new Vector3()) { + const point = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + point.set( + CubicBezier(t, v0.x, v1.x, v2.x, v3.x), + CubicBezier(t, v0.y, v1.y, v2.y, v3.y), + CubicBezier(t, v0.z, v1.z, v2.z, v3.z) + ); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + this.v3.copy(source.v3); + return this; + } + toJSON() { + const data = super.toJSON(); + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + data.v3 = this.v3.toArray(); + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + this.v3.fromArray(json.v3); + return this; + } + }; + var LineCurve = class extends Curve { + constructor(v1 = new Vector2(), v2 = new Vector2()) { + super(); + this.isLineCurve = true; + this.type = "LineCurve"; + this.v1 = v1; + this.v2 = v2; + } + getPoint(t, optionalTarget = new Vector2()) { + const point = optionalTarget; + if (t === 1) { + point.copy(this.v2); + } else { + point.copy(this.v2).sub(this.v1); + point.multiplyScalar(t).add(this.v1); + } + return point; + } + // Line curve is linear, so we can overwrite default getPointAt + getPointAt(u, optionalTarget) { + return this.getPoint(u, optionalTarget); + } + getTangent(t, optionalTarget = new Vector2()) { + return optionalTarget.subVectors(this.v2, this.v1).normalize(); + } + getTangentAt(u, optionalTarget) { + return this.getTangent(u, optionalTarget); + } + copy(source) { + super.copy(source); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data = super.toJSON(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } + }; + var LineCurve3 = class extends Curve { + constructor(v1 = new Vector3(), v2 = new Vector3()) { + super(); + this.isLineCurve3 = true; + this.type = "LineCurve3"; + this.v1 = v1; + this.v2 = v2; + } + getPoint(t, optionalTarget = new Vector3()) { + const point = optionalTarget; + if (t === 1) { + point.copy(this.v2); + } else { + point.copy(this.v2).sub(this.v1); + point.multiplyScalar(t).add(this.v1); + } + return point; + } + // Line curve is linear, so we can overwrite default getPointAt + getPointAt(u, optionalTarget) { + return this.getPoint(u, optionalTarget); + } + getTangent(t, optionalTarget = new Vector3()) { + return optionalTarget.subVectors(this.v2, this.v1).normalize(); + } + getTangentAt(u, optionalTarget) { + return this.getTangent(u, optionalTarget); + } + copy(source) { + super.copy(source); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data = super.toJSON(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } + }; + var QuadraticBezierCurve = class extends Curve { + constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) { + super(); + this.isQuadraticBezierCurve = true; + this.type = "QuadraticBezierCurve"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + } + getPoint(t, optionalTarget = new Vector2()) { + const point = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + point.set( + QuadraticBezier(t, v0.x, v1.x, v2.x), + QuadraticBezier(t, v0.y, v1.y, v2.y) + ); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data = super.toJSON(); + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } + }; + var QuadraticBezierCurve3 = class extends Curve { + constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) { + super(); + this.isQuadraticBezierCurve3 = true; + this.type = "QuadraticBezierCurve3"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + } + getPoint(t, optionalTarget = new Vector3()) { + const point = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + point.set( + QuadraticBezier(t, v0.x, v1.x, v2.x), + QuadraticBezier(t, v0.y, v1.y, v2.y), + QuadraticBezier(t, v0.z, v1.z, v2.z) + ); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data = super.toJSON(); + data.v0 = this.v0.toArray(); + data.v1 = this.v1.toArray(); + data.v2 = this.v2.toArray(); + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } + }; + var SplineCurve = class extends Curve { + constructor(points = []) { + super(); + this.isSplineCurve = true; + this.type = "SplineCurve"; + this.points = points; + } + getPoint(t, optionalTarget = new Vector2()) { + const point = optionalTarget; + const points = this.points; + const p = (points.length - 1) * t; + const intPoint = Math.floor(p); + const weight = p - intPoint; + const p0 = points[intPoint === 0 ? intPoint : intPoint - 1]; + const p1 = points[intPoint]; + const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1]; + const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2]; + point.set( + CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), + CatmullRom(weight, p0.y, p1.y, p2.y, p3.y) + ); + return point; + } + copy(source) { + super.copy(source); + this.points = []; + for (let i = 0, l = source.points.length; i < l; i++) { + const point = source.points[i]; + this.points.push(point.clone()); + } + return this; + } + toJSON() { + const data = super.toJSON(); + data.points = []; + for (let i = 0, l = this.points.length; i < l; i++) { + const point = this.points[i]; + data.points.push(point.toArray()); + } + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.points = []; + for (let i = 0, l = json.points.length; i < l; i++) { + const point = json.points[i]; + this.points.push(new Vector2().fromArray(point)); + } + return this; + } + }; + var Curves = /* @__PURE__ */ Object.freeze({ + __proto__: null, + ArcCurve, + CatmullRomCurve3, + CubicBezierCurve, + CubicBezierCurve3, + EllipseCurve, + LineCurve, + LineCurve3, + QuadraticBezierCurve, + QuadraticBezierCurve3, + SplineCurve + }); + var CurvePath = class extends Curve { + constructor() { + super(); + this.type = "CurvePath"; + this.curves = []; + this.autoClose = false; + } + add(curve) { + this.curves.push(curve); + } + closePath() { + const startPoint = this.curves[0].getPoint(0); + const endPoint = this.curves[this.curves.length - 1].getPoint(1); + if (!startPoint.equals(endPoint)) { + const lineType = startPoint.isVector2 === true ? "LineCurve" : "LineCurve3"; + this.curves.push(new Curves[lineType](endPoint, startPoint)); + } + return this; + } + // To get accurate point with reference to + // entire path distance at time t, + // following has to be done: + // 1. Length of each sub path have to be known + // 2. Locate and identify type of curve + // 3. Get t for the curve + // 4. Return curve.getPointAt(t') + getPoint(t, optionalTarget) { + const d = t * this.getLength(); + const curveLengths = this.getCurveLengths(); + let i = 0; + while (i < curveLengths.length) { + if (curveLengths[i] >= d) { + const diff = curveLengths[i] - d; + const curve = this.curves[i]; + const segmentLength = curve.getLength(); + const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; + return curve.getPointAt(u, optionalTarget); + } + i++; + } + return null; + } + // We cannot use the default THREE.Curve getPoint() with getLength() because in + // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath + // getPoint() depends on getLength + getLength() { + const lens = this.getCurveLengths(); + return lens[lens.length - 1]; + } + // cacheLengths must be recalculated. + updateArcLengths() { + this.needsUpdate = true; + this.cacheLengths = null; + this.getCurveLengths(); + } + // Compute lengths and cache them + // We cannot overwrite getLengths() because UtoT mapping uses it. + getCurveLengths() { + if (this.cacheLengths && this.cacheLengths.length === this.curves.length) { + return this.cacheLengths; + } + const lengths = []; + let sums = 0; + for (let i = 0, l = this.curves.length; i < l; i++) { + sums += this.curves[i].getLength(); + lengths.push(sums); + } + this.cacheLengths = lengths; + return lengths; + } + getSpacedPoints(divisions = 40) { + const points = []; + for (let i = 0; i <= divisions; i++) { + points.push(this.getPoint(i / divisions)); + } + if (this.autoClose) { + points.push(points[0]); + } + return points; + } + getPoints(divisions = 12) { + const points = []; + let last; + for (let i = 0, curves = this.curves; i < curves.length; i++) { + const curve = curves[i]; + const resolution = curve.isEllipseCurve ? divisions * 2 : curve.isLineCurve || curve.isLineCurve3 ? 1 : curve.isSplineCurve ? divisions * curve.points.length : divisions; + const pts = curve.getPoints(resolution); + for (let j = 0; j < pts.length; j++) { + const point = pts[j]; + if (last && last.equals(point)) continue; + points.push(point); + last = point; + } + } + if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) { + points.push(points[0]); + } + return points; + } + copy(source) { + super.copy(source); + this.curves = []; + for (let i = 0, l = source.curves.length; i < l; i++) { + const curve = source.curves[i]; + this.curves.push(curve.clone()); + } + this.autoClose = source.autoClose; + return this; + } + toJSON() { + const data = super.toJSON(); + data.autoClose = this.autoClose; + data.curves = []; + for (let i = 0, l = this.curves.length; i < l; i++) { + const curve = this.curves[i]; + data.curves.push(curve.toJSON()); + } + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.autoClose = json.autoClose; + this.curves = []; + for (let i = 0, l = json.curves.length; i < l; i++) { + const curve = json.curves[i]; + this.curves.push(new Curves[curve.type]().fromJSON(curve)); + } + return this; + } + }; + var Path = class extends CurvePath { + constructor(points) { + super(); + this.type = "Path"; + this.currentPoint = new Vector2(); + if (points) { + this.setFromPoints(points); + } + } + setFromPoints(points) { + this.moveTo(points[0].x, points[0].y); + for (let i = 1, l = points.length; i < l; i++) { + this.lineTo(points[i].x, points[i].y); + } + return this; + } + moveTo(x, y) { + this.currentPoint.set(x, y); + return this; + } + lineTo(x, y) { + const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y)); + this.curves.push(curve); + this.currentPoint.set(x, y); + return this; + } + quadraticCurveTo(aCPx, aCPy, aX, aY) { + const curve = new QuadraticBezierCurve( + this.currentPoint.clone(), + new Vector2(aCPx, aCPy), + new Vector2(aX, aY) + ); + this.curves.push(curve); + this.currentPoint.set(aX, aY); + return this; + } + bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { + const curve = new CubicBezierCurve( + this.currentPoint.clone(), + new Vector2(aCP1x, aCP1y), + new Vector2(aCP2x, aCP2y), + new Vector2(aX, aY) + ); + this.curves.push(curve); + this.currentPoint.set(aX, aY); + return this; + } + splineThru(pts) { + const npts = [this.currentPoint.clone()].concat(pts); + const curve = new SplineCurve(npts); + this.curves.push(curve); + this.currentPoint.copy(pts[pts.length - 1]); + return this; + } + arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + this.absarc( + aX + x0, + aY + y0, + aRadius, + aStartAngle, + aEndAngle, + aClockwise + ); + return this; + } + absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); + return this; + } + ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) { + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation); + return this; + } + absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) { + const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation); + if (this.curves.length > 0) { + const firstPoint = curve.getPoint(0); + if (!firstPoint.equals(this.currentPoint)) { + this.lineTo(firstPoint.x, firstPoint.y); + } + } + this.curves.push(curve); + const lastPoint = curve.getPoint(1); + this.currentPoint.copy(lastPoint); + return this; + } + copy(source) { + super.copy(source); + this.currentPoint.copy(source.currentPoint); + return this; + } + toJSON() { + const data = super.toJSON(); + data.currentPoint = this.currentPoint.toArray(); + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.currentPoint.fromArray(json.currentPoint); + return this; + } + }; + var LatheGeometry = class _LatheGeometry extends BufferGeometry { + constructor(points = [new Vector2(0, -0.5), new Vector2(0.5, 0), new Vector2(0, 0.5)], segments = 12, phiStart = 0, phiLength = Math.PI * 2) { + super(); + this.type = "LatheGeometry"; + this.parameters = { + points, + segments, + phiStart, + phiLength + }; + segments = Math.floor(segments); + phiLength = clamp(phiLength, 0, Math.PI * 2); + const indices = []; + const vertices = []; + const uvs = []; + const initNormals = []; + const normals = []; + const inverseSegments = 1 / segments; + const vertex2 = new Vector3(); + const uv = new Vector2(); + const normal = new Vector3(); + const curNormal = new Vector3(); + const prevNormal = new Vector3(); + let dx = 0; + let dy = 0; + for (let j = 0; j <= points.length - 1; j++) { + switch (j) { + case 0: + dx = points[j + 1].x - points[j].x; + dy = points[j + 1].y - points[j].y; + normal.x = dy * 1; + normal.y = -dx; + normal.z = dy * 0; + prevNormal.copy(normal); + normal.normalize(); + initNormals.push(normal.x, normal.y, normal.z); + break; + case points.length - 1: + initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z); + break; + default: + dx = points[j + 1].x - points[j].x; + dy = points[j + 1].y - points[j].y; + normal.x = dy * 1; + normal.y = -dx; + normal.z = dy * 0; + curNormal.copy(normal); + normal.x += prevNormal.x; + normal.y += prevNormal.y; + normal.z += prevNormal.z; + normal.normalize(); + initNormals.push(normal.x, normal.y, normal.z); + prevNormal.copy(curNormal); + } + } + for (let i = 0; i <= segments; i++) { + const phi = phiStart + i * inverseSegments * phiLength; + const sin = Math.sin(phi); + const cos = Math.cos(phi); + for (let j = 0; j <= points.length - 1; j++) { + vertex2.x = points[j].x * sin; + vertex2.y = points[j].y; + vertex2.z = points[j].x * cos; + vertices.push(vertex2.x, vertex2.y, vertex2.z); + uv.x = i / segments; + uv.y = j / (points.length - 1); + uvs.push(uv.x, uv.y); + const x = initNormals[3 * j + 0] * sin; + const y = initNormals[3 * j + 1]; + const z = initNormals[3 * j + 0] * cos; + normals.push(x, y, z); + } + } + for (let i = 0; i < segments; i++) { + for (let j = 0; j < points.length - 1; j++) { + const base = j + i * points.length; + const a = base; + const b = base + points.length; + const c = base + points.length + 1; + const d = base + 1; + indices.push(a, b, d); + indices.push(c, d, b); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data) { + return new _LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength); + } + }; + var CapsuleGeometry = class _CapsuleGeometry extends LatheGeometry { + constructor(radius = 1, length = 1, capSegments = 4, radialSegments = 8) { + const path = new Path(); + path.absarc(0, -length / 2, radius, Math.PI * 1.5, 0); + path.absarc(0, length / 2, radius, 0, Math.PI * 0.5); + super(path.getPoints(capSegments), radialSegments); + this.type = "CapsuleGeometry"; + this.parameters = { + radius, + length, + capSegments, + radialSegments + }; + } + static fromJSON(data) { + return new _CapsuleGeometry(data.radius, data.length, data.capSegments, data.radialSegments); + } + }; + var CircleGeometry = class _CircleGeometry extends BufferGeometry { + constructor(radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "CircleGeometry"; + this.parameters = { + radius, + segments, + thetaStart, + thetaLength + }; + segments = Math.max(3, segments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const vertex2 = new Vector3(); + const uv = new Vector2(); + vertices.push(0, 0, 0); + normals.push(0, 0, 1); + uvs.push(0.5, 0.5); + for (let s = 0, i = 3; s <= segments; s++, i += 3) { + const segment = thetaStart + s / segments * thetaLength; + vertex2.x = radius * Math.cos(segment); + vertex2.y = radius * Math.sin(segment); + vertices.push(vertex2.x, vertex2.y, vertex2.z); + normals.push(0, 0, 1); + uv.x = (vertices[i] / radius + 1) / 2; + uv.y = (vertices[i + 1] / radius + 1) / 2; + uvs.push(uv.x, uv.y); + } + for (let i = 1; i <= segments; i++) { + indices.push(i, i + 1, 0); + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data) { + return new _CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength); + } + }; + var CylinderGeometry = class _CylinderGeometry extends BufferGeometry { + constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "CylinderGeometry"; + this.parameters = { + radiusTop, + radiusBottom, + height, + radialSegments, + heightSegments, + openEnded, + thetaStart, + thetaLength + }; + const scope = this; + radialSegments = Math.floor(radialSegments); + heightSegments = Math.floor(heightSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let index = 0; + const indexArray = []; + const halfHeight = height / 2; + let groupStart = 0; + generateTorso(); + if (openEnded === false) { + if (radiusTop > 0) generateCap(true); + if (radiusBottom > 0) generateCap(false); + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function generateTorso() { + const normal = new Vector3(); + const vertex2 = new Vector3(); + let groupCount = 0; + const slope = (radiusBottom - radiusTop) / height; + for (let y = 0; y <= heightSegments; y++) { + const indexRow = []; + const v = y / heightSegments; + const radius = v * (radiusBottom - radiusTop) + radiusTop; + for (let x = 0; x <= radialSegments; x++) { + const u = x / radialSegments; + const theta = u * thetaLength + thetaStart; + const sinTheta = Math.sin(theta); + const cosTheta = Math.cos(theta); + vertex2.x = radius * sinTheta; + vertex2.y = -v * height + halfHeight; + vertex2.z = radius * cosTheta; + vertices.push(vertex2.x, vertex2.y, vertex2.z); + normal.set(sinTheta, slope, cosTheta).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(u, 1 - v); + indexRow.push(index++); + } + indexArray.push(indexRow); + } + for (let x = 0; x < radialSegments; x++) { + for (let y = 0; y < heightSegments; y++) { + const a = indexArray[y][x]; + const b = indexArray[y + 1][x]; + const c = indexArray[y + 1][x + 1]; + const d = indexArray[y][x + 1]; + indices.push(a, b, d); + indices.push(b, c, d); + groupCount += 6; + } + } + scope.addGroup(groupStart, groupCount, 0); + groupStart += groupCount; + } + function generateCap(top) { + const centerIndexStart = index; + const uv = new Vector2(); + const vertex2 = new Vector3(); + let groupCount = 0; + const radius = top === true ? radiusTop : radiusBottom; + const sign2 = top === true ? 1 : -1; + for (let x = 1; x <= radialSegments; x++) { + vertices.push(0, halfHeight * sign2, 0); + normals.push(0, sign2, 0); + uvs.push(0.5, 0.5); + index++; + } + const centerIndexEnd = index; + for (let x = 0; x <= radialSegments; x++) { + const u = x / radialSegments; + const theta = u * thetaLength + thetaStart; + const cosTheta = Math.cos(theta); + const sinTheta = Math.sin(theta); + vertex2.x = radius * sinTheta; + vertex2.y = halfHeight * sign2; + vertex2.z = radius * cosTheta; + vertices.push(vertex2.x, vertex2.y, vertex2.z); + normals.push(0, sign2, 0); + uv.x = cosTheta * 0.5 + 0.5; + uv.y = sinTheta * 0.5 * sign2 + 0.5; + uvs.push(uv.x, uv.y); + index++; + } + for (let x = 0; x < radialSegments; x++) { + const c = centerIndexStart + x; + const i = centerIndexEnd + x; + if (top === true) { + indices.push(i, i + 1, c); + } else { + indices.push(i + 1, i, c); + } + groupCount += 3; + } + scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); + groupStart += groupCount; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data) { + return new _CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength); + } + }; + var ConeGeometry = class _ConeGeometry extends CylinderGeometry { + constructor(radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) { + super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength); + this.type = "ConeGeometry"; + this.parameters = { + radius, + height, + radialSegments, + heightSegments, + openEnded, + thetaStart, + thetaLength + }; + } + static fromJSON(data) { + return new _ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength); + } + }; + var PolyhedronGeometry = class _PolyhedronGeometry extends BufferGeometry { + constructor(vertices = [], indices = [], radius = 1, detail = 0) { + super(); + this.type = "PolyhedronGeometry"; + this.parameters = { + vertices, + indices, + radius, + detail + }; + const vertexBuffer = []; + const uvBuffer = []; + subdivide(detail); + applyRadius(radius); + generateUVs(); + this.setAttribute("position", new Float32BufferAttribute(vertexBuffer, 3)); + this.setAttribute("normal", new Float32BufferAttribute(vertexBuffer.slice(), 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvBuffer, 2)); + if (detail === 0) { + this.computeVertexNormals(); + } else { + this.normalizeNormals(); + } + function subdivide(detail2) { + const a = new Vector3(); + const b = new Vector3(); + const c = new Vector3(); + for (let i = 0; i < indices.length; i += 3) { + getVertexByIndex(indices[i + 0], a); + getVertexByIndex(indices[i + 1], b); + getVertexByIndex(indices[i + 2], c); + subdivideFace(a, b, c, detail2); + } + } + function subdivideFace(a, b, c, detail2) { + const cols = detail2 + 1; + const v = []; + for (let i = 0; i <= cols; i++) { + v[i] = []; + const aj = a.clone().lerp(c, i / cols); + const bj = b.clone().lerp(c, i / cols); + const rows = cols - i; + for (let j = 0; j <= rows; j++) { + if (j === 0 && i === cols) { + v[i][j] = aj; + } else { + v[i][j] = aj.clone().lerp(bj, j / rows); + } + } + } + for (let i = 0; i < cols; i++) { + for (let j = 0; j < 2 * (cols - i) - 1; j++) { + const k = Math.floor(j / 2); + if (j % 2 === 0) { + pushVertex(v[i][k + 1]); + pushVertex(v[i + 1][k]); + pushVertex(v[i][k]); + } else { + pushVertex(v[i][k + 1]); + pushVertex(v[i + 1][k + 1]); + pushVertex(v[i + 1][k]); + } + } + } + } + function applyRadius(radius2) { + const vertex2 = new Vector3(); + for (let i = 0; i < vertexBuffer.length; i += 3) { + vertex2.x = vertexBuffer[i + 0]; + vertex2.y = vertexBuffer[i + 1]; + vertex2.z = vertexBuffer[i + 2]; + vertex2.normalize().multiplyScalar(radius2); + vertexBuffer[i + 0] = vertex2.x; + vertexBuffer[i + 1] = vertex2.y; + vertexBuffer[i + 2] = vertex2.z; + } + } + function generateUVs() { + const vertex2 = new Vector3(); + for (let i = 0; i < vertexBuffer.length; i += 3) { + vertex2.x = vertexBuffer[i + 0]; + vertex2.y = vertexBuffer[i + 1]; + vertex2.z = vertexBuffer[i + 2]; + const u = azimuth(vertex2) / 2 / Math.PI + 0.5; + const v = inclination(vertex2) / Math.PI + 0.5; + uvBuffer.push(u, 1 - v); + } + correctUVs(); + correctSeam(); + } + function correctSeam() { + for (let i = 0; i < uvBuffer.length; i += 6) { + const x0 = uvBuffer[i + 0]; + const x1 = uvBuffer[i + 2]; + const x2 = uvBuffer[i + 4]; + const max2 = Math.max(x0, x1, x2); + const min = Math.min(x0, x1, x2); + if (max2 > 0.9 && min < 0.1) { + if (x0 < 0.2) uvBuffer[i + 0] += 1; + if (x1 < 0.2) uvBuffer[i + 2] += 1; + if (x2 < 0.2) uvBuffer[i + 4] += 1; + } + } + } + function pushVertex(vertex2) { + vertexBuffer.push(vertex2.x, vertex2.y, vertex2.z); + } + function getVertexByIndex(index, vertex2) { + const stride = index * 3; + vertex2.x = vertices[stride + 0]; + vertex2.y = vertices[stride + 1]; + vertex2.z = vertices[stride + 2]; + } + function correctUVs() { + const a = new Vector3(); + const b = new Vector3(); + const c = new Vector3(); + const centroid = new Vector3(); + const uvA = new Vector2(); + const uvB = new Vector2(); + const uvC = new Vector2(); + for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) { + a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]); + b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]); + c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]); + uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]); + uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]); + uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]); + centroid.copy(a).add(b).add(c).divideScalar(3); + const azi = azimuth(centroid); + correctUV(uvA, j + 0, a, azi); + correctUV(uvB, j + 2, b, azi); + correctUV(uvC, j + 4, c, azi); + } + } + function correctUV(uv, stride, vector, azimuth2) { + if (azimuth2 < 0 && uv.x === 1) { + uvBuffer[stride] = uv.x - 1; + } + if (vector.x === 0 && vector.z === 0) { + uvBuffer[stride] = azimuth2 / 2 / Math.PI + 0.5; + } + } + function azimuth(vector) { + return Math.atan2(vector.z, -vector.x); + } + function inclination(vector) { + return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data) { + return new _PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details); + } + }; + var DodecahedronGeometry = class _DodecahedronGeometry extends PolyhedronGeometry { + constructor(radius = 1, detail = 0) { + const t = (1 + Math.sqrt(5)) / 2; + const r = 1 / t; + const vertices = [ + // (+/-1, +/-1, +/-1) + -1, + -1, + -1, + -1, + -1, + 1, + -1, + 1, + -1, + -1, + 1, + 1, + 1, + -1, + -1, + 1, + -1, + 1, + 1, + 1, + -1, + 1, + 1, + 1, + // (0, +/-1/phi, +/-phi) + 0, + -r, + -t, + 0, + -r, + t, + 0, + r, + -t, + 0, + r, + t, + // (+/-1/phi, +/-phi, 0) + -r, + -t, + 0, + -r, + t, + 0, + r, + -t, + 0, + r, + t, + 0, + // (+/-phi, 0, +/-1/phi) + -t, + 0, + -r, + t, + 0, + -r, + -t, + 0, + r, + t, + 0, + r + ]; + const indices = [ + 3, + 11, + 7, + 3, + 7, + 15, + 3, + 15, + 13, + 7, + 19, + 17, + 7, + 17, + 6, + 7, + 6, + 15, + 17, + 4, + 8, + 17, + 8, + 10, + 17, + 10, + 6, + 8, + 0, + 16, + 8, + 16, + 2, + 8, + 2, + 10, + 0, + 12, + 1, + 0, + 1, + 18, + 0, + 18, + 16, + 6, + 10, + 2, + 6, + 2, + 13, + 6, + 13, + 15, + 2, + 16, + 18, + 2, + 18, + 3, + 2, + 3, + 13, + 18, + 1, + 9, + 18, + 9, + 11, + 18, + 11, + 3, + 4, + 14, + 12, + 4, + 12, + 0, + 4, + 0, + 8, + 11, + 9, + 5, + 11, + 5, + 19, + 11, + 19, + 7, + 19, + 5, + 14, + 19, + 14, + 4, + 19, + 4, + 17, + 1, + 12, + 14, + 1, + 14, + 5, + 1, + 5, + 9 + ]; + super(vertices, indices, radius, detail); + this.type = "DodecahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data) { + return new _DodecahedronGeometry(data.radius, data.detail); + } + }; + var _v0 = /* @__PURE__ */ new Vector3(); + var _v1$1 = /* @__PURE__ */ new Vector3(); + var _normal = /* @__PURE__ */ new Vector3(); + var _triangle = /* @__PURE__ */ new Triangle(); + var EdgesGeometry = class extends BufferGeometry { + constructor(geometry = null, thresholdAngle = 1) { + super(); + this.type = "EdgesGeometry"; + this.parameters = { + geometry, + thresholdAngle + }; + if (geometry !== null) { + const precisionPoints = 4; + const precision = Math.pow(10, precisionPoints); + const thresholdDot = Math.cos(DEG2RAD * thresholdAngle); + const indexAttr = geometry.getIndex(); + const positionAttr = geometry.getAttribute("position"); + const indexCount = indexAttr ? indexAttr.count : positionAttr.count; + const indexArr = [0, 0, 0]; + const vertKeys = ["a", "b", "c"]; + const hashes = new Array(3); + const edgeData = {}; + const vertices = []; + for (let i = 0; i < indexCount; i += 3) { + if (indexAttr) { + indexArr[0] = indexAttr.getX(i); + indexArr[1] = indexAttr.getX(i + 1); + indexArr[2] = indexAttr.getX(i + 2); + } else { + indexArr[0] = i; + indexArr[1] = i + 1; + indexArr[2] = i + 2; + } + const { a, b, c } = _triangle; + a.fromBufferAttribute(positionAttr, indexArr[0]); + b.fromBufferAttribute(positionAttr, indexArr[1]); + c.fromBufferAttribute(positionAttr, indexArr[2]); + _triangle.getNormal(_normal); + hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`; + hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`; + hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; + if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) { + continue; + } + for (let j = 0; j < 3; j++) { + const jNext = (j + 1) % 3; + const vecHash0 = hashes[j]; + const vecHash1 = hashes[jNext]; + const v0 = _triangle[vertKeys[j]]; + const v1 = _triangle[vertKeys[jNext]]; + const hash = `${vecHash0}_${vecHash1}`; + const reverseHash = `${vecHash1}_${vecHash0}`; + if (reverseHash in edgeData && edgeData[reverseHash]) { + if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) { + vertices.push(v0.x, v0.y, v0.z); + vertices.push(v1.x, v1.y, v1.z); + } + edgeData[reverseHash] = null; + } else if (!(hash in edgeData)) { + edgeData[hash] = { + index0: indexArr[j], + index1: indexArr[jNext], + normal: _normal.clone() + }; + } + } + } + for (const key in edgeData) { + if (edgeData[key]) { + const { index0, index1 } = edgeData[key]; + _v0.fromBufferAttribute(positionAttr, index0); + _v1$1.fromBufferAttribute(positionAttr, index1); + vertices.push(_v0.x, _v0.y, _v0.z); + vertices.push(_v1$1.x, _v1$1.y, _v1$1.z); + } + } + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + }; + var Shape = class extends Path { + constructor(points) { + super(points); + this.uuid = generateUUID(); + this.type = "Shape"; + this.holes = []; + } + getPointsHoles(divisions) { + const holesPts = []; + for (let i = 0, l = this.holes.length; i < l; i++) { + holesPts[i] = this.holes[i].getPoints(divisions); + } + return holesPts; + } + // get points of shape and holes (keypoints based on segments parameter) + extractPoints(divisions) { + return { + shape: this.getPoints(divisions), + holes: this.getPointsHoles(divisions) + }; + } + copy(source) { + super.copy(source); + this.holes = []; + for (let i = 0, l = source.holes.length; i < l; i++) { + const hole = source.holes[i]; + this.holes.push(hole.clone()); + } + return this; + } + toJSON() { + const data = super.toJSON(); + data.uuid = this.uuid; + data.holes = []; + for (let i = 0, l = this.holes.length; i < l; i++) { + const hole = this.holes[i]; + data.holes.push(hole.toJSON()); + } + return data; + } + fromJSON(json) { + super.fromJSON(json); + this.uuid = json.uuid; + this.holes = []; + for (let i = 0, l = json.holes.length; i < l; i++) { + const hole = json.holes[i]; + this.holes.push(new Path().fromJSON(hole)); + } + return this; + } + }; + var Earcut = { + triangulate: function(data, holeIndices, dim = 2) { + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[0] * dim : data.length; + let outerNode = linkedList(data, 0, outerLen, dim, true); + const triangles = []; + if (!outerNode || outerNode.next === outerNode.prev) return triangles; + let minX, minY, maxX, maxY, x, y, invSize; + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + for (let i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 32767 / invSize : 0; + } + earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0); + return triangles; + } + }; + function linkedList(data, start, end, dim, clockwise) { + let i, last; + if (clockwise === signedArea(data, start, end, dim) > 0) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + return last; + } + function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + let p = start, again; + do { + again = false; + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) break; + again = true; + } else { + p = p.next; + } + } while (again || p !== end); + return end; + } + function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) return; + if (!pass && invSize) indexCurve(ear, minX, minY, invSize); + let stop = ear, prev, next; + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + triangles.push(prev.i / dim | 0); + triangles.push(ear.i / dim | 0); + triangles.push(next.i / dim | 0); + removeNode(ear); + ear = next.next; + stop = next.next; + continue; + } + ear = next; + if (ear === stop) { + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + } else if (pass === 1) { + ear = cureLocalIntersections(filterPoints(ear), triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } + break; + } + } + } + function isEar(ear) { + const a = ear.prev, b = ear, c = ear.next; + if (area(a, b, c) >= 0) return false; + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; + let p = c.next; + while (p !== a) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + return true; + } + function isEarHashed(ear, minX, minY, invSize) { + const a = ear.prev, b = ear, c = ear.next; + if (area(a, b, c) >= 0) return false; + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; + const minZ = zOrder(x0, y0, minX, minY, invSize), maxZ = zOrder(x1, y1, minX, minY, invSize); + let p = ear.prevZ, n = ear.nextZ; + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + while (p && p.z >= minZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + while (n && n.z <= maxZ) { + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + return true; + } + function cureLocalIntersections(start, triangles, dim) { + let p = start; + do { + const a = p.prev, b = p.next.next; + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + triangles.push(a.i / dim | 0); + triangles.push(p.i / dim | 0); + triangles.push(b.i / dim | 0); + removeNode(p); + removeNode(p.next); + p = start = b; + } + p = p.next; + } while (p !== start); + return filterPoints(p); + } + function splitEarcut(start, triangles, dim, minX, minY, invSize) { + let a = start; + do { + let b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + let c = splitPolygon(a, b); + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + earcutLinked(a, triangles, dim, minX, minY, invSize, 0); + earcutLinked(c, triangles, dim, minX, minY, invSize, 0); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); + } + function eliminateHoles(data, holeIndices, outerNode, dim) { + const queue = []; + let i, len, start, end, list; + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + queue.sort(compareX); + for (i = 0; i < queue.length; i++) { + outerNode = eliminateHole(queue[i], outerNode); + } + return outerNode; + } + function compareX(a, b) { + return a.x - b.x; + } + function eliminateHole(hole, outerNode) { + const bridge = findHoleBridge(hole, outerNode); + if (!bridge) { + return outerNode; + } + const bridgeReverse = splitPolygon(bridge, hole); + filterPoints(bridgeReverse, bridgeReverse.next); + return filterPoints(bridge, bridge.next); + } + function findHoleBridge(hole, outerNode) { + let p = outerNode, qx = -Infinity, m; + const hx = hole.x, hy = hole.y; + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + if (x === hx) return m; + } + } + p = p.next; + } while (p !== outerNode); + if (!m) return null; + const stop = m, mx = m.x, my = m.y; + let tanMin = Infinity, tan; + p = m; + do { + if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + tan = Math.abs(hy - p.y) / (hx - p.x); + if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) { + m = p; + tanMin = tan; + } + } + p = p.next; + } while (p !== stop); + return m; + } + function sectorContainsSector(m, p) { + return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; + } + function indexCurve(start, minX, minY, invSize) { + let p = start; + do { + if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + p.prevZ.nextZ = null; + p.prevZ = null; + sortLinked(p); + } + function sortLinked(list) { + let i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1; + do { + p = list; + list = null; + tail = null; + numMerges = 0; + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + qSize = inSize; + while (pSize > 0 || qSize > 0 && q) { + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + if (tail) tail.nextZ = e; + else list = e; + e.prevZ = tail; + tail = e; + } + p = q; + } + tail.nextZ = null; + inSize *= 2; + } while (numMerges > 1); + return list; + } + function zOrder(x, y, minX, minY, invSize) { + x = (x - minX) * invSize | 0; + y = (y - minY) * invSize | 0; + x = (x | x << 8) & 16711935; + x = (x | x << 4) & 252645135; + x = (x | x << 2) & 858993459; + x = (x | x << 1) & 1431655765; + y = (y | y << 8) & 16711935; + y = (y | y << 4) & 252645135; + y = (y | y << 2) & 858993459; + y = (y | y << 1) & 1431655765; + return x | y << 1; + } + function getLeftmost(start) { + let p = start, leftmost = start; + do { + if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p; + p = p.next; + } while (p !== start); + return leftmost; + } + function pointInTriangle(ax, ay, bx, by, cx, cy, px2, py2) { + return (cx - px2) * (ay - py2) >= (ax - px2) * (cy - py2) && (ax - px2) * (by - py2) >= (bx - px2) * (ay - py2) && (bx - px2) * (cy - py2) >= (cx - px2) * (by - py2); + } + function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges + (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible + (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors + equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); + } + function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); + } + function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; + } + function intersects(p1, q1, p2, q2) { + const o1 = sign(area(p1, q1, p2)); + const o2 = sign(area(p1, q1, q2)); + const o3 = sign(area(p2, q2, p1)); + const o4 = sign(area(p2, q2, q1)); + if (o1 !== o2 && o3 !== o4) return true; + if (o1 === 0 && onSegment(p1, p2, q1)) return true; + if (o2 === 0 && onSegment(p1, q2, q1)) return true; + if (o3 === 0 && onSegment(p2, p1, q2)) return true; + if (o4 === 0 && onSegment(p2, q1, q2)) return true; + return false; + } + function onSegment(p, q, r) { + return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); + } + function sign(num) { + return num > 0 ? 1 : num < 0 ? -1 : 0; + } + function intersectsPolygon(a, b) { + let p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + return false; + } + function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; + } + function middleInside(a, b) { + let p = a, inside = false; + const px2 = (a.x + b.x) / 2, py2 = (a.y + b.y) / 2; + do { + if (p.y > py2 !== p.next.y > py2 && p.next.y !== p.y && px2 < (p.next.x - p.x) * (py2 - p.y) / (p.next.y - p.y) + p.x) + inside = !inside; + p = p.next; + } while (p !== a); + return inside; + } + function splitPolygon(a, b) { + const a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev; + a.next = b; + b.prev = a; + a2.next = an; + an.prev = a2; + b2.next = a2; + a2.prev = b2; + bp.next = b2; + b2.prev = bp; + return b2; + } + function insertNode(i, x, y, last) { + const p = new Node(i, x, y); + if (!last) { + p.prev = p; + p.next = p; + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; + } + function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; + } + function Node(i, x, y) { + this.i = i; + this.x = x; + this.y = y; + this.prev = null; + this.next = null; + this.z = 0; + this.prevZ = null; + this.nextZ = null; + this.steiner = false; + } + function signedArea(data, start, end, dim) { + let sum = 0; + for (let i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; + } + var ShapeUtils = class _ShapeUtils { + // calculate area of the contour polygon + static area(contour) { + const n = contour.length; + let a = 0; + for (let p = n - 1, q = 0; q < n; p = q++) { + a += contour[p].x * contour[q].y - contour[q].x * contour[p].y; + } + return a * 0.5; + } + static isClockWise(pts) { + return _ShapeUtils.area(pts) < 0; + } + static triangulateShape(contour, holes) { + const vertices = []; + const holeIndices = []; + const faces = []; + removeDupEndPts(contour); + addContour(vertices, contour); + let holeIndex = contour.length; + holes.forEach(removeDupEndPts); + for (let i = 0; i < holes.length; i++) { + holeIndices.push(holeIndex); + holeIndex += holes[i].length; + addContour(vertices, holes[i]); + } + const triangles = Earcut.triangulate(vertices, holeIndices); + for (let i = 0; i < triangles.length; i += 3) { + faces.push(triangles.slice(i, i + 3)); + } + return faces; + } + }; + function removeDupEndPts(points) { + const l = points.length; + if (l > 2 && points[l - 1].equals(points[0])) { + points.pop(); + } + } + function addContour(vertices, contour) { + for (let i = 0; i < contour.length; i++) { + vertices.push(contour[i].x); + vertices.push(contour[i].y); + } + } + var ExtrudeGeometry = class _ExtrudeGeometry extends BufferGeometry { + constructor(shapes = new Shape([new Vector2(0.5, 0.5), new Vector2(-0.5, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), options = {}) { + super(); + this.type = "ExtrudeGeometry"; + this.parameters = { + shapes, + options + }; + shapes = Array.isArray(shapes) ? shapes : [shapes]; + const scope = this; + const verticesArray = []; + const uvArray = []; + for (let i = 0, l = shapes.length; i < l; i++) { + const shape = shapes[i]; + addShape(shape); + } + this.setAttribute("position", new Float32BufferAttribute(verticesArray, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvArray, 2)); + this.computeVertexNormals(); + function addShape(shape) { + const placeholder = []; + const curveSegments = options.curveSegments !== void 0 ? options.curveSegments : 12; + const steps = options.steps !== void 0 ? options.steps : 1; + const depth = options.depth !== void 0 ? options.depth : 1; + let bevelEnabled = options.bevelEnabled !== void 0 ? options.bevelEnabled : true; + let bevelThickness = options.bevelThickness !== void 0 ? options.bevelThickness : 0.2; + let bevelSize = options.bevelSize !== void 0 ? options.bevelSize : bevelThickness - 0.1; + let bevelOffset = options.bevelOffset !== void 0 ? options.bevelOffset : 0; + let bevelSegments = options.bevelSegments !== void 0 ? options.bevelSegments : 3; + const extrudePath = options.extrudePath; + const uvgen = options.UVGenerator !== void 0 ? options.UVGenerator : WorldUVGenerator; + let extrudePts, extrudeByPath = false; + let splineTube, binormal, normal, position2; + if (extrudePath) { + extrudePts = extrudePath.getSpacedPoints(steps); + extrudeByPath = true; + bevelEnabled = false; + splineTube = extrudePath.computeFrenetFrames(steps, false); + binormal = new Vector3(); + normal = new Vector3(); + position2 = new Vector3(); + } + if (!bevelEnabled) { + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; + bevelOffset = 0; + } + const shapePoints = shape.extractPoints(curveSegments); + let vertices = shapePoints.shape; + const holes = shapePoints.holes; + const reverse = !ShapeUtils.isClockWise(vertices); + if (reverse) { + vertices = vertices.reverse(); + for (let h = 0, hl = holes.length; h < hl; h++) { + const ahole = holes[h]; + if (ShapeUtils.isClockWise(ahole)) { + holes[h] = ahole.reverse(); + } + } + } + const faces = ShapeUtils.triangulateShape(vertices, holes); + const contour = vertices; + for (let h = 0, hl = holes.length; h < hl; h++) { + const ahole = holes[h]; + vertices = vertices.concat(ahole); + } + function scalePt2(pt, vec, size) { + if (!vec) console.error("THREE.ExtrudeGeometry: vec does not exist"); + return pt.clone().addScaledVector(vec, size); + } + const vlen = vertices.length, flen = faces.length; + function getBevelVec(inPt, inPrev, inNext) { + let v_trans_x, v_trans_y, shrink_by; + const v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y; + const v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y; + const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; + const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x; + if (Math.abs(collinear0) > Number.EPSILON) { + const v_prev_len = Math.sqrt(v_prev_lensq); + const v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); + const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len; + const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len; + const ptNextShift_x = inNext.x - v_next_y / v_next_len; + const ptNextShift_y = inNext.y + v_next_x / v_next_len; + const sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); + v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x; + v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; + const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y; + if (v_trans_lensq <= 2) { + return new Vector2(v_trans_x, v_trans_y); + } else { + shrink_by = Math.sqrt(v_trans_lensq / 2); + } + } else { + let direction_eq = false; + if (v_prev_x > Number.EPSILON) { + if (v_next_x > Number.EPSILON) { + direction_eq = true; + } + } else { + if (v_prev_x < -Number.EPSILON) { + if (v_next_x < -Number.EPSILON) { + direction_eq = true; + } + } else { + if (Math.sign(v_prev_y) === Math.sign(v_next_y)) { + direction_eq = true; + } + } + } + if (direction_eq) { + v_trans_x = -v_prev_y; + v_trans_y = v_prev_x; + shrink_by = Math.sqrt(v_prev_lensq); + } else { + v_trans_x = v_prev_x; + v_trans_y = v_prev_y; + shrink_by = Math.sqrt(v_prev_lensq / 2); + } + } + return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by); + } + const contourMovements = []; + for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) { + if (j === il) j = 0; + if (k === il) k = 0; + contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]); + } + const holesMovements = []; + let oneHoleMovements, verticesMovements = contourMovements.concat(); + for (let h = 0, hl = holes.length; h < hl; h++) { + const ahole = holes[h]; + oneHoleMovements = []; + for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) { + if (j === il) j = 0; + if (k === il) k = 0; + oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]); + } + holesMovements.push(oneHoleMovements); + verticesMovements = verticesMovements.concat(oneHoleMovements); + } + for (let b = 0; b < bevelSegments; b++) { + const t = b / bevelSegments; + const z = bevelThickness * Math.cos(t * Math.PI / 2); + const bs2 = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; + for (let i = 0, il = contour.length; i < il; i++) { + const vert = scalePt2(contour[i], contourMovements[i], bs2); + v(vert.x, vert.y, -z); + } + for (let h = 0, hl = holes.length; h < hl; h++) { + const ahole = holes[h]; + oneHoleMovements = holesMovements[h]; + for (let i = 0, il = ahole.length; i < il; i++) { + const vert = scalePt2(ahole[i], oneHoleMovements[i], bs2); + v(vert.x, vert.y, -z); + } + } + } + const bs = bevelSize + bevelOffset; + for (let i = 0; i < vlen; i++) { + const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i]; + if (!extrudeByPath) { + v(vert.x, vert.y, 0); + } else { + normal.copy(splineTube.normals[0]).multiplyScalar(vert.x); + binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y); + position2.copy(extrudePts[0]).add(normal).add(binormal); + v(position2.x, position2.y, position2.z); + } + } + for (let s = 1; s <= steps; s++) { + for (let i = 0; i < vlen; i++) { + const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i]; + if (!extrudeByPath) { + v(vert.x, vert.y, depth / steps * s); + } else { + normal.copy(splineTube.normals[s]).multiplyScalar(vert.x); + binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y); + position2.copy(extrudePts[s]).add(normal).add(binormal); + v(position2.x, position2.y, position2.z); + } + } + } + for (let b = bevelSegments - 1; b >= 0; b--) { + const t = b / bevelSegments; + const z = bevelThickness * Math.cos(t * Math.PI / 2); + const bs2 = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; + for (let i = 0, il = contour.length; i < il; i++) { + const vert = scalePt2(contour[i], contourMovements[i], bs2); + v(vert.x, vert.y, depth + z); + } + for (let h = 0, hl = holes.length; h < hl; h++) { + const ahole = holes[h]; + oneHoleMovements = holesMovements[h]; + for (let i = 0, il = ahole.length; i < il; i++) { + const vert = scalePt2(ahole[i], oneHoleMovements[i], bs2); + if (!extrudeByPath) { + v(vert.x, vert.y, depth + z); + } else { + v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z); + } + } + } + } + buildLidFaces(); + buildSideFaces(); + function buildLidFaces() { + const start = verticesArray.length / 3; + if (bevelEnabled) { + let layer = 0; + let offset = vlen * layer; + for (let i = 0; i < flen; i++) { + const face = faces[i]; + f3(face[2] + offset, face[1] + offset, face[0] + offset); + } + layer = steps + bevelSegments * 2; + offset = vlen * layer; + for (let i = 0; i < flen; i++) { + const face = faces[i]; + f3(face[0] + offset, face[1] + offset, face[2] + offset); + } + } else { + for (let i = 0; i < flen; i++) { + const face = faces[i]; + f3(face[2], face[1], face[0]); + } + for (let i = 0; i < flen; i++) { + const face = faces[i]; + f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps); + } + } + scope.addGroup(start, verticesArray.length / 3 - start, 0); + } + function buildSideFaces() { + const start = verticesArray.length / 3; + let layeroffset = 0; + sidewalls(contour, layeroffset); + layeroffset += contour.length; + for (let h = 0, hl = holes.length; h < hl; h++) { + const ahole = holes[h]; + sidewalls(ahole, layeroffset); + layeroffset += ahole.length; + } + scope.addGroup(start, verticesArray.length / 3 - start, 1); + } + function sidewalls(contour2, layeroffset) { + let i = contour2.length; + while (--i >= 0) { + const j = i; + let k = i - 1; + if (k < 0) k = contour2.length - 1; + for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) { + const slen1 = vlen * s; + const slen2 = vlen * (s + 1); + const a = layeroffset + j + slen1, b = layeroffset + k + slen1, c = layeroffset + k + slen2, d = layeroffset + j + slen2; + f4(a, b, c, d); + } + } + } + function v(x, y, z) { + placeholder.push(x); + placeholder.push(y); + placeholder.push(z); + } + function f3(a, b, c) { + addVertex(a); + addVertex(b); + addVertex(c); + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1); + addUV(uvs[0]); + addUV(uvs[1]); + addUV(uvs[2]); + } + function f4(a, b, c, d) { + addVertex(a); + addVertex(b); + addVertex(d); + addVertex(b); + addVertex(c); + addVertex(d); + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1); + addUV(uvs[0]); + addUV(uvs[1]); + addUV(uvs[3]); + addUV(uvs[1]); + addUV(uvs[2]); + addUV(uvs[3]); + } + function addVertex(index) { + verticesArray.push(placeholder[index * 3 + 0]); + verticesArray.push(placeholder[index * 3 + 1]); + verticesArray.push(placeholder[index * 3 + 2]); + } + function addUV(vector2) { + uvArray.push(vector2.x); + uvArray.push(vector2.y); + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data = super.toJSON(); + const shapes = this.parameters.shapes; + const options = this.parameters.options; + return toJSON$1(shapes, options, data); + } + static fromJSON(data, shapes) { + const geometryShapes = []; + for (let j = 0, jl = data.shapes.length; j < jl; j++) { + const shape = shapes[data.shapes[j]]; + geometryShapes.push(shape); + } + const extrudePath = data.options.extrudePath; + if (extrudePath !== void 0) { + data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath); + } + return new _ExtrudeGeometry(geometryShapes, data.options); + } + }; + var WorldUVGenerator = { + generateTopUV: function(geometry, vertices, indexA, indexB, indexC) { + const a_x = vertices[indexA * 3]; + const a_y = vertices[indexA * 3 + 1]; + const b_x = vertices[indexB * 3]; + const b_y = vertices[indexB * 3 + 1]; + const c_x = vertices[indexC * 3]; + const c_y = vertices[indexC * 3 + 1]; + return [ + new Vector2(a_x, a_y), + new Vector2(b_x, b_y), + new Vector2(c_x, c_y) + ]; + }, + generateSideWallUV: function(geometry, vertices, indexA, indexB, indexC, indexD) { + const a_x = vertices[indexA * 3]; + const a_y = vertices[indexA * 3 + 1]; + const a_z = vertices[indexA * 3 + 2]; + const b_x = vertices[indexB * 3]; + const b_y = vertices[indexB * 3 + 1]; + const b_z = vertices[indexB * 3 + 2]; + const c_x = vertices[indexC * 3]; + const c_y = vertices[indexC * 3 + 1]; + const c_z = vertices[indexC * 3 + 2]; + const d_x = vertices[indexD * 3]; + const d_y = vertices[indexD * 3 + 1]; + const d_z = vertices[indexD * 3 + 2]; + if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) { + return [ + new Vector2(a_x, 1 - a_z), + new Vector2(b_x, 1 - b_z), + new Vector2(c_x, 1 - c_z), + new Vector2(d_x, 1 - d_z) + ]; + } else { + return [ + new Vector2(a_y, 1 - a_z), + new Vector2(b_y, 1 - b_z), + new Vector2(c_y, 1 - c_z), + new Vector2(d_y, 1 - d_z) + ]; + } + } + }; + function toJSON$1(shapes, options, data) { + data.shapes = []; + if (Array.isArray(shapes)) { + for (let i = 0, l = shapes.length; i < l; i++) { + const shape = shapes[i]; + data.shapes.push(shape.uuid); + } + } else { + data.shapes.push(shapes.uuid); + } + data.options = Object.assign({}, options); + if (options.extrudePath !== void 0) data.options.extrudePath = options.extrudePath.toJSON(); + return data; + } + var IcosahedronGeometry = class _IcosahedronGeometry extends PolyhedronGeometry { + constructor(radius = 1, detail = 0) { + const t = (1 + Math.sqrt(5)) / 2; + const vertices = [ + -1, + t, + 0, + 1, + t, + 0, + -1, + -t, + 0, + 1, + -t, + 0, + 0, + -1, + t, + 0, + 1, + t, + 0, + -1, + -t, + 0, + 1, + -t, + t, + 0, + -1, + t, + 0, + 1, + -t, + 0, + -1, + -t, + 0, + 1 + ]; + const indices = [ + 0, + 11, + 5, + 0, + 5, + 1, + 0, + 1, + 7, + 0, + 7, + 10, + 0, + 10, + 11, + 1, + 5, + 9, + 5, + 11, + 4, + 11, + 10, + 2, + 10, + 7, + 6, + 7, + 1, + 8, + 3, + 9, + 4, + 3, + 4, + 2, + 3, + 2, + 6, + 3, + 6, + 8, + 3, + 8, + 9, + 4, + 9, + 5, + 2, + 4, + 11, + 6, + 2, + 10, + 8, + 6, + 7, + 9, + 8, + 1 + ]; + super(vertices, indices, radius, detail); + this.type = "IcosahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data) { + return new _IcosahedronGeometry(data.radius, data.detail); + } + }; + var OctahedronGeometry = class _OctahedronGeometry extends PolyhedronGeometry { + constructor(radius = 1, detail = 0) { + const vertices = [ + 1, + 0, + 0, + -1, + 0, + 0, + 0, + 1, + 0, + 0, + -1, + 0, + 0, + 0, + 1, + 0, + 0, + -1 + ]; + const indices = [ + 0, + 2, + 4, + 0, + 4, + 3, + 0, + 3, + 5, + 0, + 5, + 2, + 1, + 2, + 5, + 1, + 5, + 3, + 1, + 3, + 4, + 1, + 4, + 2 + ]; + super(vertices, indices, radius, detail); + this.type = "OctahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data) { + return new _OctahedronGeometry(data.radius, data.detail); + } + }; + var RingGeometry = class _RingGeometry extends BufferGeometry { + constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "RingGeometry"; + this.parameters = { + innerRadius, + outerRadius, + thetaSegments, + phiSegments, + thetaStart, + thetaLength + }; + thetaSegments = Math.max(3, thetaSegments); + phiSegments = Math.max(1, phiSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let radius = innerRadius; + const radiusStep = (outerRadius - innerRadius) / phiSegments; + const vertex2 = new Vector3(); + const uv = new Vector2(); + for (let j = 0; j <= phiSegments; j++) { + for (let i = 0; i <= thetaSegments; i++) { + const segment = thetaStart + i / thetaSegments * thetaLength; + vertex2.x = radius * Math.cos(segment); + vertex2.y = radius * Math.sin(segment); + vertices.push(vertex2.x, vertex2.y, vertex2.z); + normals.push(0, 0, 1); + uv.x = (vertex2.x / outerRadius + 1) / 2; + uv.y = (vertex2.y / outerRadius + 1) / 2; + uvs.push(uv.x, uv.y); + } + radius += radiusStep; + } + for (let j = 0; j < phiSegments; j++) { + const thetaSegmentLevel = j * (thetaSegments + 1); + for (let i = 0; i < thetaSegments; i++) { + const segment = i + thetaSegmentLevel; + const a = segment; + const b = segment + thetaSegments + 1; + const c = segment + thetaSegments + 2; + const d = segment + 1; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data) { + return new _RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength); + } + }; + var ShapeGeometry = class _ShapeGeometry extends BufferGeometry { + constructor(shapes = new Shape([new Vector2(0, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), curveSegments = 12) { + super(); + this.type = "ShapeGeometry"; + this.parameters = { + shapes, + curveSegments + }; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let groupStart = 0; + let groupCount = 0; + if (Array.isArray(shapes) === false) { + addShape(shapes); + } else { + for (let i = 0; i < shapes.length; i++) { + addShape(shapes[i]); + this.addGroup(groupStart, groupCount, i); + groupStart += groupCount; + groupCount = 0; + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function addShape(shape) { + const indexOffset = vertices.length / 3; + const points = shape.extractPoints(curveSegments); + let shapeVertices = points.shape; + const shapeHoles = points.holes; + if (ShapeUtils.isClockWise(shapeVertices) === false) { + shapeVertices = shapeVertices.reverse(); + } + for (let i = 0, l = shapeHoles.length; i < l; i++) { + const shapeHole = shapeHoles[i]; + if (ShapeUtils.isClockWise(shapeHole) === true) { + shapeHoles[i] = shapeHole.reverse(); + } + } + const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); + for (let i = 0, l = shapeHoles.length; i < l; i++) { + const shapeHole = shapeHoles[i]; + shapeVertices = shapeVertices.concat(shapeHole); + } + for (let i = 0, l = shapeVertices.length; i < l; i++) { + const vertex2 = shapeVertices[i]; + vertices.push(vertex2.x, vertex2.y, 0); + normals.push(0, 0, 1); + uvs.push(vertex2.x, vertex2.y); + } + for (let i = 0, l = faces.length; i < l; i++) { + const face = faces[i]; + const a = face[0] + indexOffset; + const b = face[1] + indexOffset; + const c = face[2] + indexOffset; + indices.push(a, b, c); + groupCount += 3; + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data = super.toJSON(); + const shapes = this.parameters.shapes; + return toJSON(shapes, data); + } + static fromJSON(data, shapes) { + const geometryShapes = []; + for (let j = 0, jl = data.shapes.length; j < jl; j++) { + const shape = shapes[data.shapes[j]]; + geometryShapes.push(shape); + } + return new _ShapeGeometry(geometryShapes, data.curveSegments); + } + }; + function toJSON(shapes, data) { + data.shapes = []; + if (Array.isArray(shapes)) { + for (let i = 0, l = shapes.length; i < l; i++) { + const shape = shapes[i]; + data.shapes.push(shape.uuid); + } + } else { + data.shapes.push(shapes.uuid); + } + return data; + } + var SphereGeometry = class _SphereGeometry extends BufferGeometry { + constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) { + super(); + this.type = "SphereGeometry"; + this.parameters = { + radius, + widthSegments, + heightSegments, + phiStart, + phiLength, + thetaStart, + thetaLength + }; + widthSegments = Math.max(3, Math.floor(widthSegments)); + heightSegments = Math.max(2, Math.floor(heightSegments)); + const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI); + let index = 0; + const grid = []; + const vertex2 = new Vector3(); + const normal = new Vector3(); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + for (let iy = 0; iy <= heightSegments; iy++) { + const verticesRow = []; + const v = iy / heightSegments; + let uOffset = 0; + if (iy === 0 && thetaStart === 0) { + uOffset = 0.5 / widthSegments; + } else if (iy === heightSegments && thetaEnd === Math.PI) { + uOffset = -0.5 / widthSegments; + } + for (let ix = 0; ix <= widthSegments; ix++) { + const u = ix / widthSegments; + vertex2.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength); + vertex2.y = radius * Math.cos(thetaStart + v * thetaLength); + vertex2.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength); + vertices.push(vertex2.x, vertex2.y, vertex2.z); + normal.copy(vertex2).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(u + uOffset, 1 - v); + verticesRow.push(index++); + } + grid.push(verticesRow); + } + for (let iy = 0; iy < heightSegments; iy++) { + for (let ix = 0; ix < widthSegments; ix++) { + const a = grid[iy][ix + 1]; + const b = grid[iy][ix]; + const c = grid[iy + 1][ix]; + const d = grid[iy + 1][ix + 1]; + if (iy !== 0 || thetaStart > 0) indices.push(a, b, d); + if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data) { + return new _SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength); + } + }; + var TetrahedronGeometry = class _TetrahedronGeometry extends PolyhedronGeometry { + constructor(radius = 1, detail = 0) { + const vertices = [ + 1, + 1, + 1, + -1, + -1, + 1, + -1, + 1, + -1, + 1, + -1, + -1 + ]; + const indices = [ + 2, + 1, + 0, + 0, + 3, + 2, + 1, + 3, + 0, + 2, + 3, + 1 + ]; + super(vertices, indices, radius, detail); + this.type = "TetrahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data) { + return new _TetrahedronGeometry(data.radius, data.detail); + } + }; + var TorusGeometry = class _TorusGeometry extends BufferGeometry { + constructor(radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2) { + super(); + this.type = "TorusGeometry"; + this.parameters = { + radius, + tube, + radialSegments, + tubularSegments, + arc + }; + radialSegments = Math.floor(radialSegments); + tubularSegments = Math.floor(tubularSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const center = new Vector3(); + const vertex2 = new Vector3(); + const normal = new Vector3(); + for (let j = 0; j <= radialSegments; j++) { + for (let i = 0; i <= tubularSegments; i++) { + const u = i / tubularSegments * arc; + const v = j / radialSegments * Math.PI * 2; + vertex2.x = (radius + tube * Math.cos(v)) * Math.cos(u); + vertex2.y = (radius + tube * Math.cos(v)) * Math.sin(u); + vertex2.z = tube * Math.sin(v); + vertices.push(vertex2.x, vertex2.y, vertex2.z); + center.x = radius * Math.cos(u); + center.y = radius * Math.sin(u); + normal.subVectors(vertex2, center).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(i / tubularSegments); + uvs.push(j / radialSegments); + } + } + for (let j = 1; j <= radialSegments; j++) { + for (let i = 1; i <= tubularSegments; i++) { + const a = (tubularSegments + 1) * j + i - 1; + const b = (tubularSegments + 1) * (j - 1) + i - 1; + const c = (tubularSegments + 1) * (j - 1) + i; + const d = (tubularSegments + 1) * j + i; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data) { + return new _TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc); + } + }; + var TorusKnotGeometry = class _TorusKnotGeometry extends BufferGeometry { + constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) { + super(); + this.type = "TorusKnotGeometry"; + this.parameters = { + radius, + tube, + tubularSegments, + radialSegments, + p, + q + }; + tubularSegments = Math.floor(tubularSegments); + radialSegments = Math.floor(radialSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const vertex2 = new Vector3(); + const normal = new Vector3(); + const P1 = new Vector3(); + const P2 = new Vector3(); + const B = new Vector3(); + const T = new Vector3(); + const N = new Vector3(); + for (let i = 0; i <= tubularSegments; ++i) { + const u = i / tubularSegments * p * Math.PI * 2; + calculatePositionOnCurve(u, p, q, radius, P1); + calculatePositionOnCurve(u + 0.01, p, q, radius, P2); + T.subVectors(P2, P1); + N.addVectors(P2, P1); + B.crossVectors(T, N); + N.crossVectors(B, T); + B.normalize(); + N.normalize(); + for (let j = 0; j <= radialSegments; ++j) { + const v = j / radialSegments * Math.PI * 2; + const cx = -tube * Math.cos(v); + const cy = tube * Math.sin(v); + vertex2.x = P1.x + (cx * N.x + cy * B.x); + vertex2.y = P1.y + (cx * N.y + cy * B.y); + vertex2.z = P1.z + (cx * N.z + cy * B.z); + vertices.push(vertex2.x, vertex2.y, vertex2.z); + normal.subVectors(vertex2, P1).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(i / tubularSegments); + uvs.push(j / radialSegments); + } + } + for (let j = 1; j <= tubularSegments; j++) { + for (let i = 1; i <= radialSegments; i++) { + const a = (radialSegments + 1) * (j - 1) + (i - 1); + const b = (radialSegments + 1) * j + (i - 1); + const c = (radialSegments + 1) * j + i; + const d = (radialSegments + 1) * (j - 1) + i; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function calculatePositionOnCurve(u, p2, q2, radius2, position) { + const cu = Math.cos(u); + const su = Math.sin(u); + const quOverP = q2 / p2 * u; + const cs = Math.cos(quOverP); + position.x = radius2 * (2 + cs) * 0.5 * cu; + position.y = radius2 * (2 + cs) * su * 0.5; + position.z = radius2 * Math.sin(quOverP) * 0.5; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data) { + return new _TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q); + } + }; + var TubeGeometry = class _TubeGeometry extends BufferGeometry { + constructor(path = new QuadraticBezierCurve3(new Vector3(-1, -1, 0), new Vector3(-1, 1, 0), new Vector3(1, 1, 0)), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) { + super(); + this.type = "TubeGeometry"; + this.parameters = { + path, + tubularSegments, + radius, + radialSegments, + closed + }; + const frames = path.computeFrenetFrames(tubularSegments, closed); + this.tangents = frames.tangents; + this.normals = frames.normals; + this.binormals = frames.binormals; + const vertex2 = new Vector3(); + const normal = new Vector3(); + const uv = new Vector2(); + let P = new Vector3(); + const vertices = []; + const normals = []; + const uvs = []; + const indices = []; + generateBufferData(); + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function generateBufferData() { + for (let i = 0; i < tubularSegments; i++) { + generateSegment(i); + } + generateSegment(closed === false ? tubularSegments : 0); + generateUVs(); + generateIndices(); + } + function generateSegment(i) { + P = path.getPointAt(i / tubularSegments, P); + const N = frames.normals[i]; + const B = frames.binormals[i]; + for (let j = 0; j <= radialSegments; j++) { + const v = j / radialSegments * Math.PI * 2; + const sin = Math.sin(v); + const cos = -Math.cos(v); + normal.x = cos * N.x + sin * B.x; + normal.y = cos * N.y + sin * B.y; + normal.z = cos * N.z + sin * B.z; + normal.normalize(); + normals.push(normal.x, normal.y, normal.z); + vertex2.x = P.x + radius * normal.x; + vertex2.y = P.y + radius * normal.y; + vertex2.z = P.z + radius * normal.z; + vertices.push(vertex2.x, vertex2.y, vertex2.z); + } + } + function generateIndices() { + for (let j = 1; j <= tubularSegments; j++) { + for (let i = 1; i <= radialSegments; i++) { + const a = (radialSegments + 1) * (j - 1) + (i - 1); + const b = (radialSegments + 1) * j + (i - 1); + const c = (radialSegments + 1) * j + i; + const d = (radialSegments + 1) * (j - 1) + i; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + } + function generateUVs() { + for (let i = 0; i <= tubularSegments; i++) { + for (let j = 0; j <= radialSegments; j++) { + uv.x = i / tubularSegments; + uv.y = j / radialSegments; + uvs.push(uv.x, uv.y); + } + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data = super.toJSON(); + data.path = this.parameters.path.toJSON(); + return data; + } + static fromJSON(data) { + return new _TubeGeometry( + new Curves[data.path.type]().fromJSON(data.path), + data.tubularSegments, + data.radius, + data.radialSegments, + data.closed + ); + } + }; + var WireframeGeometry = class extends BufferGeometry { + constructor(geometry = null) { + super(); + this.type = "WireframeGeometry"; + this.parameters = { + geometry + }; + if (geometry !== null) { + const vertices = []; + const edges = /* @__PURE__ */ new Set(); + const start = new Vector3(); + const end = new Vector3(); + if (geometry.index !== null) { + const position = geometry.attributes.position; + const indices = geometry.index; + let groups = geometry.groups; + if (groups.length === 0) { + groups = [{ start: 0, count: indices.count, materialIndex: 0 }]; + } + for (let o = 0, ol = groups.length; o < ol; ++o) { + const group = groups[o]; + const groupStart = group.start; + const groupCount = group.count; + for (let i = groupStart, l = groupStart + groupCount; i < l; i += 3) { + for (let j = 0; j < 3; j++) { + const index1 = indices.getX(i + j); + const index2 = indices.getX(i + (j + 1) % 3); + start.fromBufferAttribute(position, index1); + end.fromBufferAttribute(position, index2); + if (isUniqueEdge(start, end, edges) === true) { + vertices.push(start.x, start.y, start.z); + vertices.push(end.x, end.y, end.z); + } + } + } + } + } else { + const position = geometry.attributes.position; + for (let i = 0, l = position.count / 3; i < l; i++) { + for (let j = 0; j < 3; j++) { + const index1 = 3 * i + j; + const index2 = 3 * i + (j + 1) % 3; + start.fromBufferAttribute(position, index1); + end.fromBufferAttribute(position, index2); + if (isUniqueEdge(start, end, edges) === true) { + vertices.push(start.x, start.y, start.z); + vertices.push(end.x, end.y, end.z); + } + } + } + } + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + }; + function isUniqueEdge(start, end, edges) { + const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`; + const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; + if (edges.has(hash1) === true || edges.has(hash2) === true) { + return false; + } else { + edges.add(hash1); + edges.add(hash2); + return true; + } + } + var Geometries = /* @__PURE__ */ Object.freeze({ + __proto__: null, + BoxGeometry, + CapsuleGeometry, + CircleGeometry, + ConeGeometry, + CylinderGeometry, + DodecahedronGeometry, + EdgesGeometry, + ExtrudeGeometry, + IcosahedronGeometry, + LatheGeometry, + OctahedronGeometry, + PlaneGeometry, + PolyhedronGeometry, + RingGeometry, + ShapeGeometry, + SphereGeometry, + TetrahedronGeometry, + TorusGeometry, + TorusKnotGeometry, + TubeGeometry, + WireframeGeometry + }); + var ShadowMaterial = class extends Material { + constructor(parameters) { + super(); + this.isShadowMaterial = true; + this.type = "ShadowMaterial"; + this.color = new Color(0); + this.transparent = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.fog = source.fog; + return this; + } + }; + var RawShaderMaterial = class extends ShaderMaterial { + constructor(parameters) { + super(parameters); + this.isRawShaderMaterial = true; + this.type = "RawShaderMaterial"; + } + }; + var MeshStandardMaterial = class extends Material { + constructor(parameters) { + super(); + this.isMeshStandardMaterial = true; + this.defines = { "STANDARD": "" }; + this.type = "MeshStandardMaterial"; + this.color = new Color(16777215); + this.roughness = 1; + this.metalness = 0; + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.roughnessMap = null; + this.metalnessMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapIntensity = 1; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.defines = { "STANDARD": "" }; + this.color.copy(source.color); + this.roughness = source.roughness; + this.metalness = source.metalness; + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.roughnessMap = source.roughnessMap; + this.metalnessMap = source.metalnessMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapIntensity = source.envMapIntensity; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } + }; + var MeshPhysicalMaterial = class extends MeshStandardMaterial { + constructor(parameters) { + super(); + this.isMeshPhysicalMaterial = true; + this.defines = { + "STANDARD": "", + "PHYSICAL": "" + }; + this.type = "MeshPhysicalMaterial"; + this.anisotropyRotation = 0; + this.anisotropyMap = null; + this.clearcoatMap = null; + this.clearcoatRoughness = 0; + this.clearcoatRoughnessMap = null; + this.clearcoatNormalScale = new Vector2(1, 1); + this.clearcoatNormalMap = null; + this.ior = 1.5; + Object.defineProperty(this, "reflectivity", { + get: function() { + return clamp(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1); + }, + set: function(reflectivity) { + this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity); + } + }); + this.iridescenceMap = null; + this.iridescenceIOR = 1.3; + this.iridescenceThicknessRange = [100, 400]; + this.iridescenceThicknessMap = null; + this.sheenColor = new Color(0); + this.sheenColorMap = null; + this.sheenRoughness = 1; + this.sheenRoughnessMap = null; + this.transmissionMap = null; + this.thickness = 0; + this.thicknessMap = null; + this.attenuationDistance = Infinity; + this.attenuationColor = new Color(1, 1, 1); + this.specularIntensity = 1; + this.specularIntensityMap = null; + this.specularColor = new Color(1, 1, 1); + this.specularColorMap = null; + this._anisotropy = 0; + this._clearcoat = 0; + this._iridescence = 0; + this._sheen = 0; + this._transmission = 0; + this.setValues(parameters); + } + get anisotropy() { + return this._anisotropy; + } + set anisotropy(value) { + if (this._anisotropy > 0 !== value > 0) { + this.version++; + } + this._anisotropy = value; + } + get clearcoat() { + return this._clearcoat; + } + set clearcoat(value) { + if (this._clearcoat > 0 !== value > 0) { + this.version++; + } + this._clearcoat = value; + } + get iridescence() { + return this._iridescence; + } + set iridescence(value) { + if (this._iridescence > 0 !== value > 0) { + this.version++; + } + this._iridescence = value; + } + get sheen() { + return this._sheen; + } + set sheen(value) { + if (this._sheen > 0 !== value > 0) { + this.version++; + } + this._sheen = value; + } + get transmission() { + return this._transmission; + } + set transmission(value) { + if (this._transmission > 0 !== value > 0) { + this.version++; + } + this._transmission = value; + } + copy(source) { + super.copy(source); + this.defines = { + "STANDARD": "", + "PHYSICAL": "" + }; + this.anisotropy = source.anisotropy; + this.anisotropyRotation = source.anisotropyRotation; + this.anisotropyMap = source.anisotropyMap; + this.clearcoat = source.clearcoat; + this.clearcoatMap = source.clearcoatMap; + this.clearcoatRoughness = source.clearcoatRoughness; + this.clearcoatRoughnessMap = source.clearcoatRoughnessMap; + this.clearcoatNormalMap = source.clearcoatNormalMap; + this.clearcoatNormalScale.copy(source.clearcoatNormalScale); + this.ior = source.ior; + this.iridescence = source.iridescence; + this.iridescenceMap = source.iridescenceMap; + this.iridescenceIOR = source.iridescenceIOR; + this.iridescenceThicknessRange = [...source.iridescenceThicknessRange]; + this.iridescenceThicknessMap = source.iridescenceThicknessMap; + this.sheen = source.sheen; + this.sheenColor.copy(source.sheenColor); + this.sheenColorMap = source.sheenColorMap; + this.sheenRoughness = source.sheenRoughness; + this.sheenRoughnessMap = source.sheenRoughnessMap; + this.transmission = source.transmission; + this.transmissionMap = source.transmissionMap; + this.thickness = source.thickness; + this.thicknessMap = source.thicknessMap; + this.attenuationDistance = source.attenuationDistance; + this.attenuationColor.copy(source.attenuationColor); + this.specularIntensity = source.specularIntensity; + this.specularIntensityMap = source.specularIntensityMap; + this.specularColor.copy(source.specularColor); + this.specularColorMap = source.specularColorMap; + return this; + } + }; + var MeshPhongMaterial = class extends Material { + constructor(parameters) { + super(); + this.isMeshPhongMaterial = true; + this.type = "MeshPhongMaterial"; + this.color = new Color(16777215); + this.specular = new Color(1118481); + this.shininess = 30; + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.specular.copy(source.specular); + this.shininess = source.shininess; + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } + }; + var MeshToonMaterial = class extends Material { + constructor(parameters) { + super(); + this.isMeshToonMaterial = true; + this.defines = { "TOON": "" }; + this.type = "MeshToonMaterial"; + this.color = new Color(16777215); + this.map = null; + this.gradientMap = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.alphaMap = null; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.gradientMap = source.gradientMap; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.alphaMap = source.alphaMap; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; + } + }; + var MeshNormalMaterial = class extends Material { + constructor(parameters) { + super(); + this.isMeshNormalMaterial = true; + this.type = "MeshNormalMaterial"; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.flatShading = false; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.flatShading = source.flatShading; + return this; + } + }; + var MeshLambertMaterial = class extends Material { + constructor(parameters) { + super(); + this.isMeshLambertMaterial = true; + this.type = "MeshLambertMaterial"; + this.color = new Color(16777215); + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } + }; + var MeshMatcapMaterial = class extends Material { + constructor(parameters) { + super(); + this.isMeshMatcapMaterial = true; + this.defines = { "MATCAP": "" }; + this.type = "MeshMatcapMaterial"; + this.color = new Color(16777215); + this.matcap = null; + this.map = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.alphaMap = null; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.defines = { "MATCAP": "" }; + this.color.copy(source.color); + this.matcap = source.matcap; + this.map = source.map; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.alphaMap = source.alphaMap; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } + }; + var LineDashedMaterial = class extends LineBasicMaterial { + constructor(parameters) { + super(); + this.isLineDashedMaterial = true; + this.type = "LineDashedMaterial"; + this.scale = 1; + this.dashSize = 3; + this.gapSize = 1; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.scale = source.scale; + this.dashSize = source.dashSize; + this.gapSize = source.gapSize; + return this; + } + }; + function convertArray(array, type, forceClone) { + if (!array || // let 'undefined' and 'null' pass + !forceClone && array.constructor === type) return array; + if (typeof type.BYTES_PER_ELEMENT === "number") { + return new type(array); + } + return Array.prototype.slice.call(array); + } + function isTypedArray(object) { + return ArrayBuffer.isView(object) && !(object instanceof DataView); + } + function getKeyframeOrder(times) { + function compareTime(i, j) { + return times[i] - times[j]; + } + const n = times.length; + const result = new Array(n); + for (let i = 0; i !== n; ++i) result[i] = i; + result.sort(compareTime); + return result; + } + function sortedArray(values, stride, order) { + const nValues = values.length; + const result = new values.constructor(nValues); + for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) { + const srcOffset = order[i] * stride; + for (let j = 0; j !== stride; ++j) { + result[dstOffset++] = values[srcOffset + j]; + } + } + return result; + } + function flattenJSON(jsonKeys, times, values, valuePropertyName) { + let i = 1, key = jsonKeys[0]; + while (key !== void 0 && key[valuePropertyName] === void 0) { + key = jsonKeys[i++]; + } + if (key === void 0) return; + let value = key[valuePropertyName]; + if (value === void 0) return; + if (Array.isArray(value)) { + do { + value = key[valuePropertyName]; + if (value !== void 0) { + times.push(key.time); + values.push.apply(values, value); + } + key = jsonKeys[i++]; + } while (key !== void 0); + } else if (value.toArray !== void 0) { + do { + value = key[valuePropertyName]; + if (value !== void 0) { + times.push(key.time); + value.toArray(values, values.length); + } + key = jsonKeys[i++]; + } while (key !== void 0); + } else { + do { + value = key[valuePropertyName]; + if (value !== void 0) { + times.push(key.time); + values.push(value); + } + key = jsonKeys[i++]; + } while (key !== void 0); + } + } + function subclip(sourceClip, name, startFrame, endFrame, fps = 30) { + const clip = sourceClip.clone(); + clip.name = name; + const tracks = []; + for (let i = 0; i < clip.tracks.length; ++i) { + const track = clip.tracks[i]; + const valueSize = track.getValueSize(); + const times = []; + const values = []; + for (let j = 0; j < track.times.length; ++j) { + const frame = track.times[j] * fps; + if (frame < startFrame || frame >= endFrame) continue; + times.push(track.times[j]); + for (let k = 0; k < valueSize; ++k) { + values.push(track.values[j * valueSize + k]); + } + } + if (times.length === 0) continue; + track.times = convertArray(times, track.times.constructor); + track.values = convertArray(values, track.values.constructor); + tracks.push(track); + } + clip.tracks = tracks; + let minStartTime = Infinity; + for (let i = 0; i < clip.tracks.length; ++i) { + if (minStartTime > clip.tracks[i].times[0]) { + minStartTime = clip.tracks[i].times[0]; + } + } + for (let i = 0; i < clip.tracks.length; ++i) { + clip.tracks[i].shift(-1 * minStartTime); + } + clip.resetDuration(); + return clip; + } + function makeClipAdditive(targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) { + if (fps <= 0) fps = 30; + const numTracks = referenceClip.tracks.length; + const referenceTime = referenceFrame / fps; + for (let i = 0; i < numTracks; ++i) { + const referenceTrack = referenceClip.tracks[i]; + const referenceTrackType = referenceTrack.ValueTypeName; + if (referenceTrackType === "bool" || referenceTrackType === "string") continue; + const targetTrack = targetClip.tracks.find(function(track) { + return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType; + }); + if (targetTrack === void 0) continue; + let referenceOffset = 0; + const referenceValueSize = referenceTrack.getValueSize(); + if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { + referenceOffset = referenceValueSize / 3; + } + let targetOffset = 0; + const targetValueSize = targetTrack.getValueSize(); + if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { + targetOffset = targetValueSize / 3; + } + const lastIndex = referenceTrack.times.length - 1; + let referenceValue; + if (referenceTime <= referenceTrack.times[0]) { + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + referenceValue = referenceTrack.values.slice(startIndex, endIndex); + } else if (referenceTime >= referenceTrack.times[lastIndex]) { + const startIndex = lastIndex * referenceValueSize + referenceOffset; + const endIndex = startIndex + referenceValueSize - referenceOffset; + referenceValue = referenceTrack.values.slice(startIndex, endIndex); + } else { + const interpolant = referenceTrack.createInterpolant(); + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + interpolant.evaluate(referenceTime); + referenceValue = interpolant.resultBuffer.slice(startIndex, endIndex); + } + if (referenceTrackType === "quaternion") { + const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate(); + referenceQuat.toArray(referenceValue); + } + const numTimes = targetTrack.times.length; + for (let j = 0; j < numTimes; ++j) { + const valueStart = j * targetValueSize + targetOffset; + if (referenceTrackType === "quaternion") { + Quaternion.multiplyQuaternionsFlat( + targetTrack.values, + valueStart, + referenceValue, + 0, + targetTrack.values, + valueStart + ); + } else { + const valueEnd = targetValueSize - targetOffset * 2; + for (let k = 0; k < valueEnd; ++k) { + targetTrack.values[valueStart + k] -= referenceValue[k]; + } + } + } + } + targetClip.blendMode = AdditiveAnimationBlendMode; + return targetClip; + } + var AnimationUtils = { + convertArray, + isTypedArray, + getKeyframeOrder, + sortedArray, + flattenJSON, + subclip, + makeClipAdditive + }; + var Interpolant = class { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + this.parameterPositions = parameterPositions; + this._cachedIndex = 0; + this.resultBuffer = resultBuffer !== void 0 ? resultBuffer : new sampleValues.constructor(sampleSize); + this.sampleValues = sampleValues; + this.valueSize = sampleSize; + this.settings = null; + this.DefaultSettings_ = {}; + } + evaluate(t) { + const pp = this.parameterPositions; + let i1 = this._cachedIndex, t1 = pp[i1], t0 = pp[i1 - 1]; + validate_interval: { + seek: { + let right; + linear_scan: { + forward_scan: if (!(t < t1)) { + for (let giveUpAt = i1 + 2; ; ) { + if (t1 === void 0) { + if (t < t0) break forward_scan; + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_(i1 - 1); + } + if (i1 === giveUpAt) break; + t0 = t1; + t1 = pp[++i1]; + if (t < t1) { + break seek; + } + } + right = pp.length; + break linear_scan; + } + if (!(t >= t0)) { + const t1global = pp[1]; + if (t < t1global) { + i1 = 2; + t0 = t1global; + } + for (let giveUpAt = i1 - 2; ; ) { + if (t0 === void 0) { + this._cachedIndex = 0; + return this.copySampleValue_(0); + } + if (i1 === giveUpAt) break; + t1 = t0; + t0 = pp[--i1 - 1]; + if (t >= t0) { + break seek; + } + } + right = i1; + i1 = 0; + break linear_scan; + } + break validate_interval; + } + while (i1 < right) { + const mid = i1 + right >>> 1; + if (t < pp[mid]) { + right = mid; + } else { + i1 = mid + 1; + } + } + t1 = pp[i1]; + t0 = pp[i1 - 1]; + if (t0 === void 0) { + this._cachedIndex = 0; + return this.copySampleValue_(0); + } + if (t1 === void 0) { + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_(i1 - 1); + } + } + this._cachedIndex = i1; + this.intervalChanged_(i1, t0, t1); + } + return this.interpolate_(i1, t0, t, t1); + } + getSettings_() { + return this.settings || this.DefaultSettings_; + } + copySampleValue_(index) { + const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, offset = index * stride; + for (let i = 0; i !== stride; ++i) { + result[i] = values[offset + i]; + } + return result; + } + // Template methods for derived classes: + interpolate_() { + throw new Error("call to abstract method"); + } + intervalChanged_() { + } + }; + var CubicInterpolant = class extends Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + this._weightPrev = -0; + this._offsetPrev = -0; + this._weightNext = -0; + this._offsetNext = -0; + this.DefaultSettings_ = { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + }; + } + intervalChanged_(i1, t0, t1) { + const pp = this.parameterPositions; + let iPrev = i1 - 2, iNext = i1 + 1, tPrev = pp[iPrev], tNext = pp[iNext]; + if (tPrev === void 0) { + switch (this.getSettings_().endingStart) { + case ZeroSlopeEnding: + iPrev = i1; + tPrev = 2 * t0 - t1; + break; + case WrapAroundEnding: + iPrev = pp.length - 2; + tPrev = t0 + pp[iPrev] - pp[iPrev + 1]; + break; + default: + iPrev = i1; + tPrev = t1; + } + } + if (tNext === void 0) { + switch (this.getSettings_().endingEnd) { + case ZeroSlopeEnding: + iNext = i1; + tNext = 2 * t1 - t0; + break; + case WrapAroundEnding: + iNext = 1; + tNext = t1 + pp[1] - pp[0]; + break; + default: + iNext = i1 - 1; + tNext = t0; + } + } + const halfDt = (t1 - t0) * 0.5, stride = this.valueSize; + this._weightPrev = halfDt / (t0 - tPrev); + this._weightNext = halfDt / (tNext - t1); + this._offsetPrev = iPrev * stride; + this._offsetNext = iNext * stride; + } + interpolate_(i1, t0, t, t1) { + const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, o1 = i1 * stride, o0 = o1 - stride, oP = this._offsetPrev, oN = this._offsetNext, wP = this._weightPrev, wN = this._weightNext, p = (t - t0) / (t1 - t0), pp = p * p, ppp = pp * p; + const sP = -wP * ppp + 2 * wP * pp - wP * p; + const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1; + const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p; + const sN = wN * ppp - wN * pp; + for (let i = 0; i !== stride; ++i) { + result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i]; + } + return result; + } + }; + var LinearInterpolant = class extends Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1, t0, t, t1) { + const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, offset1 = i1 * stride, offset0 = offset1 - stride, weight1 = (t - t0) / (t1 - t0), weight0 = 1 - weight1; + for (let i = 0; i !== stride; ++i) { + result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1; + } + return result; + } + }; + var DiscreteInterpolant = class extends Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1) { + return this.copySampleValue_(i1 - 1); + } + }; + var KeyframeTrack = class { + constructor(name, times, values, interpolation) { + if (name === void 0) throw new Error("THREE.KeyframeTrack: track name is undefined"); + if (times === void 0 || times.length === 0) throw new Error("THREE.KeyframeTrack: no keyframes in track named " + name); + this.name = name; + this.times = convertArray(times, this.TimeBufferType); + this.values = convertArray(values, this.ValueBufferType); + this.setInterpolation(interpolation || this.DefaultInterpolation); + } + // Serialization (in static context, because of constructor invocation + // and automatic invocation of .toJSON): + static toJSON(track) { + const trackType = track.constructor; + let json; + if (trackType.toJSON !== this.toJSON) { + json = trackType.toJSON(track); + } else { + json = { + "name": track.name, + "times": convertArray(track.times, Array), + "values": convertArray(track.values, Array) + }; + const interpolation = track.getInterpolation(); + if (interpolation !== track.DefaultInterpolation) { + json.interpolation = interpolation; + } + } + json.type = track.ValueTypeName; + return json; + } + InterpolantFactoryMethodDiscrete(result) { + return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result); + } + InterpolantFactoryMethodLinear(result) { + return new LinearInterpolant(this.times, this.values, this.getValueSize(), result); + } + InterpolantFactoryMethodSmooth(result) { + return new CubicInterpolant(this.times, this.values, this.getValueSize(), result); + } + setInterpolation(interpolation) { + let factoryMethod; + switch (interpolation) { + case InterpolateDiscrete: + factoryMethod = this.InterpolantFactoryMethodDiscrete; + break; + case InterpolateLinear: + factoryMethod = this.InterpolantFactoryMethodLinear; + break; + case InterpolateSmooth: + factoryMethod = this.InterpolantFactoryMethodSmooth; + break; + } + if (factoryMethod === void 0) { + const message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name; + if (this.createInterpolant === void 0) { + if (interpolation !== this.DefaultInterpolation) { + this.setInterpolation(this.DefaultInterpolation); + } else { + throw new Error(message); + } + } + console.warn("THREE.KeyframeTrack:", message); + return this; + } + this.createInterpolant = factoryMethod; + return this; + } + getInterpolation() { + switch (this.createInterpolant) { + case this.InterpolantFactoryMethodDiscrete: + return InterpolateDiscrete; + case this.InterpolantFactoryMethodLinear: + return InterpolateLinear; + case this.InterpolantFactoryMethodSmooth: + return InterpolateSmooth; + } + } + getValueSize() { + return this.values.length / this.times.length; + } + // move all keyframes either forwards or backwards in time + shift(timeOffset) { + if (timeOffset !== 0) { + const times = this.times; + for (let i = 0, n = times.length; i !== n; ++i) { + times[i] += timeOffset; + } + } + return this; + } + // scale all keyframe times by a factor (useful for frame <-> seconds conversions) + scale(timeScale) { + if (timeScale !== 1) { + const times = this.times; + for (let i = 0, n = times.length; i !== n; ++i) { + times[i] *= timeScale; + } + } + return this; + } + // removes keyframes before and after animation without changing any values within the range [startTime, endTime]. + // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values + trim(startTime, endTime) { + const times = this.times, nKeys = times.length; + let from = 0, to = nKeys - 1; + while (from !== nKeys && times[from] < startTime) { + ++from; + } + while (to !== -1 && times[to] > endTime) { + --to; + } + ++to; + if (from !== 0 || to !== nKeys) { + if (from >= to) { + to = Math.max(to, 1); + from = to - 1; + } + const stride = this.getValueSize(); + this.times = times.slice(from, to); + this.values = this.values.slice(from * stride, to * stride); + } + return this; + } + // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable + validate() { + let valid = true; + const valueSize = this.getValueSize(); + if (valueSize - Math.floor(valueSize) !== 0) { + console.error("THREE.KeyframeTrack: Invalid value size in track.", this); + valid = false; + } + const times = this.times, values = this.values, nKeys = times.length; + if (nKeys === 0) { + console.error("THREE.KeyframeTrack: Track is empty.", this); + valid = false; + } + let prevTime = null; + for (let i = 0; i !== nKeys; i++) { + const currTime = times[i]; + if (typeof currTime === "number" && isNaN(currTime)) { + console.error("THREE.KeyframeTrack: Time is not a valid number.", this, i, currTime); + valid = false; + break; + } + if (prevTime !== null && prevTime > currTime) { + console.error("THREE.KeyframeTrack: Out of order keys.", this, i, currTime, prevTime); + valid = false; + break; + } + prevTime = currTime; + } + if (values !== void 0) { + if (isTypedArray(values)) { + for (let i = 0, n = values.length; i !== n; ++i) { + const value = values[i]; + if (isNaN(value)) { + console.error("THREE.KeyframeTrack: Value is not a valid number.", this, i, value); + valid = false; + break; + } + } + } + } + return valid; + } + // removes equivalent sequential keys as common in morph target sequences + // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0) + optimize() { + const times = this.times.slice(), values = this.values.slice(), stride = this.getValueSize(), smoothInterpolation = this.getInterpolation() === InterpolateSmooth, lastIndex = times.length - 1; + let writeIndex = 1; + for (let i = 1; i < lastIndex; ++i) { + let keep = false; + const time = times[i]; + const timeNext = times[i + 1]; + if (time !== timeNext && (i !== 1 || time !== times[0])) { + if (!smoothInterpolation) { + const offset = i * stride, offsetP = offset - stride, offsetN = offset + stride; + for (let j = 0; j !== stride; ++j) { + const value = values[offset + j]; + if (value !== values[offsetP + j] || value !== values[offsetN + j]) { + keep = true; + break; + } + } + } else { + keep = true; + } + } + if (keep) { + if (i !== writeIndex) { + times[writeIndex] = times[i]; + const readOffset = i * stride, writeOffset = writeIndex * stride; + for (let j = 0; j !== stride; ++j) { + values[writeOffset + j] = values[readOffset + j]; + } + } + ++writeIndex; + } + } + if (lastIndex > 0) { + times[writeIndex] = times[lastIndex]; + for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) { + values[writeOffset + j] = values[readOffset + j]; + } + ++writeIndex; + } + if (writeIndex !== times.length) { + this.times = times.slice(0, writeIndex); + this.values = values.slice(0, writeIndex * stride); + } else { + this.times = times; + this.values = values; + } + return this; + } + clone() { + const times = this.times.slice(); + const values = this.values.slice(); + const TypedKeyframeTrack = this.constructor; + const track = new TypedKeyframeTrack(this.name, times, values); + track.createInterpolant = this.createInterpolant; + return track; + } + }; + KeyframeTrack.prototype.TimeBufferType = Float32Array; + KeyframeTrack.prototype.ValueBufferType = Float32Array; + KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; + var BooleanKeyframeTrack = class extends KeyframeTrack { + }; + BooleanKeyframeTrack.prototype.ValueTypeName = "bool"; + BooleanKeyframeTrack.prototype.ValueBufferType = Array; + BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; + BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = void 0; + BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = void 0; + var ColorKeyframeTrack = class extends KeyframeTrack { + }; + ColorKeyframeTrack.prototype.ValueTypeName = "color"; + var NumberKeyframeTrack = class extends KeyframeTrack { + }; + NumberKeyframeTrack.prototype.ValueTypeName = "number"; + var QuaternionLinearInterpolant = class extends Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1, t0, t, t1) { + const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, alpha = (t - t0) / (t1 - t0); + let offset = i1 * stride; + for (let end = offset + stride; offset !== end; offset += 4) { + Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha); + } + return result; + } + }; + var QuaternionKeyframeTrack = class extends KeyframeTrack { + InterpolantFactoryMethodLinear(result) { + return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result); + } + }; + QuaternionKeyframeTrack.prototype.ValueTypeName = "quaternion"; + QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; + QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = void 0; + var StringKeyframeTrack = class extends KeyframeTrack { + }; + StringKeyframeTrack.prototype.ValueTypeName = "string"; + StringKeyframeTrack.prototype.ValueBufferType = Array; + StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; + StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = void 0; + StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = void 0; + var VectorKeyframeTrack = class extends KeyframeTrack { + }; + VectorKeyframeTrack.prototype.ValueTypeName = "vector"; + var AnimationClip = class { + constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) { + this.name = name; + this.tracks = tracks; + this.duration = duration; + this.blendMode = blendMode; + this.uuid = generateUUID(); + if (this.duration < 0) { + this.resetDuration(); + } + } + static parse(json) { + const tracks = [], jsonTracks = json.tracks, frameTime = 1 / (json.fps || 1); + for (let i = 0, n = jsonTracks.length; i !== n; ++i) { + tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime)); + } + const clip = new this(json.name, json.duration, tracks, json.blendMode); + clip.uuid = json.uuid; + return clip; + } + static toJSON(clip) { + const tracks = [], clipTracks = clip.tracks; + const json = { + "name": clip.name, + "duration": clip.duration, + "tracks": tracks, + "uuid": clip.uuid, + "blendMode": clip.blendMode + }; + for (let i = 0, n = clipTracks.length; i !== n; ++i) { + tracks.push(KeyframeTrack.toJSON(clipTracks[i])); + } + return json; + } + static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) { + const numMorphTargets = morphTargetSequence.length; + const tracks = []; + for (let i = 0; i < numMorphTargets; i++) { + let times = []; + let values = []; + times.push( + (i + numMorphTargets - 1) % numMorphTargets, + i, + (i + 1) % numMorphTargets + ); + values.push(0, 1, 0); + const order = getKeyframeOrder(times); + times = sortedArray(times, 1, order); + values = sortedArray(values, 1, order); + if (!noLoop && times[0] === 0) { + times.push(numMorphTargets); + values.push(values[0]); + } + tracks.push( + new NumberKeyframeTrack( + ".morphTargetInfluences[" + morphTargetSequence[i].name + "]", + times, + values + ).scale(1 / fps) + ); + } + return new this(name, -1, tracks); + } + static findByName(objectOrClipArray, name) { + let clipArray = objectOrClipArray; + if (!Array.isArray(objectOrClipArray)) { + const o = objectOrClipArray; + clipArray = o.geometry && o.geometry.animations || o.animations; + } + for (let i = 0; i < clipArray.length; i++) { + if (clipArray[i].name === name) { + return clipArray[i]; + } + } + return null; + } + static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) { + const animationToMorphTargets = {}; + const pattern = /^([\w-]*?)([\d]+)$/; + for (let i = 0, il = morphTargets.length; i < il; i++) { + const morphTarget = morphTargets[i]; + const parts = morphTarget.name.match(pattern); + if (parts && parts.length > 1) { + const name = parts[1]; + let animationMorphTargets = animationToMorphTargets[name]; + if (!animationMorphTargets) { + animationToMorphTargets[name] = animationMorphTargets = []; + } + animationMorphTargets.push(morphTarget); + } + } + const clips = []; + for (const name in animationToMorphTargets) { + clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop)); + } + return clips; + } + // parse the animation.hierarchy format + static parseAnimation(animation, bones) { + if (!animation) { + console.error("THREE.AnimationClip: No animation in JSONLoader data."); + return null; + } + const addNonemptyTrack = function(trackType, trackName, animationKeys, propertyName, destTracks) { + if (animationKeys.length !== 0) { + const times = []; + const values = []; + flattenJSON(animationKeys, times, values, propertyName); + if (times.length !== 0) { + destTracks.push(new trackType(trackName, times, values)); + } + } + }; + const tracks = []; + const clipName = animation.name || "default"; + const fps = animation.fps || 30; + const blendMode = animation.blendMode; + let duration = animation.length || -1; + const hierarchyTracks = animation.hierarchy || []; + for (let h = 0; h < hierarchyTracks.length; h++) { + const animationKeys = hierarchyTracks[h].keys; + if (!animationKeys || animationKeys.length === 0) continue; + if (animationKeys[0].morphTargets) { + const morphTargetNames = {}; + let k; + for (k = 0; k < animationKeys.length; k++) { + if (animationKeys[k].morphTargets) { + for (let m = 0; m < animationKeys[k].morphTargets.length; m++) { + morphTargetNames[animationKeys[k].morphTargets[m]] = -1; + } + } + } + for (const morphTargetName in morphTargetNames) { + const times = []; + const values = []; + for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) { + const animationKey = animationKeys[k]; + times.push(animationKey.time); + values.push(animationKey.morphTarget === morphTargetName ? 1 : 0); + } + tracks.push(new NumberKeyframeTrack(".morphTargetInfluence[" + morphTargetName + "]", times, values)); + } + duration = morphTargetNames.length * fps; + } else { + const boneName = ".bones[" + bones[h].name + "]"; + addNonemptyTrack( + VectorKeyframeTrack, + boneName + ".position", + animationKeys, + "pos", + tracks + ); + addNonemptyTrack( + QuaternionKeyframeTrack, + boneName + ".quaternion", + animationKeys, + "rot", + tracks + ); + addNonemptyTrack( + VectorKeyframeTrack, + boneName + ".scale", + animationKeys, + "scl", + tracks + ); + } + } + if (tracks.length === 0) { + return null; + } + const clip = new this(clipName, duration, tracks, blendMode); + return clip; + } + resetDuration() { + const tracks = this.tracks; + let duration = 0; + for (let i = 0, n = tracks.length; i !== n; ++i) { + const track = this.tracks[i]; + duration = Math.max(duration, track.times[track.times.length - 1]); + } + this.duration = duration; + return this; + } + trim() { + for (let i = 0; i < this.tracks.length; i++) { + this.tracks[i].trim(0, this.duration); + } + return this; + } + validate() { + let valid = true; + for (let i = 0; i < this.tracks.length; i++) { + valid = valid && this.tracks[i].validate(); + } + return valid; + } + optimize() { + for (let i = 0; i < this.tracks.length; i++) { + this.tracks[i].optimize(); + } + return this; + } + clone() { + const tracks = []; + for (let i = 0; i < this.tracks.length; i++) { + tracks.push(this.tracks[i].clone()); + } + return new this.constructor(this.name, this.duration, tracks, this.blendMode); + } + toJSON() { + return this.constructor.toJSON(this); + } + }; + function getTrackTypeForValueTypeName(typeName) { + switch (typeName.toLowerCase()) { + case "scalar": + case "double": + case "float": + case "number": + case "integer": + return NumberKeyframeTrack; + case "vector": + case "vector2": + case "vector3": + case "vector4": + return VectorKeyframeTrack; + case "color": + return ColorKeyframeTrack; + case "quaternion": + return QuaternionKeyframeTrack; + case "bool": + case "boolean": + return BooleanKeyframeTrack; + case "string": + return StringKeyframeTrack; + } + throw new Error("THREE.KeyframeTrack: Unsupported typeName: " + typeName); + } + function parseKeyframeTrack(json) { + if (json.type === void 0) { + throw new Error("THREE.KeyframeTrack: track type undefined, can not parse"); + } + const trackType = getTrackTypeForValueTypeName(json.type); + if (json.times === void 0) { + const times = [], values = []; + flattenJSON(json.keys, times, values, "value"); + json.times = times; + json.values = values; + } + if (trackType.parse !== void 0) { + return trackType.parse(json); + } else { + return new trackType(json.name, json.times, json.values, json.interpolation); + } + } + var Cache = { + enabled: false, + files: {}, + add: function(key, file) { + if (this.enabled === false) return; + this.files[key] = file; + }, + get: function(key) { + if (this.enabled === false) return; + return this.files[key]; + }, + remove: function(key) { + delete this.files[key]; + }, + clear: function() { + this.files = {}; + } + }; + var LoadingManager = class { + constructor(onLoad, onProgress, onError) { + const scope = this; + let isLoading = false; + let itemsLoaded = 0; + let itemsTotal = 0; + let urlModifier = void 0; + const handlers = []; + this.onStart = void 0; + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; + this.itemStart = function(url) { + itemsTotal++; + if (isLoading === false) { + if (scope.onStart !== void 0) { + scope.onStart(url, itemsLoaded, itemsTotal); + } + } + isLoading = true; + }; + this.itemEnd = function(url) { + itemsLoaded++; + if (scope.onProgress !== void 0) { + scope.onProgress(url, itemsLoaded, itemsTotal); + } + if (itemsLoaded === itemsTotal) { + isLoading = false; + if (scope.onLoad !== void 0) { + scope.onLoad(); + } + } + }; + this.itemError = function(url) { + if (scope.onError !== void 0) { + scope.onError(url); + } + }; + this.resolveURL = function(url) { + if (urlModifier) { + return urlModifier(url); + } + return url; + }; + this.setURLModifier = function(transform) { + urlModifier = transform; + return this; + }; + this.addHandler = function(regex, loader) { + handlers.push(regex, loader); + return this; + }; + this.removeHandler = function(regex) { + const index = handlers.indexOf(regex); + if (index !== -1) { + handlers.splice(index, 2); + } + return this; + }; + this.getHandler = function(file) { + for (let i = 0, l = handlers.length; i < l; i += 2) { + const regex = handlers[i]; + const loader = handlers[i + 1]; + if (regex.global) regex.lastIndex = 0; + if (regex.test(file)) { + return loader; + } + } + return null; + }; + } + }; + var DefaultLoadingManager = /* @__PURE__ */ new LoadingManager(); + var Loader = class { + constructor(manager) { + this.manager = manager !== void 0 ? manager : DefaultLoadingManager; + this.crossOrigin = "anonymous"; + this.withCredentials = false; + this.path = ""; + this.resourcePath = ""; + this.requestHeader = {}; + } + load() { + } + loadAsync(url, onProgress) { + const scope = this; + return new Promise(function(resolve, reject) { + scope.load(url, resolve, onProgress, reject); + }); + } + parse() { + } + setCrossOrigin(crossOrigin) { + this.crossOrigin = crossOrigin; + return this; + } + setWithCredentials(value) { + this.withCredentials = value; + return this; + } + setPath(path) { + this.path = path; + return this; + } + setResourcePath(resourcePath) { + this.resourcePath = resourcePath; + return this; + } + setRequestHeader(requestHeader) { + this.requestHeader = requestHeader; + return this; + } + }; + Loader.DEFAULT_MATERIAL_NAME = "__DEFAULT"; + var loading = {}; + var HttpError = class extends Error { + constructor(message, response) { + super(message); + this.response = response; + } + }; + var FileLoader = class extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + if (url === void 0) url = ""; + if (this.path !== void 0) url = this.path + url; + url = this.manager.resolveURL(url); + const cached = Cache.get(url); + if (cached !== void 0) { + this.manager.itemStart(url); + setTimeout(() => { + if (onLoad) onLoad(cached); + this.manager.itemEnd(url); + }, 0); + return cached; + } + if (loading[url] !== void 0) { + loading[url].push({ + onLoad, + onProgress, + onError + }); + return; + } + loading[url] = []; + loading[url].push({ + onLoad, + onProgress, + onError + }); + const req = new Request(url, { + headers: new Headers(this.requestHeader), + credentials: this.withCredentials ? "include" : "same-origin" + // An abort controller could be added within a future PR + }); + const mimeType = this.mimeType; + const responseType = this.responseType; + fetch(req).then((response) => { + if (response.status === 200 || response.status === 0) { + if (response.status === 0) { + console.warn("THREE.FileLoader: HTTP Status 0 received."); + } + if (typeof ReadableStream === "undefined" || response.body === void 0 || response.body.getReader === void 0) { + return response; + } + const callbacks = loading[url]; + const reader = response.body.getReader(); + const contentLength = response.headers.get("Content-Length") || response.headers.get("X-File-Size"); + const total = contentLength ? parseInt(contentLength) : 0; + const lengthComputable = total !== 0; + let loaded = 0; + const stream = new ReadableStream({ + start(controller) { + readData(); + function readData() { + reader.read().then(({ done, value }) => { + if (done) { + controller.close(); + } else { + loaded += value.byteLength; + const event = new ProgressEvent("progress", { lengthComputable, loaded, total }); + for (let i = 0, il = callbacks.length; i < il; i++) { + const callback = callbacks[i]; + if (callback.onProgress) callback.onProgress(event); + } + controller.enqueue(value); + readData(); + } + }); + } + } + }); + return new Response(stream); + } else { + throw new HttpError(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response); + } + }).then((response) => { + switch (responseType) { + case "arraybuffer": + return response.arrayBuffer(); + case "blob": + return response.blob(); + case "document": + return response.text().then((text) => { + const parser = new DOMParser(); + return parser.parseFromString(text, mimeType); + }); + case "json": + return response.json(); + default: + if (mimeType === void 0) { + return response.text(); + } else { + const re = /charset="?([^;"\s]*)"?/i; + const exec = re.exec(mimeType); + const label = exec && exec[1] ? exec[1].toLowerCase() : void 0; + const decoder = new TextDecoder(label); + return response.arrayBuffer().then((ab) => decoder.decode(ab)); + } + } + }).then((data) => { + Cache.add(url, data); + const callbacks = loading[url]; + delete loading[url]; + for (let i = 0, il = callbacks.length; i < il; i++) { + const callback = callbacks[i]; + if (callback.onLoad) callback.onLoad(data); + } + }).catch((err) => { + const callbacks = loading[url]; + if (callbacks === void 0) { + this.manager.itemError(url); + throw err; + } + delete loading[url]; + for (let i = 0, il = callbacks.length; i < il; i++) { + const callback = callbacks[i]; + if (callback.onError) callback.onError(err); + } + this.manager.itemError(url); + }).finally(() => { + this.manager.itemEnd(url); + }); + this.manager.itemStart(url); + } + setResponseType(value) { + this.responseType = value; + return this; + } + setMimeType(value) { + this.mimeType = value; + return this; + } + }; + var AnimationLoader = class extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(text) { + try { + onLoad(scope.parse(JSON.parse(text))); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(json) { + const animations = []; + for (let i = 0; i < json.length; i++) { + const clip = AnimationClip.parse(json[i]); + animations.push(clip); + } + return animations; + } + }; + var CompressedTextureLoader = class extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const images = []; + const texture = new CompressedTexture(); + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setResponseType("arraybuffer"); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(scope.withCredentials); + let loaded = 0; + function loadTexture(i) { + loader.load(url[i], function(buffer) { + const texDatas = scope.parse(buffer, true); + images[i] = { + width: texDatas.width, + height: texDatas.height, + format: texDatas.format, + mipmaps: texDatas.mipmaps + }; + loaded += 1; + if (loaded === 6) { + if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter; + texture.image = images; + texture.format = texDatas.format; + texture.needsUpdate = true; + if (onLoad) onLoad(texture); + } + }, onProgress, onError); + } + if (Array.isArray(url)) { + for (let i = 0, il = url.length; i < il; ++i) { + loadTexture(i); + } + } else { + loader.load(url, function(buffer) { + const texDatas = scope.parse(buffer, true); + if (texDatas.isCubemap) { + const faces = texDatas.mipmaps.length / texDatas.mipmapCount; + for (let f = 0; f < faces; f++) { + images[f] = { mipmaps: [] }; + for (let i = 0; i < texDatas.mipmapCount; i++) { + images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]); + images[f].format = texDatas.format; + images[f].width = texDatas.width; + images[f].height = texDatas.height; + } + } + texture.image = images; + } else { + texture.image.width = texDatas.width; + texture.image.height = texDatas.height; + texture.mipmaps = texDatas.mipmaps; + } + if (texDatas.mipmapCount === 1) { + texture.minFilter = LinearFilter; + } + texture.format = texDatas.format; + texture.needsUpdate = true; + if (onLoad) onLoad(texture); + }, onProgress, onError); + } + return texture; + } + }; + var ImageLoader = class extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + if (this.path !== void 0) url = this.path + url; + url = this.manager.resolveURL(url); + const scope = this; + const cached = Cache.get(url); + if (cached !== void 0) { + scope.manager.itemStart(url); + setTimeout(function() { + if (onLoad) onLoad(cached); + scope.manager.itemEnd(url); + }, 0); + return cached; + } + const image = createElementNS("img"); + function onImageLoad() { + removeEventListeners(); + Cache.add(url, this); + if (onLoad) onLoad(this); + scope.manager.itemEnd(url); + } + function onImageError(event) { + removeEventListeners(); + if (onError) onError(event); + scope.manager.itemError(url); + scope.manager.itemEnd(url); + } + function removeEventListeners() { + image.removeEventListener("load", onImageLoad, false); + image.removeEventListener("error", onImageError, false); + } + image.addEventListener("load", onImageLoad, false); + image.addEventListener("error", onImageError, false); + if (url.slice(0, 5) !== "data:") { + if (this.crossOrigin !== void 0) image.crossOrigin = this.crossOrigin; + } + scope.manager.itemStart(url); + image.src = url; + return image; + } + }; + var CubeTextureLoader = class extends Loader { + constructor(manager) { + super(manager); + } + load(urls, onLoad, onProgress, onError) { + const texture = new CubeTexture(); + texture.colorSpace = SRGBColorSpace; + const loader = new ImageLoader(this.manager); + loader.setCrossOrigin(this.crossOrigin); + loader.setPath(this.path); + let loaded = 0; + function loadTexture(i) { + loader.load(urls[i], function(image) { + texture.images[i] = image; + loaded++; + if (loaded === 6) { + texture.needsUpdate = true; + if (onLoad) onLoad(texture); + } + }, void 0, onError); + } + for (let i = 0; i < urls.length; ++i) { + loadTexture(i); + } + return texture; + } + }; + var DataTextureLoader = class extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const texture = new DataTexture(); + const loader = new FileLoader(this.manager); + loader.setResponseType("arraybuffer"); + loader.setRequestHeader(this.requestHeader); + loader.setPath(this.path); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(buffer) { + let texData; + try { + texData = scope.parse(buffer); + } catch (error) { + if (onError !== void 0) { + onError(error); + } else { + console.error(error); + return; + } + } + if (texData.image !== void 0) { + texture.image = texData.image; + } else if (texData.data !== void 0) { + texture.image.width = texData.width; + texture.image.height = texData.height; + texture.image.data = texData.data; + } + texture.wrapS = texData.wrapS !== void 0 ? texData.wrapS : ClampToEdgeWrapping; + texture.wrapT = texData.wrapT !== void 0 ? texData.wrapT : ClampToEdgeWrapping; + texture.magFilter = texData.magFilter !== void 0 ? texData.magFilter : LinearFilter; + texture.minFilter = texData.minFilter !== void 0 ? texData.minFilter : LinearFilter; + texture.anisotropy = texData.anisotropy !== void 0 ? texData.anisotropy : 1; + if (texData.colorSpace !== void 0) { + texture.colorSpace = texData.colorSpace; + } else if (texData.encoding !== void 0) { + texture.encoding = texData.encoding; + } + if (texData.flipY !== void 0) { + texture.flipY = texData.flipY; + } + if (texData.format !== void 0) { + texture.format = texData.format; + } + if (texData.type !== void 0) { + texture.type = texData.type; + } + if (texData.mipmaps !== void 0) { + texture.mipmaps = texData.mipmaps; + texture.minFilter = LinearMipmapLinearFilter; + } + if (texData.mipmapCount === 1) { + texture.minFilter = LinearFilter; + } + if (texData.generateMipmaps !== void 0) { + texture.generateMipmaps = texData.generateMipmaps; + } + texture.needsUpdate = true; + if (onLoad) onLoad(texture, texData); + }, onProgress, onError); + return texture; + } + }; + var TextureLoader = class extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const texture = new Texture(); + const loader = new ImageLoader(this.manager); + loader.setCrossOrigin(this.crossOrigin); + loader.setPath(this.path); + loader.load(url, function(image) { + texture.image = image; + texture.needsUpdate = true; + if (onLoad !== void 0) { + onLoad(texture); + } + }, onProgress, onError); + return texture; + } + }; + var Light = class extends Object3D { + constructor(color, intensity = 1) { + super(); + this.isLight = true; + this.type = "Light"; + this.color = new Color(color); + this.intensity = intensity; + } + dispose() { + } + copy(source, recursive) { + super.copy(source, recursive); + this.color.copy(source.color); + this.intensity = source.intensity; + return this; + } + toJSON(meta) { + const data = super.toJSON(meta); + data.object.color = this.color.getHex(); + data.object.intensity = this.intensity; + if (this.groundColor !== void 0) data.object.groundColor = this.groundColor.getHex(); + if (this.distance !== void 0) data.object.distance = this.distance; + if (this.angle !== void 0) data.object.angle = this.angle; + if (this.decay !== void 0) data.object.decay = this.decay; + if (this.penumbra !== void 0) data.object.penumbra = this.penumbra; + if (this.shadow !== void 0) data.object.shadow = this.shadow.toJSON(); + return data; + } + }; + var HemisphereLight = class extends Light { + constructor(skyColor, groundColor, intensity) { + super(skyColor, intensity); + this.isHemisphereLight = true; + this.type = "HemisphereLight"; + this.position.copy(Object3D.DEFAULT_UP); + this.updateMatrix(); + this.groundColor = new Color(groundColor); + } + copy(source, recursive) { + super.copy(source, recursive); + this.groundColor.copy(source.groundColor); + return this; + } + }; + var _projScreenMatrix$1 = /* @__PURE__ */ new Matrix4(); + var _lightPositionWorld$1 = /* @__PURE__ */ new Vector3(); + var _lookTarget$1 = /* @__PURE__ */ new Vector3(); + var LightShadow = class { + constructor(camera) { + this.camera = camera; + this.bias = 0; + this.normalBias = 0; + this.radius = 1; + this.blurSamples = 8; + this.mapSize = new Vector2(512, 512); + this.map = null; + this.mapPass = null; + this.matrix = new Matrix4(); + this.autoUpdate = true; + this.needsUpdate = false; + this._frustum = new Frustum(); + this._frameExtents = new Vector2(1, 1); + this._viewportCount = 1; + this._viewports = [ + new Vector4(0, 0, 1, 1) + ]; + } + getViewportCount() { + return this._viewportCount; + } + getFrustum() { + return this._frustum; + } + updateMatrices(light) { + const shadowCamera = this.camera; + const shadowMatrix = this.matrix; + _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld); + shadowCamera.position.copy(_lightPositionWorld$1); + _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld); + shadowCamera.lookAt(_lookTarget$1); + shadowCamera.updateMatrixWorld(); + _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse); + this._frustum.setFromProjectionMatrix(_projScreenMatrix$1); + shadowMatrix.set( + 0.5, + 0, + 0, + 0.5, + 0, + 0.5, + 0, + 0.5, + 0, + 0, + 0.5, + 0.5, + 0, + 0, + 0, + 1 + ); + shadowMatrix.multiply(_projScreenMatrix$1); + } + getViewport(viewportIndex) { + return this._viewports[viewportIndex]; + } + getFrameExtents() { + return this._frameExtents; + } + dispose() { + if (this.map) { + this.map.dispose(); + } + if (this.mapPass) { + this.mapPass.dispose(); + } + } + copy(source) { + this.camera = source.camera.clone(); + this.bias = source.bias; + this.radius = source.radius; + this.mapSize.copy(source.mapSize); + return this; + } + clone() { + return new this.constructor().copy(this); + } + toJSON() { + const object = {}; + if (this.bias !== 0) object.bias = this.bias; + if (this.normalBias !== 0) object.normalBias = this.normalBias; + if (this.radius !== 1) object.radius = this.radius; + if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray(); + object.camera = this.camera.toJSON(false).object; + delete object.camera.matrix; + return object; + } + }; + var SpotLightShadow = class extends LightShadow { + constructor() { + super(new PerspectiveCamera(50, 1, 0.5, 500)); + this.isSpotLightShadow = true; + this.focus = 1; + } + updateMatrices(light) { + const camera = this.camera; + const fov2 = RAD2DEG * 2 * light.angle * this.focus; + const aspect2 = this.mapSize.width / this.mapSize.height; + const far = light.distance || camera.far; + if (fov2 !== camera.fov || aspect2 !== camera.aspect || far !== camera.far) { + camera.fov = fov2; + camera.aspect = aspect2; + camera.far = far; + camera.updateProjectionMatrix(); + } + super.updateMatrices(light); + } + copy(source) { + super.copy(source); + this.focus = source.focus; + return this; + } + }; + var SpotLight = class extends Light { + constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2) { + super(color, intensity); + this.isSpotLight = true; + this.type = "SpotLight"; + this.position.copy(Object3D.DEFAULT_UP); + this.updateMatrix(); + this.target = new Object3D(); + this.distance = distance; + this.angle = angle; + this.penumbra = penumbra; + this.decay = decay; + this.map = null; + this.shadow = new SpotLightShadow(); + } + get power() { + return this.intensity * Math.PI; + } + set power(power) { + this.intensity = power / Math.PI; + } + dispose() { + this.shadow.dispose(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.distance = source.distance; + this.angle = source.angle; + this.penumbra = source.penumbra; + this.decay = source.decay; + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); + return this; + } + }; + var _projScreenMatrix = /* @__PURE__ */ new Matrix4(); + var _lightPositionWorld = /* @__PURE__ */ new Vector3(); + var _lookTarget = /* @__PURE__ */ new Vector3(); + var PointLightShadow = class extends LightShadow { + constructor() { + super(new PerspectiveCamera(90, 1, 0.5, 500)); + this.isPointLightShadow = true; + this._frameExtents = new Vector2(4, 2); + this._viewportCount = 6; + this._viewports = [ + // These viewports map a cube-map onto a 2D texture with the + // following orientation: + // + // xzXZ + // y Y + // + // X - Positive x direction + // x - Negative x direction + // Y - Positive y direction + // y - Negative y direction + // Z - Positive z direction + // z - Negative z direction + // positive X + new Vector4(2, 1, 1, 1), + // negative X + new Vector4(0, 1, 1, 1), + // positive Z + new Vector4(3, 1, 1, 1), + // negative Z + new Vector4(1, 1, 1, 1), + // positive Y + new Vector4(3, 0, 1, 1), + // negative Y + new Vector4(1, 0, 1, 1) + ]; + this._cubeDirections = [ + new Vector3(1, 0, 0), + new Vector3(-1, 0, 0), + new Vector3(0, 0, 1), + new Vector3(0, 0, -1), + new Vector3(0, 1, 0), + new Vector3(0, -1, 0) + ]; + this._cubeUps = [ + new Vector3(0, 1, 0), + new Vector3(0, 1, 0), + new Vector3(0, 1, 0), + new Vector3(0, 1, 0), + new Vector3(0, 0, 1), + new Vector3(0, 0, -1) + ]; + } + updateMatrices(light, viewportIndex = 0) { + const camera = this.camera; + const shadowMatrix = this.matrix; + const far = light.distance || camera.far; + if (far !== camera.far) { + camera.far = far; + camera.updateProjectionMatrix(); + } + _lightPositionWorld.setFromMatrixPosition(light.matrixWorld); + camera.position.copy(_lightPositionWorld); + _lookTarget.copy(camera.position); + _lookTarget.add(this._cubeDirections[viewportIndex]); + camera.up.copy(this._cubeUps[viewportIndex]); + camera.lookAt(_lookTarget); + camera.updateMatrixWorld(); + shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z); + _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); + this._frustum.setFromProjectionMatrix(_projScreenMatrix); + } + }; + var PointLight = class extends Light { + constructor(color, intensity, distance = 0, decay = 2) { + super(color, intensity); + this.isPointLight = true; + this.type = "PointLight"; + this.distance = distance; + this.decay = decay; + this.shadow = new PointLightShadow(); + } + get power() { + return this.intensity * 4 * Math.PI; + } + set power(power) { + this.intensity = power / (4 * Math.PI); + } + dispose() { + this.shadow.dispose(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.distance = source.distance; + this.decay = source.decay; + this.shadow = source.shadow.clone(); + return this; + } + }; + var DirectionalLightShadow = class extends LightShadow { + constructor() { + super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500)); + this.isDirectionalLightShadow = true; + } + }; + var DirectionalLight = class extends Light { + constructor(color, intensity) { + super(color, intensity); + this.isDirectionalLight = true; + this.type = "DirectionalLight"; + this.position.copy(Object3D.DEFAULT_UP); + this.updateMatrix(); + this.target = new Object3D(); + this.shadow = new DirectionalLightShadow(); + } + dispose() { + this.shadow.dispose(); + } + copy(source) { + super.copy(source); + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); + return this; + } + }; + var AmbientLight = class extends Light { + constructor(color, intensity) { + super(color, intensity); + this.isAmbientLight = true; + this.type = "AmbientLight"; + } + }; + var RectAreaLight = class extends Light { + constructor(color, intensity, width = 10, height = 10) { + super(color, intensity); + this.isRectAreaLight = true; + this.type = "RectAreaLight"; + this.width = width; + this.height = height; + } + get power() { + return this.intensity * this.width * this.height * Math.PI; + } + set power(power) { + this.intensity = power / (this.width * this.height * Math.PI); + } + copy(source) { + super.copy(source); + this.width = source.width; + this.height = source.height; + return this; + } + toJSON(meta) { + const data = super.toJSON(meta); + data.object.width = this.width; + data.object.height = this.height; + return data; + } + }; + var SphericalHarmonics3 = class { + constructor() { + this.isSphericalHarmonics3 = true; + this.coefficients = []; + for (let i = 0; i < 9; i++) { + this.coefficients.push(new Vector3()); + } + } + set(coefficients) { + for (let i = 0; i < 9; i++) { + this.coefficients[i].copy(coefficients[i]); + } + return this; + } + zero() { + for (let i = 0; i < 9; i++) { + this.coefficients[i].set(0, 0, 0); + } + return this; + } + // get the radiance in the direction of the normal + // target is a Vector3 + getAt(normal, target) { + const x = normal.x, y = normal.y, z = normal.z; + const coeff = this.coefficients; + target.copy(coeff[0]).multiplyScalar(0.282095); + target.addScaledVector(coeff[1], 0.488603 * y); + target.addScaledVector(coeff[2], 0.488603 * z); + target.addScaledVector(coeff[3], 0.488603 * x); + target.addScaledVector(coeff[4], 1.092548 * (x * y)); + target.addScaledVector(coeff[5], 1.092548 * (y * z)); + target.addScaledVector(coeff[6], 0.315392 * (3 * z * z - 1)); + target.addScaledVector(coeff[7], 1.092548 * (x * z)); + target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y)); + return target; + } + // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal + // target is a Vector3 + // https://graphics.stanford.edu/papers/envmap/envmap.pdf + getIrradianceAt(normal, target) { + const x = normal.x, y = normal.y, z = normal.z; + const coeff = this.coefficients; + target.copy(coeff[0]).multiplyScalar(0.886227); + target.addScaledVector(coeff[1], 2 * 0.511664 * y); + target.addScaledVector(coeff[2], 2 * 0.511664 * z); + target.addScaledVector(coeff[3], 2 * 0.511664 * x); + target.addScaledVector(coeff[4], 2 * 0.429043 * x * y); + target.addScaledVector(coeff[5], 2 * 0.429043 * y * z); + target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); + target.addScaledVector(coeff[7], 2 * 0.429043 * x * z); + target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); + return target; + } + add(sh) { + for (let i = 0; i < 9; i++) { + this.coefficients[i].add(sh.coefficients[i]); + } + return this; + } + addScaledSH(sh, s) { + for (let i = 0; i < 9; i++) { + this.coefficients[i].addScaledVector(sh.coefficients[i], s); + } + return this; + } + scale(s) { + for (let i = 0; i < 9; i++) { + this.coefficients[i].multiplyScalar(s); + } + return this; + } + lerp(sh, alpha) { + for (let i = 0; i < 9; i++) { + this.coefficients[i].lerp(sh.coefficients[i], alpha); + } + return this; + } + equals(sh) { + for (let i = 0; i < 9; i++) { + if (!this.coefficients[i].equals(sh.coefficients[i])) { + return false; + } + } + return true; + } + copy(sh) { + return this.set(sh.coefficients); + } + clone() { + return new this.constructor().copy(this); + } + fromArray(array, offset = 0) { + const coefficients = this.coefficients; + for (let i = 0; i < 9; i++) { + coefficients[i].fromArray(array, offset + i * 3); + } + return this; + } + toArray(array = [], offset = 0) { + const coefficients = this.coefficients; + for (let i = 0; i < 9; i++) { + coefficients[i].toArray(array, offset + i * 3); + } + return array; + } + // evaluate the basis functions + // shBasis is an Array[ 9 ] + static getBasisAt(normal, shBasis) { + const x = normal.x, y = normal.y, z = normal.z; + shBasis[0] = 0.282095; + shBasis[1] = 0.488603 * y; + shBasis[2] = 0.488603 * z; + shBasis[3] = 0.488603 * x; + shBasis[4] = 1.092548 * x * y; + shBasis[5] = 1.092548 * y * z; + shBasis[6] = 0.315392 * (3 * z * z - 1); + shBasis[7] = 1.092548 * x * z; + shBasis[8] = 0.546274 * (x * x - y * y); + } + }; + var LightProbe = class extends Light { + constructor(sh = new SphericalHarmonics3(), intensity = 1) { + super(void 0, intensity); + this.isLightProbe = true; + this.sh = sh; + } + copy(source) { + super.copy(source); + this.sh.copy(source.sh); + return this; + } + fromJSON(json) { + this.intensity = json.intensity; + this.sh.fromArray(json.sh); + return this; + } + toJSON(meta) { + const data = super.toJSON(meta); + data.object.sh = this.sh.toArray(); + return data; + } + }; + var MaterialLoader = class _MaterialLoader extends Loader { + constructor(manager) { + super(manager); + this.textures = {}; + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader(scope.manager); + loader.setPath(scope.path); + loader.setRequestHeader(scope.requestHeader); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(text) { + try { + onLoad(scope.parse(JSON.parse(text))); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(json) { + const textures = this.textures; + function getTexture(name) { + if (textures[name] === void 0) { + console.warn("THREE.MaterialLoader: Undefined texture", name); + } + return textures[name]; + } + const material = _MaterialLoader.createMaterialFromType(json.type); + if (json.uuid !== void 0) material.uuid = json.uuid; + if (json.name !== void 0) material.name = json.name; + if (json.color !== void 0 && material.color !== void 0) material.color.setHex(json.color); + if (json.roughness !== void 0) material.roughness = json.roughness; + if (json.metalness !== void 0) material.metalness = json.metalness; + if (json.sheen !== void 0) material.sheen = json.sheen; + if (json.sheenColor !== void 0) material.sheenColor = new Color().setHex(json.sheenColor); + if (json.sheenRoughness !== void 0) material.sheenRoughness = json.sheenRoughness; + if (json.emissive !== void 0 && material.emissive !== void 0) material.emissive.setHex(json.emissive); + if (json.specular !== void 0 && material.specular !== void 0) material.specular.setHex(json.specular); + if (json.specularIntensity !== void 0) material.specularIntensity = json.specularIntensity; + if (json.specularColor !== void 0 && material.specularColor !== void 0) material.specularColor.setHex(json.specularColor); + if (json.shininess !== void 0) material.shininess = json.shininess; + if (json.clearcoat !== void 0) material.clearcoat = json.clearcoat; + if (json.clearcoatRoughness !== void 0) material.clearcoatRoughness = json.clearcoatRoughness; + if (json.iridescence !== void 0) material.iridescence = json.iridescence; + if (json.iridescenceIOR !== void 0) material.iridescenceIOR = json.iridescenceIOR; + if (json.iridescenceThicknessRange !== void 0) material.iridescenceThicknessRange = json.iridescenceThicknessRange; + if (json.transmission !== void 0) material.transmission = json.transmission; + if (json.thickness !== void 0) material.thickness = json.thickness; + if (json.attenuationDistance !== void 0) material.attenuationDistance = json.attenuationDistance; + if (json.attenuationColor !== void 0 && material.attenuationColor !== void 0) material.attenuationColor.setHex(json.attenuationColor); + if (json.anisotropy !== void 0) material.anisotropy = json.anisotropy; + if (json.anisotropyRotation !== void 0) material.anisotropyRotation = json.anisotropyRotation; + if (json.fog !== void 0) material.fog = json.fog; + if (json.flatShading !== void 0) material.flatShading = json.flatShading; + if (json.blending !== void 0) material.blending = json.blending; + if (json.combine !== void 0) material.combine = json.combine; + if (json.side !== void 0) material.side = json.side; + if (json.shadowSide !== void 0) material.shadowSide = json.shadowSide; + if (json.opacity !== void 0) material.opacity = json.opacity; + if (json.transparent !== void 0) material.transparent = json.transparent; + if (json.alphaTest !== void 0) material.alphaTest = json.alphaTest; + if (json.alphaHash !== void 0) material.alphaHash = json.alphaHash; + if (json.depthFunc !== void 0) material.depthFunc = json.depthFunc; + if (json.depthTest !== void 0) material.depthTest = json.depthTest; + if (json.depthWrite !== void 0) material.depthWrite = json.depthWrite; + if (json.colorWrite !== void 0) material.colorWrite = json.colorWrite; + if (json.blendSrc !== void 0) material.blendSrc = json.blendSrc; + if (json.blendDst !== void 0) material.blendDst = json.blendDst; + if (json.blendEquation !== void 0) material.blendEquation = json.blendEquation; + if (json.blendSrcAlpha !== void 0) material.blendSrcAlpha = json.blendSrcAlpha; + if (json.blendDstAlpha !== void 0) material.blendDstAlpha = json.blendDstAlpha; + if (json.blendEquationAlpha !== void 0) material.blendEquationAlpha = json.blendEquationAlpha; + if (json.blendColor !== void 0 && material.blendColor !== void 0) material.blendColor.setHex(json.blendColor); + if (json.blendAlpha !== void 0) material.blendAlpha = json.blendAlpha; + if (json.stencilWriteMask !== void 0) material.stencilWriteMask = json.stencilWriteMask; + if (json.stencilFunc !== void 0) material.stencilFunc = json.stencilFunc; + if (json.stencilRef !== void 0) material.stencilRef = json.stencilRef; + if (json.stencilFuncMask !== void 0) material.stencilFuncMask = json.stencilFuncMask; + if (json.stencilFail !== void 0) material.stencilFail = json.stencilFail; + if (json.stencilZFail !== void 0) material.stencilZFail = json.stencilZFail; + if (json.stencilZPass !== void 0) material.stencilZPass = json.stencilZPass; + if (json.stencilWrite !== void 0) material.stencilWrite = json.stencilWrite; + if (json.wireframe !== void 0) material.wireframe = json.wireframe; + if (json.wireframeLinewidth !== void 0) material.wireframeLinewidth = json.wireframeLinewidth; + if (json.wireframeLinecap !== void 0) material.wireframeLinecap = json.wireframeLinecap; + if (json.wireframeLinejoin !== void 0) material.wireframeLinejoin = json.wireframeLinejoin; + if (json.rotation !== void 0) material.rotation = json.rotation; + if (json.linewidth !== void 0) material.linewidth = json.linewidth; + if (json.dashSize !== void 0) material.dashSize = json.dashSize; + if (json.gapSize !== void 0) material.gapSize = json.gapSize; + if (json.scale !== void 0) material.scale = json.scale; + if (json.polygonOffset !== void 0) material.polygonOffset = json.polygonOffset; + if (json.polygonOffsetFactor !== void 0) material.polygonOffsetFactor = json.polygonOffsetFactor; + if (json.polygonOffsetUnits !== void 0) material.polygonOffsetUnits = json.polygonOffsetUnits; + if (json.dithering !== void 0) material.dithering = json.dithering; + if (json.alphaToCoverage !== void 0) material.alphaToCoverage = json.alphaToCoverage; + if (json.premultipliedAlpha !== void 0) material.premultipliedAlpha = json.premultipliedAlpha; + if (json.forceSinglePass !== void 0) material.forceSinglePass = json.forceSinglePass; + if (json.visible !== void 0) material.visible = json.visible; + if (json.toneMapped !== void 0) material.toneMapped = json.toneMapped; + if (json.userData !== void 0) material.userData = json.userData; + if (json.vertexColors !== void 0) { + if (typeof json.vertexColors === "number") { + material.vertexColors = json.vertexColors > 0 ? true : false; + } else { + material.vertexColors = json.vertexColors; + } + } + if (json.uniforms !== void 0) { + for (const name in json.uniforms) { + const uniform = json.uniforms[name]; + material.uniforms[name] = {}; + switch (uniform.type) { + case "t": + material.uniforms[name].value = getTexture(uniform.value); + break; + case "c": + material.uniforms[name].value = new Color().setHex(uniform.value); + break; + case "v2": + material.uniforms[name].value = new Vector2().fromArray(uniform.value); + break; + case "v3": + material.uniforms[name].value = new Vector3().fromArray(uniform.value); + break; + case "v4": + material.uniforms[name].value = new Vector4().fromArray(uniform.value); + break; + case "m3": + material.uniforms[name].value = new Matrix3().fromArray(uniform.value); + break; + case "m4": + material.uniforms[name].value = new Matrix4().fromArray(uniform.value); + break; + default: + material.uniforms[name].value = uniform.value; + } + } + } + if (json.defines !== void 0) material.defines = json.defines; + if (json.vertexShader !== void 0) material.vertexShader = json.vertexShader; + if (json.fragmentShader !== void 0) material.fragmentShader = json.fragmentShader; + if (json.glslVersion !== void 0) material.glslVersion = json.glslVersion; + if (json.extensions !== void 0) { + for (const key in json.extensions) { + material.extensions[key] = json.extensions[key]; + } + } + if (json.lights !== void 0) material.lights = json.lights; + if (json.clipping !== void 0) material.clipping = json.clipping; + if (json.size !== void 0) material.size = json.size; + if (json.sizeAttenuation !== void 0) material.sizeAttenuation = json.sizeAttenuation; + if (json.map !== void 0) material.map = getTexture(json.map); + if (json.matcap !== void 0) material.matcap = getTexture(json.matcap); + if (json.alphaMap !== void 0) material.alphaMap = getTexture(json.alphaMap); + if (json.bumpMap !== void 0) material.bumpMap = getTexture(json.bumpMap); + if (json.bumpScale !== void 0) material.bumpScale = json.bumpScale; + if (json.normalMap !== void 0) material.normalMap = getTexture(json.normalMap); + if (json.normalMapType !== void 0) material.normalMapType = json.normalMapType; + if (json.normalScale !== void 0) { + let normalScale = json.normalScale; + if (Array.isArray(normalScale) === false) { + normalScale = [normalScale, normalScale]; + } + material.normalScale = new Vector2().fromArray(normalScale); + } + if (json.displacementMap !== void 0) material.displacementMap = getTexture(json.displacementMap); + if (json.displacementScale !== void 0) material.displacementScale = json.displacementScale; + if (json.displacementBias !== void 0) material.displacementBias = json.displacementBias; + if (json.roughnessMap !== void 0) material.roughnessMap = getTexture(json.roughnessMap); + if (json.metalnessMap !== void 0) material.metalnessMap = getTexture(json.metalnessMap); + if (json.emissiveMap !== void 0) material.emissiveMap = getTexture(json.emissiveMap); + if (json.emissiveIntensity !== void 0) material.emissiveIntensity = json.emissiveIntensity; + if (json.specularMap !== void 0) material.specularMap = getTexture(json.specularMap); + if (json.specularIntensityMap !== void 0) material.specularIntensityMap = getTexture(json.specularIntensityMap); + if (json.specularColorMap !== void 0) material.specularColorMap = getTexture(json.specularColorMap); + if (json.envMap !== void 0) material.envMap = getTexture(json.envMap); + if (json.envMapIntensity !== void 0) material.envMapIntensity = json.envMapIntensity; + if (json.reflectivity !== void 0) material.reflectivity = json.reflectivity; + if (json.refractionRatio !== void 0) material.refractionRatio = json.refractionRatio; + if (json.lightMap !== void 0) material.lightMap = getTexture(json.lightMap); + if (json.lightMapIntensity !== void 0) material.lightMapIntensity = json.lightMapIntensity; + if (json.aoMap !== void 0) material.aoMap = getTexture(json.aoMap); + if (json.aoMapIntensity !== void 0) material.aoMapIntensity = json.aoMapIntensity; + if (json.gradientMap !== void 0) material.gradientMap = getTexture(json.gradientMap); + if (json.clearcoatMap !== void 0) material.clearcoatMap = getTexture(json.clearcoatMap); + if (json.clearcoatRoughnessMap !== void 0) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap); + if (json.clearcoatNormalMap !== void 0) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap); + if (json.clearcoatNormalScale !== void 0) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale); + if (json.iridescenceMap !== void 0) material.iridescenceMap = getTexture(json.iridescenceMap); + if (json.iridescenceThicknessMap !== void 0) material.iridescenceThicknessMap = getTexture(json.iridescenceThicknessMap); + if (json.transmissionMap !== void 0) material.transmissionMap = getTexture(json.transmissionMap); + if (json.thicknessMap !== void 0) material.thicknessMap = getTexture(json.thicknessMap); + if (json.anisotropyMap !== void 0) material.anisotropyMap = getTexture(json.anisotropyMap); + if (json.sheenColorMap !== void 0) material.sheenColorMap = getTexture(json.sheenColorMap); + if (json.sheenRoughnessMap !== void 0) material.sheenRoughnessMap = getTexture(json.sheenRoughnessMap); + return material; + } + setTextures(value) { + this.textures = value; + return this; + } + static createMaterialFromType(type) { + const materialLib = { + ShadowMaterial, + SpriteMaterial, + RawShaderMaterial, + ShaderMaterial, + PointsMaterial, + MeshPhysicalMaterial, + MeshStandardMaterial, + MeshPhongMaterial, + MeshToonMaterial, + MeshNormalMaterial, + MeshLambertMaterial, + MeshDepthMaterial, + MeshDistanceMaterial, + MeshBasicMaterial, + MeshMatcapMaterial, + LineDashedMaterial, + LineBasicMaterial, + Material + }; + return new materialLib[type](); + } + }; + var LoaderUtils = class { + static decodeText(array) { + if (typeof TextDecoder !== "undefined") { + return new TextDecoder().decode(array); + } + let s = ""; + for (let i = 0, il = array.length; i < il; i++) { + s += String.fromCharCode(array[i]); + } + try { + return decodeURIComponent(escape(s)); + } catch (e) { + return s; + } + } + static extractUrlBase(url) { + const index = url.lastIndexOf("/"); + if (index === -1) return "./"; + return url.slice(0, index + 1); + } + static resolveURL(url, path) { + if (typeof url !== "string" || url === "") return ""; + if (/^https?:\/\//i.test(path) && /^\//.test(url)) { + path = path.replace(/(^https?:\/\/[^\/]+).*/i, "$1"); + } + if (/^(https?:)?\/\//i.test(url)) return url; + if (/^data:.*,.*$/i.test(url)) return url; + if (/^blob:.*$/i.test(url)) return url; + return path + url; + } + }; + var InstancedBufferGeometry = class extends BufferGeometry { + constructor() { + super(); + this.isInstancedBufferGeometry = true; + this.type = "InstancedBufferGeometry"; + this.instanceCount = Infinity; + } + copy(source) { + super.copy(source); + this.instanceCount = source.instanceCount; + return this; + } + toJSON() { + const data = super.toJSON(); + data.instanceCount = this.instanceCount; + data.isInstancedBufferGeometry = true; + return data; + } + }; + var BufferGeometryLoader = class extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader(scope.manager); + loader.setPath(scope.path); + loader.setRequestHeader(scope.requestHeader); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(text) { + try { + onLoad(scope.parse(JSON.parse(text))); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(json) { + const interleavedBufferMap = {}; + const arrayBufferMap = {}; + function getInterleavedBuffer(json2, uuid) { + if (interleavedBufferMap[uuid] !== void 0) return interleavedBufferMap[uuid]; + const interleavedBuffers = json2.interleavedBuffers; + const interleavedBuffer = interleavedBuffers[uuid]; + const buffer = getArrayBuffer(json2, interleavedBuffer.buffer); + const array = getTypedArray(interleavedBuffer.type, buffer); + const ib = new InterleavedBuffer(array, interleavedBuffer.stride); + ib.uuid = interleavedBuffer.uuid; + interleavedBufferMap[uuid] = ib; + return ib; + } + function getArrayBuffer(json2, uuid) { + if (arrayBufferMap[uuid] !== void 0) return arrayBufferMap[uuid]; + const arrayBuffers = json2.arrayBuffers; + const arrayBuffer = arrayBuffers[uuid]; + const ab = new Uint32Array(arrayBuffer).buffer; + arrayBufferMap[uuid] = ab; + return ab; + } + const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry(); + const index = json.data.index; + if (index !== void 0) { + const typedArray = getTypedArray(index.type, index.array); + geometry.setIndex(new BufferAttribute(typedArray, 1)); + } + const attributes = json.data.attributes; + for (const key in attributes) { + const attribute = attributes[key]; + let bufferAttribute; + if (attribute.isInterleavedBufferAttribute) { + const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data); + bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized); + } else { + const typedArray = getTypedArray(attribute.type, attribute.array); + const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute; + bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized); + } + if (attribute.name !== void 0) bufferAttribute.name = attribute.name; + if (attribute.usage !== void 0) bufferAttribute.setUsage(attribute.usage); + geometry.setAttribute(key, bufferAttribute); + } + const morphAttributes = json.data.morphAttributes; + if (morphAttributes) { + for (const key in morphAttributes) { + const attributeArray = morphAttributes[key]; + const array = []; + for (let i = 0, il = attributeArray.length; i < il; i++) { + const attribute = attributeArray[i]; + let bufferAttribute; + if (attribute.isInterleavedBufferAttribute) { + const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data); + bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized); + } else { + const typedArray = getTypedArray(attribute.type, attribute.array); + bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized); + } + if (attribute.name !== void 0) bufferAttribute.name = attribute.name; + array.push(bufferAttribute); + } + geometry.morphAttributes[key] = array; + } + } + const morphTargetsRelative = json.data.morphTargetsRelative; + if (morphTargetsRelative) { + geometry.morphTargetsRelative = true; + } + const groups = json.data.groups || json.data.drawcalls || json.data.offsets; + if (groups !== void 0) { + for (let i = 0, n = groups.length; i !== n; ++i) { + const group = groups[i]; + geometry.addGroup(group.start, group.count, group.materialIndex); + } + } + const boundingSphere = json.data.boundingSphere; + if (boundingSphere !== void 0) { + const center = new Vector3(); + if (boundingSphere.center !== void 0) { + center.fromArray(boundingSphere.center); + } + geometry.boundingSphere = new Sphere(center, boundingSphere.radius); + } + if (json.name) geometry.name = json.name; + if (json.userData) geometry.userData = json.userData; + return geometry; + } + }; + var ObjectLoader = class extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const path = this.path === "" ? LoaderUtils.extractUrlBase(url) : this.path; + this.resourcePath = this.resourcePath || path; + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(text) { + let json = null; + try { + json = JSON.parse(text); + } catch (error) { + if (onError !== void 0) onError(error); + console.error("THREE:ObjectLoader: Can't parse " + url + ".", error.message); + return; + } + const metadata = json.metadata; + if (metadata === void 0 || metadata.type === void 0 || metadata.type.toLowerCase() === "geometry") { + if (onError !== void 0) onError(new Error("THREE.ObjectLoader: Can't load " + url)); + console.error("THREE.ObjectLoader: Can't load " + url); + return; + } + scope.parse(json, onLoad); + }, onProgress, onError); + } + async loadAsync(url, onProgress) { + const scope = this; + const path = this.path === "" ? LoaderUtils.extractUrlBase(url) : this.path; + this.resourcePath = this.resourcePath || path; + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + const text = await loader.loadAsync(url, onProgress); + const json = JSON.parse(text); + const metadata = json.metadata; + if (metadata === void 0 || metadata.type === void 0 || metadata.type.toLowerCase() === "geometry") { + throw new Error("THREE.ObjectLoader: Can't load " + url); + } + return await scope.parseAsync(json); + } + parse(json, onLoad) { + const animations = this.parseAnimations(json.animations); + const shapes = this.parseShapes(json.shapes); + const geometries = this.parseGeometries(json.geometries, shapes); + const images = this.parseImages(json.images, function() { + if (onLoad !== void 0) onLoad(object); + }); + const textures = this.parseTextures(json.textures, images); + const materials = this.parseMaterials(json.materials, textures); + const object = this.parseObject(json.object, geometries, materials, textures, animations); + const skeletons = this.parseSkeletons(json.skeletons, object); + this.bindSkeletons(object, skeletons); + if (onLoad !== void 0) { + let hasImages = false; + for (const uuid in images) { + if (images[uuid].data instanceof HTMLImageElement) { + hasImages = true; + break; + } + } + if (hasImages === false) onLoad(object); + } + return object; + } + async parseAsync(json) { + const animations = this.parseAnimations(json.animations); + const shapes = this.parseShapes(json.shapes); + const geometries = this.parseGeometries(json.geometries, shapes); + const images = await this.parseImagesAsync(json.images); + const textures = this.parseTextures(json.textures, images); + const materials = this.parseMaterials(json.materials, textures); + const object = this.parseObject(json.object, geometries, materials, textures, animations); + const skeletons = this.parseSkeletons(json.skeletons, object); + this.bindSkeletons(object, skeletons); + return object; + } + parseShapes(json) { + const shapes = {}; + if (json !== void 0) { + for (let i = 0, l = json.length; i < l; i++) { + const shape = new Shape().fromJSON(json[i]); + shapes[shape.uuid] = shape; + } + } + return shapes; + } + parseSkeletons(json, object) { + const skeletons = {}; + const bones = {}; + object.traverse(function(child) { + if (child.isBone) bones[child.uuid] = child; + }); + if (json !== void 0) { + for (let i = 0, l = json.length; i < l; i++) { + const skeleton = new Skeleton().fromJSON(json[i], bones); + skeletons[skeleton.uuid] = skeleton; + } + } + return skeletons; + } + parseGeometries(json, shapes) { + const geometries = {}; + if (json !== void 0) { + const bufferGeometryLoader = new BufferGeometryLoader(); + for (let i = 0, l = json.length; i < l; i++) { + let geometry; + const data = json[i]; + switch (data.type) { + case "BufferGeometry": + case "InstancedBufferGeometry": + geometry = bufferGeometryLoader.parse(data); + break; + default: + if (data.type in Geometries) { + geometry = Geometries[data.type].fromJSON(data, shapes); + } else { + console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data.type}"`); + } + } + geometry.uuid = data.uuid; + if (data.name !== void 0) geometry.name = data.name; + if (data.userData !== void 0) geometry.userData = data.userData; + geometries[data.uuid] = geometry; + } + } + return geometries; + } + parseMaterials(json, textures) { + const cache = {}; + const materials = {}; + if (json !== void 0) { + const loader = new MaterialLoader(); + loader.setTextures(textures); + for (let i = 0, l = json.length; i < l; i++) { + const data = json[i]; + if (cache[data.uuid] === void 0) { + cache[data.uuid] = loader.parse(data); + } + materials[data.uuid] = cache[data.uuid]; + } + } + return materials; + } + parseAnimations(json) { + const animations = {}; + if (json !== void 0) { + for (let i = 0; i < json.length; i++) { + const data = json[i]; + const clip = AnimationClip.parse(data); + animations[clip.uuid] = clip; + } + } + return animations; + } + parseImages(json, onLoad) { + const scope = this; + const images = {}; + let loader; + function loadImage(url) { + scope.manager.itemStart(url); + return loader.load(url, function() { + scope.manager.itemEnd(url); + }, void 0, function() { + scope.manager.itemError(url); + scope.manager.itemEnd(url); + }); + } + function deserializeImage(image) { + if (typeof image === "string") { + const url = image; + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url; + return loadImage(path); + } else { + if (image.data) { + return { + data: getTypedArray(image.type, image.data), + width: image.width, + height: image.height + }; + } else { + return null; + } + } + } + if (json !== void 0 && json.length > 0) { + const manager = new LoadingManager(onLoad); + loader = new ImageLoader(manager); + loader.setCrossOrigin(this.crossOrigin); + for (let i = 0, il = json.length; i < il; i++) { + const image = json[i]; + const url = image.url; + if (Array.isArray(url)) { + const imageArray = []; + for (let j = 0, jl = url.length; j < jl; j++) { + const currentUrl = url[j]; + const deserializedImage = deserializeImage(currentUrl); + if (deserializedImage !== null) { + if (deserializedImage instanceof HTMLImageElement) { + imageArray.push(deserializedImage); + } else { + imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height)); + } + } + } + images[image.uuid] = new Source(imageArray); + } else { + const deserializedImage = deserializeImage(image.url); + images[image.uuid] = new Source(deserializedImage); + } + } + } + return images; + } + async parseImagesAsync(json) { + const scope = this; + const images = {}; + let loader; + async function deserializeImage(image) { + if (typeof image === "string") { + const url = image; + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url; + return await loader.loadAsync(path); + } else { + if (image.data) { + return { + data: getTypedArray(image.type, image.data), + width: image.width, + height: image.height + }; + } else { + return null; + } + } + } + if (json !== void 0 && json.length > 0) { + loader = new ImageLoader(this.manager); + loader.setCrossOrigin(this.crossOrigin); + for (let i = 0, il = json.length; i < il; i++) { + const image = json[i]; + const url = image.url; + if (Array.isArray(url)) { + const imageArray = []; + for (let j = 0, jl = url.length; j < jl; j++) { + const currentUrl = url[j]; + const deserializedImage = await deserializeImage(currentUrl); + if (deserializedImage !== null) { + if (deserializedImage instanceof HTMLImageElement) { + imageArray.push(deserializedImage); + } else { + imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height)); + } + } + } + images[image.uuid] = new Source(imageArray); + } else { + const deserializedImage = await deserializeImage(image.url); + images[image.uuid] = new Source(deserializedImage); + } + } + } + return images; + } + parseTextures(json, images) { + function parseConstant(value, type) { + if (typeof value === "number") return value; + console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.", value); + return type[value]; + } + const textures = {}; + if (json !== void 0) { + for (let i = 0, l = json.length; i < l; i++) { + const data = json[i]; + if (data.image === void 0) { + console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid); + } + if (images[data.image] === void 0) { + console.warn("THREE.ObjectLoader: Undefined image", data.image); + } + const source = images[data.image]; + const image = source.data; + let texture; + if (Array.isArray(image)) { + texture = new CubeTexture(); + if (image.length === 6) texture.needsUpdate = true; + } else { + if (image && image.data) { + texture = new DataTexture(); + } else { + texture = new Texture(); + } + if (image) texture.needsUpdate = true; + } + texture.source = source; + texture.uuid = data.uuid; + if (data.name !== void 0) texture.name = data.name; + if (data.mapping !== void 0) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING); + if (data.channel !== void 0) texture.channel = data.channel; + if (data.offset !== void 0) texture.offset.fromArray(data.offset); + if (data.repeat !== void 0) texture.repeat.fromArray(data.repeat); + if (data.center !== void 0) texture.center.fromArray(data.center); + if (data.rotation !== void 0) texture.rotation = data.rotation; + if (data.wrap !== void 0) { + texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING); + texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING); + } + if (data.format !== void 0) texture.format = data.format; + if (data.internalFormat !== void 0) texture.internalFormat = data.internalFormat; + if (data.type !== void 0) texture.type = data.type; + if (data.colorSpace !== void 0) texture.colorSpace = data.colorSpace; + if (data.encoding !== void 0) texture.encoding = data.encoding; + if (data.minFilter !== void 0) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER); + if (data.magFilter !== void 0) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER); + if (data.anisotropy !== void 0) texture.anisotropy = data.anisotropy; + if (data.flipY !== void 0) texture.flipY = data.flipY; + if (data.generateMipmaps !== void 0) texture.generateMipmaps = data.generateMipmaps; + if (data.premultiplyAlpha !== void 0) texture.premultiplyAlpha = data.premultiplyAlpha; + if (data.unpackAlignment !== void 0) texture.unpackAlignment = data.unpackAlignment; + if (data.compareFunction !== void 0) texture.compareFunction = data.compareFunction; + if (data.userData !== void 0) texture.userData = data.userData; + textures[data.uuid] = texture; + } + } + return textures; + } + parseObject(data, geometries, materials, textures, animations) { + let object; + function getGeometry(name) { + if (geometries[name] === void 0) { + console.warn("THREE.ObjectLoader: Undefined geometry", name); + } + return geometries[name]; + } + function getMaterial(name) { + if (name === void 0) return void 0; + if (Array.isArray(name)) { + const array = []; + for (let i = 0, l = name.length; i < l; i++) { + const uuid = name[i]; + if (materials[uuid] === void 0) { + console.warn("THREE.ObjectLoader: Undefined material", uuid); + } + array.push(materials[uuid]); + } + return array; + } + if (materials[name] === void 0) { + console.warn("THREE.ObjectLoader: Undefined material", name); + } + return materials[name]; + } + function getTexture(uuid) { + if (textures[uuid] === void 0) { + console.warn("THREE.ObjectLoader: Undefined texture", uuid); + } + return textures[uuid]; + } + let geometry, material; + switch (data.type) { + case "Scene": + object = new Scene(); + if (data.background !== void 0) { + if (Number.isInteger(data.background)) { + object.background = new Color(data.background); + } else { + object.background = getTexture(data.background); + } + } + if (data.environment !== void 0) { + object.environment = getTexture(data.environment); + } + if (data.fog !== void 0) { + if (data.fog.type === "Fog") { + object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far); + } else if (data.fog.type === "FogExp2") { + object.fog = new FogExp2(data.fog.color, data.fog.density); + } + if (data.fog.name !== "") { + object.fog.name = data.fog.name; + } + } + if (data.backgroundBlurriness !== void 0) object.backgroundBlurriness = data.backgroundBlurriness; + if (data.backgroundIntensity !== void 0) object.backgroundIntensity = data.backgroundIntensity; + break; + case "PerspectiveCamera": + object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far); + if (data.focus !== void 0) object.focus = data.focus; + if (data.zoom !== void 0) object.zoom = data.zoom; + if (data.filmGauge !== void 0) object.filmGauge = data.filmGauge; + if (data.filmOffset !== void 0) object.filmOffset = data.filmOffset; + if (data.view !== void 0) object.view = Object.assign({}, data.view); + break; + case "OrthographicCamera": + object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far); + if (data.zoom !== void 0) object.zoom = data.zoom; + if (data.view !== void 0) object.view = Object.assign({}, data.view); + break; + case "AmbientLight": + object = new AmbientLight(data.color, data.intensity); + break; + case "DirectionalLight": + object = new DirectionalLight(data.color, data.intensity); + break; + case "PointLight": + object = new PointLight(data.color, data.intensity, data.distance, data.decay); + break; + case "RectAreaLight": + object = new RectAreaLight(data.color, data.intensity, data.width, data.height); + break; + case "SpotLight": + object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay); + break; + case "HemisphereLight": + object = new HemisphereLight(data.color, data.groundColor, data.intensity); + break; + case "LightProbe": + object = new LightProbe().fromJSON(data); + break; + case "SkinnedMesh": + geometry = getGeometry(data.geometry); + material = getMaterial(data.material); + object = new SkinnedMesh(geometry, material); + if (data.bindMode !== void 0) object.bindMode = data.bindMode; + if (data.bindMatrix !== void 0) object.bindMatrix.fromArray(data.bindMatrix); + if (data.skeleton !== void 0) object.skeleton = data.skeleton; + break; + case "Mesh": + geometry = getGeometry(data.geometry); + material = getMaterial(data.material); + object = new Mesh(geometry, material); + break; + case "InstancedMesh": + geometry = getGeometry(data.geometry); + material = getMaterial(data.material); + const count = data.count; + const instanceMatrix = data.instanceMatrix; + const instanceColor = data.instanceColor; + object = new InstancedMesh(geometry, material, count); + object.instanceMatrix = new InstancedBufferAttribute(new Float32Array(instanceMatrix.array), 16); + if (instanceColor !== void 0) object.instanceColor = new InstancedBufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize); + break; + case "BatchedMesh": + geometry = getGeometry(data.geometry); + material = getMaterial(data.material); + object = new BatchedMesh(data.maxGeometryCount, data.maxVertexCount, data.maxIndexCount, material); + object.geometry = geometry; + object.perObjectFrustumCulled = data.perObjectFrustumCulled; + object.sortObjects = data.sortObjects; + object._drawRanges = data.drawRanges; + object._reservedRanges = data.reservedRanges; + object._visibility = data.visibility; + object._active = data.active; + object._bounds = data.bounds.map((bound) => { + const box = new Box3(); + box.min.fromArray(bound.boxMin); + box.max.fromArray(bound.boxMax); + const sphere = new Sphere(); + sphere.radius = bound.sphereRadius; + sphere.center.fromArray(bound.sphereCenter); + return { + boxInitialized: bound.boxInitialized, + box, + sphereInitialized: bound.sphereInitialized, + sphere + }; + }); + object._maxGeometryCount = data.maxGeometryCount; + object._maxVertexCount = data.maxVertexCount; + object._maxIndexCount = data.maxIndexCount; + object._geometryInitialized = data.geometryInitialized; + object._geometryCount = data.geometryCount; + object._matricesTexture = getTexture(data.matricesTexture.uuid); + break; + case "LOD": + object = new LOD(); + break; + case "Line": + object = new Line(getGeometry(data.geometry), getMaterial(data.material)); + break; + case "LineLoop": + object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material)); + break; + case "LineSegments": + object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material)); + break; + case "PointCloud": + case "Points": + object = new Points(getGeometry(data.geometry), getMaterial(data.material)); + break; + case "Sprite": + object = new Sprite(getMaterial(data.material)); + break; + case "Group": + object = new Group(); + break; + case "Bone": + object = new Bone(); + break; + default: + object = new Object3D(); + } + object.uuid = data.uuid; + if (data.name !== void 0) object.name = data.name; + if (data.matrix !== void 0) { + object.matrix.fromArray(data.matrix); + if (data.matrixAutoUpdate !== void 0) object.matrixAutoUpdate = data.matrixAutoUpdate; + if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale); + } else { + if (data.position !== void 0) object.position.fromArray(data.position); + if (data.rotation !== void 0) object.rotation.fromArray(data.rotation); + if (data.quaternion !== void 0) object.quaternion.fromArray(data.quaternion); + if (data.scale !== void 0) object.scale.fromArray(data.scale); + } + if (data.up !== void 0) object.up.fromArray(data.up); + if (data.castShadow !== void 0) object.castShadow = data.castShadow; + if (data.receiveShadow !== void 0) object.receiveShadow = data.receiveShadow; + if (data.shadow) { + if (data.shadow.bias !== void 0) object.shadow.bias = data.shadow.bias; + if (data.shadow.normalBias !== void 0) object.shadow.normalBias = data.shadow.normalBias; + if (data.shadow.radius !== void 0) object.shadow.radius = data.shadow.radius; + if (data.shadow.mapSize !== void 0) object.shadow.mapSize.fromArray(data.shadow.mapSize); + if (data.shadow.camera !== void 0) object.shadow.camera = this.parseObject(data.shadow.camera); + } + if (data.visible !== void 0) object.visible = data.visible; + if (data.frustumCulled !== void 0) object.frustumCulled = data.frustumCulled; + if (data.renderOrder !== void 0) object.renderOrder = data.renderOrder; + if (data.userData !== void 0) object.userData = data.userData; + if (data.layers !== void 0) object.layers.mask = data.layers; + if (data.children !== void 0) { + const children = data.children; + for (let i = 0; i < children.length; i++) { + object.add(this.parseObject(children[i], geometries, materials, textures, animations)); + } + } + if (data.animations !== void 0) { + const objectAnimations = data.animations; + for (let i = 0; i < objectAnimations.length; i++) { + const uuid = objectAnimations[i]; + object.animations.push(animations[uuid]); + } + } + if (data.type === "LOD") { + if (data.autoUpdate !== void 0) object.autoUpdate = data.autoUpdate; + const levels = data.levels; + for (let l = 0; l < levels.length; l++) { + const level = levels[l]; + const child = object.getObjectByProperty("uuid", level.object); + if (child !== void 0) { + object.addLevel(child, level.distance, level.hysteresis); + } + } + } + return object; + } + bindSkeletons(object, skeletons) { + if (Object.keys(skeletons).length === 0) return; + object.traverse(function(child) { + if (child.isSkinnedMesh === true && child.skeleton !== void 0) { + const skeleton = skeletons[child.skeleton]; + if (skeleton === void 0) { + console.warn("THREE.ObjectLoader: No skeleton found with UUID:", child.skeleton); + } else { + child.bind(skeleton, child.bindMatrix); + } + } + }); + } + }; + var TEXTURE_MAPPING = { + UVMapping, + CubeReflectionMapping, + CubeRefractionMapping, + EquirectangularReflectionMapping, + EquirectangularRefractionMapping, + CubeUVReflectionMapping + }; + var TEXTURE_WRAPPING = { + RepeatWrapping, + ClampToEdgeWrapping, + MirroredRepeatWrapping + }; + var TEXTURE_FILTER = { + NearestFilter, + NearestMipmapNearestFilter, + NearestMipmapLinearFilter, + LinearFilter, + LinearMipmapNearestFilter, + LinearMipmapLinearFilter + }; + var ImageBitmapLoader = class extends Loader { + constructor(manager) { + super(manager); + this.isImageBitmapLoader = true; + if (typeof createImageBitmap === "undefined") { + console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."); + } + if (typeof fetch === "undefined") { + console.warn("THREE.ImageBitmapLoader: fetch() not supported."); + } + this.options = { premultiplyAlpha: "none" }; + } + setOptions(options) { + this.options = options; + return this; + } + load(url, onLoad, onProgress, onError) { + if (url === void 0) url = ""; + if (this.path !== void 0) url = this.path + url; + url = this.manager.resolveURL(url); + const scope = this; + const cached = Cache.get(url); + if (cached !== void 0) { + scope.manager.itemStart(url); + if (cached.then) { + cached.then((imageBitmap) => { + if (onLoad) onLoad(imageBitmap); + scope.manager.itemEnd(url); + }).catch((e) => { + if (onError) onError(e); + }); + return; + } + setTimeout(function() { + if (onLoad) onLoad(cached); + scope.manager.itemEnd(url); + }, 0); + return cached; + } + const fetchOptions = {}; + fetchOptions.credentials = this.crossOrigin === "anonymous" ? "same-origin" : "include"; + fetchOptions.headers = this.requestHeader; + const promise = fetch(url, fetchOptions).then(function(res) { + return res.blob(); + }).then(function(blob) { + return createImageBitmap(blob, Object.assign(scope.options, { colorSpaceConversion: "none" })); + }).then(function(imageBitmap) { + Cache.add(url, imageBitmap); + if (onLoad) onLoad(imageBitmap); + scope.manager.itemEnd(url); + return imageBitmap; + }).catch(function(e) { + if (onError) onError(e); + Cache.remove(url); + scope.manager.itemError(url); + scope.manager.itemEnd(url); + }); + Cache.add(url, promise); + scope.manager.itemStart(url); + } + }; + var _context; + var AudioContext = class { + static getContext() { + if (_context === void 0) { + _context = new (window.AudioContext || window.webkitAudioContext)(); + } + return _context; + } + static setContext(value) { + _context = value; + } + }; + var AudioLoader = class extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader(this.manager); + loader.setResponseType("arraybuffer"); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(buffer) { + try { + const bufferCopy = buffer.slice(0); + const context = AudioContext.getContext(); + context.decodeAudioData(bufferCopy, function(audioBuffer) { + onLoad(audioBuffer); + }).catch(handleError); + } catch (e) { + handleError(e); + } + }, onProgress, onError); + function handleError(e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + } + }; + var _eyeRight = /* @__PURE__ */ new Matrix4(); + var _eyeLeft = /* @__PURE__ */ new Matrix4(); + var _projectionMatrix = /* @__PURE__ */ new Matrix4(); + var StereoCamera = class { + constructor() { + this.type = "StereoCamera"; + this.aspect = 1; + this.eyeSep = 0.064; + this.cameraL = new PerspectiveCamera(); + this.cameraL.layers.enable(1); + this.cameraL.matrixAutoUpdate = false; + this.cameraR = new PerspectiveCamera(); + this.cameraR.layers.enable(2); + this.cameraR.matrixAutoUpdate = false; + this._cache = { + focus: null, + fov: null, + aspect: null, + near: null, + far: null, + zoom: null, + eyeSep: null + }; + } + update(camera) { + const cache = this._cache; + const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep; + if (needsUpdate) { + cache.focus = camera.focus; + cache.fov = camera.fov; + cache.aspect = camera.aspect * this.aspect; + cache.near = camera.near; + cache.far = camera.far; + cache.zoom = camera.zoom; + cache.eyeSep = this.eyeSep; + _projectionMatrix.copy(camera.projectionMatrix); + const eyeSepHalf = cache.eyeSep / 2; + const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus; + const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom; + let xmin, xmax; + _eyeLeft.elements[12] = -eyeSepHalf; + _eyeRight.elements[12] = eyeSepHalf; + xmin = -ymax * cache.aspect + eyeSepOnProjection; + xmax = ymax * cache.aspect + eyeSepOnProjection; + _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin); + _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin); + this.cameraL.projectionMatrix.copy(_projectionMatrix); + xmin = -ymax * cache.aspect - eyeSepOnProjection; + xmax = ymax * cache.aspect - eyeSepOnProjection; + _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin); + _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin); + this.cameraR.projectionMatrix.copy(_projectionMatrix); + } + this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft); + this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight); + } + }; + var Clock = class { + constructor(autoStart = true) { + this.autoStart = autoStart; + this.startTime = 0; + this.oldTime = 0; + this.elapsedTime = 0; + this.running = false; + } + start() { + this.startTime = now(); + this.oldTime = this.startTime; + this.elapsedTime = 0; + this.running = true; + } + stop() { + this.getElapsedTime(); + this.running = false; + this.autoStart = false; + } + getElapsedTime() { + this.getDelta(); + return this.elapsedTime; + } + getDelta() { + let diff = 0; + if (this.autoStart && !this.running) { + this.start(); + return 0; + } + if (this.running) { + const newTime = now(); + diff = (newTime - this.oldTime) / 1e3; + this.oldTime = newTime; + this.elapsedTime += diff; + } + return diff; + } + }; + function now() { + return (typeof performance === "undefined" ? Date : performance).now(); + } + var _position$1 = /* @__PURE__ */ new Vector3(); + var _quaternion$1 = /* @__PURE__ */ new Quaternion(); + var _scale$1 = /* @__PURE__ */ new Vector3(); + var _orientation$1 = /* @__PURE__ */ new Vector3(); + var AudioListener = class extends Object3D { + constructor() { + super(); + this.type = "AudioListener"; + this.context = AudioContext.getContext(); + this.gain = this.context.createGain(); + this.gain.connect(this.context.destination); + this.filter = null; + this.timeDelta = 0; + this._clock = new Clock(); + } + getInput() { + return this.gain; + } + removeFilter() { + if (this.filter !== null) { + this.gain.disconnect(this.filter); + this.filter.disconnect(this.context.destination); + this.gain.connect(this.context.destination); + this.filter = null; + } + return this; + } + getFilter() { + return this.filter; + } + setFilter(value) { + if (this.filter !== null) { + this.gain.disconnect(this.filter); + this.filter.disconnect(this.context.destination); + } else { + this.gain.disconnect(this.context.destination); + } + this.filter = value; + this.gain.connect(this.filter); + this.filter.connect(this.context.destination); + return this; + } + getMasterVolume() { + return this.gain.gain.value; + } + setMasterVolume(value) { + this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01); + return this; + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + const listener = this.context.listener; + const up = this.up; + this.timeDelta = this._clock.getDelta(); + this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1); + _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1); + if (listener.positionX) { + const endTime = this.context.currentTime + this.timeDelta; + listener.positionX.linearRampToValueAtTime(_position$1.x, endTime); + listener.positionY.linearRampToValueAtTime(_position$1.y, endTime); + listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime); + listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime); + listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime); + listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime); + listener.upX.linearRampToValueAtTime(up.x, endTime); + listener.upY.linearRampToValueAtTime(up.y, endTime); + listener.upZ.linearRampToValueAtTime(up.z, endTime); + } else { + listener.setPosition(_position$1.x, _position$1.y, _position$1.z); + listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z); + } + } + }; + var Audio = class extends Object3D { + constructor(listener) { + super(); + this.type = "Audio"; + this.listener = listener; + this.context = listener.context; + this.gain = this.context.createGain(); + this.gain.connect(listener.getInput()); + this.autoplay = false; + this.buffer = null; + this.detune = 0; + this.loop = false; + this.loopStart = 0; + this.loopEnd = 0; + this.offset = 0; + this.duration = void 0; + this.playbackRate = 1; + this.isPlaying = false; + this.hasPlaybackControl = true; + this.source = null; + this.sourceType = "empty"; + this._startedAt = 0; + this._progress = 0; + this._connected = false; + this.filters = []; + } + getOutput() { + return this.gain; + } + setNodeSource(audioNode) { + this.hasPlaybackControl = false; + this.sourceType = "audioNode"; + this.source = audioNode; + this.connect(); + return this; + } + setMediaElementSource(mediaElement) { + this.hasPlaybackControl = false; + this.sourceType = "mediaNode"; + this.source = this.context.createMediaElementSource(mediaElement); + this.connect(); + return this; + } + setMediaStreamSource(mediaStream) { + this.hasPlaybackControl = false; + this.sourceType = "mediaStreamNode"; + this.source = this.context.createMediaStreamSource(mediaStream); + this.connect(); + return this; + } + setBuffer(audioBuffer) { + this.buffer = audioBuffer; + this.sourceType = "buffer"; + if (this.autoplay) this.play(); + return this; + } + play(delay = 0) { + if (this.isPlaying === true) { + console.warn("THREE.Audio: Audio is already playing."); + return; + } + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this._startedAt = this.context.currentTime + delay; + const source = this.context.createBufferSource(); + source.buffer = this.buffer; + source.loop = this.loop; + source.loopStart = this.loopStart; + source.loopEnd = this.loopEnd; + source.onended = this.onEnded.bind(this); + source.start(this._startedAt, this._progress + this.offset, this.duration); + this.isPlaying = true; + this.source = source; + this.setDetune(this.detune); + this.setPlaybackRate(this.playbackRate); + return this.connect(); + } + pause() { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + if (this.isPlaying === true) { + this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate; + if (this.loop === true) { + this._progress = this._progress % (this.duration || this.buffer.duration); + } + this.source.stop(); + this.source.onended = null; + this.isPlaying = false; + } + return this; + } + stop() { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this._progress = 0; + if (this.source !== null) { + this.source.stop(); + this.source.onended = null; + } + this.isPlaying = false; + return this; + } + connect() { + if (this.filters.length > 0) { + this.source.connect(this.filters[0]); + for (let i = 1, l = this.filters.length; i < l; i++) { + this.filters[i - 1].connect(this.filters[i]); + } + this.filters[this.filters.length - 1].connect(this.getOutput()); + } else { + this.source.connect(this.getOutput()); + } + this._connected = true; + return this; + } + disconnect() { + if (this._connected === false) { + return; + } + if (this.filters.length > 0) { + this.source.disconnect(this.filters[0]); + for (let i = 1, l = this.filters.length; i < l; i++) { + this.filters[i - 1].disconnect(this.filters[i]); + } + this.filters[this.filters.length - 1].disconnect(this.getOutput()); + } else { + this.source.disconnect(this.getOutput()); + } + this._connected = false; + return this; + } + getFilters() { + return this.filters; + } + setFilters(value) { + if (!value) value = []; + if (this._connected === true) { + this.disconnect(); + this.filters = value.slice(); + this.connect(); + } else { + this.filters = value.slice(); + } + return this; + } + setDetune(value) { + this.detune = value; + if (this.source.detune === void 0) return; + if (this.isPlaying === true) { + this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01); + } + return this; + } + getDetune() { + return this.detune; + } + getFilter() { + return this.getFilters()[0]; + } + setFilter(filter) { + return this.setFilters(filter ? [filter] : []); + } + setPlaybackRate(value) { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this.playbackRate = value; + if (this.isPlaying === true) { + this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01); + } + return this; + } + getPlaybackRate() { + return this.playbackRate; + } + onEnded() { + this.isPlaying = false; + } + getLoop() { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return false; + } + return this.loop; + } + setLoop(value) { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this.loop = value; + if (this.isPlaying === true) { + this.source.loop = this.loop; + } + return this; + } + setLoopStart(value) { + this.loopStart = value; + return this; + } + setLoopEnd(value) { + this.loopEnd = value; + return this; + } + getVolume() { + return this.gain.gain.value; + } + setVolume(value) { + this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01); + return this; + } + }; + var _position = /* @__PURE__ */ new Vector3(); + var _quaternion = /* @__PURE__ */ new Quaternion(); + var _scale = /* @__PURE__ */ new Vector3(); + var _orientation = /* @__PURE__ */ new Vector3(); + var PositionalAudio = class extends Audio { + constructor(listener) { + super(listener); + this.panner = this.context.createPanner(); + this.panner.panningModel = "HRTF"; + this.panner.connect(this.gain); + } + connect() { + super.connect(); + this.panner.connect(this.gain); + } + disconnect() { + super.disconnect(); + this.panner.disconnect(this.gain); + } + getOutput() { + return this.panner; + } + getRefDistance() { + return this.panner.refDistance; + } + setRefDistance(value) { + this.panner.refDistance = value; + return this; + } + getRolloffFactor() { + return this.panner.rolloffFactor; + } + setRolloffFactor(value) { + this.panner.rolloffFactor = value; + return this; + } + getDistanceModel() { + return this.panner.distanceModel; + } + setDistanceModel(value) { + this.panner.distanceModel = value; + return this; + } + getMaxDistance() { + return this.panner.maxDistance; + } + setMaxDistance(value) { + this.panner.maxDistance = value; + return this; + } + setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) { + this.panner.coneInnerAngle = coneInnerAngle; + this.panner.coneOuterAngle = coneOuterAngle; + this.panner.coneOuterGain = coneOuterGain; + return this; + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + if (this.hasPlaybackControl === true && this.isPlaying === false) return; + this.matrixWorld.decompose(_position, _quaternion, _scale); + _orientation.set(0, 0, 1).applyQuaternion(_quaternion); + const panner = this.panner; + if (panner.positionX) { + const endTime = this.context.currentTime + this.listener.timeDelta; + panner.positionX.linearRampToValueAtTime(_position.x, endTime); + panner.positionY.linearRampToValueAtTime(_position.y, endTime); + panner.positionZ.linearRampToValueAtTime(_position.z, endTime); + panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime); + panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime); + panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime); + } else { + panner.setPosition(_position.x, _position.y, _position.z); + panner.setOrientation(_orientation.x, _orientation.y, _orientation.z); + } + } + }; + var AudioAnalyser = class { + constructor(audio, fftSize = 2048) { + this.analyser = audio.context.createAnalyser(); + this.analyser.fftSize = fftSize; + this.data = new Uint8Array(this.analyser.frequencyBinCount); + audio.getOutput().connect(this.analyser); + } + getFrequencyData() { + this.analyser.getByteFrequencyData(this.data); + return this.data; + } + getAverageFrequency() { + let value = 0; + const data = this.getFrequencyData(); + for (let i = 0; i < data.length; i++) { + value += data[i]; + } + return value / data.length; + } + }; + var PropertyMixer = class { + constructor(binding, typeName, valueSize) { + this.binding = binding; + this.valueSize = valueSize; + let mixFunction, mixFunctionAdditive, setIdentity; + switch (typeName) { + case "quaternion": + mixFunction = this._slerp; + mixFunctionAdditive = this._slerpAdditive; + setIdentity = this._setAdditiveIdentityQuaternion; + this.buffer = new Float64Array(valueSize * 6); + this._workIndex = 5; + break; + case "string": + case "bool": + mixFunction = this._select; + mixFunctionAdditive = this._select; + setIdentity = this._setAdditiveIdentityOther; + this.buffer = new Array(valueSize * 5); + break; + default: + mixFunction = this._lerp; + mixFunctionAdditive = this._lerpAdditive; + setIdentity = this._setAdditiveIdentityNumeric; + this.buffer = new Float64Array(valueSize * 5); + } + this._mixBufferRegion = mixFunction; + this._mixBufferRegionAdditive = mixFunctionAdditive; + this._setIdentity = setIdentity; + this._origIndex = 3; + this._addIndex = 4; + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + this.useCount = 0; + this.referenceCount = 0; + } + // accumulate data in the 'incoming' region into 'accu' + accumulate(accuIndex, weight) { + const buffer = this.buffer, stride = this.valueSize, offset = accuIndex * stride + stride; + let currentWeight = this.cumulativeWeight; + if (currentWeight === 0) { + for (let i = 0; i !== stride; ++i) { + buffer[offset + i] = buffer[i]; + } + currentWeight = weight; + } else { + currentWeight += weight; + const mix = weight / currentWeight; + this._mixBufferRegion(buffer, offset, 0, mix, stride); + } + this.cumulativeWeight = currentWeight; + } + // accumulate data in the 'incoming' region into 'add' + accumulateAdditive(weight) { + const buffer = this.buffer, stride = this.valueSize, offset = stride * this._addIndex; + if (this.cumulativeWeightAdditive === 0) { + this._setIdentity(); + } + this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride); + this.cumulativeWeightAdditive += weight; + } + // apply the state of 'accu' to the binding when accus differ + apply(accuIndex) { + const stride = this.valueSize, buffer = this.buffer, offset = accuIndex * stride + stride, weight = this.cumulativeWeight, weightAdditive = this.cumulativeWeightAdditive, binding = this.binding; + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + if (weight < 1) { + const originalValueOffset = stride * this._origIndex; + this._mixBufferRegion( + buffer, + offset, + originalValueOffset, + 1 - weight, + stride + ); + } + if (weightAdditive > 0) { + this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride); + } + for (let i = stride, e = stride + stride; i !== e; ++i) { + if (buffer[i] !== buffer[i + stride]) { + binding.setValue(buffer, offset); + break; + } + } + } + // remember the state of the bound property and copy it to both accus + saveOriginalState() { + const binding = this.binding; + const buffer = this.buffer, stride = this.valueSize, originalValueOffset = stride * this._origIndex; + binding.getValue(buffer, originalValueOffset); + for (let i = stride, e = originalValueOffset; i !== e; ++i) { + buffer[i] = buffer[originalValueOffset + i % stride]; + } + this._setIdentity(); + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + } + // apply the state previously taken via 'saveOriginalState' to the binding + restoreOriginalState() { + const originalValueOffset = this.valueSize * 3; + this.binding.setValue(this.buffer, originalValueOffset); + } + _setAdditiveIdentityNumeric() { + const startIndex = this._addIndex * this.valueSize; + const endIndex = startIndex + this.valueSize; + for (let i = startIndex; i < endIndex; i++) { + this.buffer[i] = 0; + } + } + _setAdditiveIdentityQuaternion() { + this._setAdditiveIdentityNumeric(); + this.buffer[this._addIndex * this.valueSize + 3] = 1; + } + _setAdditiveIdentityOther() { + const startIndex = this._origIndex * this.valueSize; + const targetIndex = this._addIndex * this.valueSize; + for (let i = 0; i < this.valueSize; i++) { + this.buffer[targetIndex + i] = this.buffer[startIndex + i]; + } + } + // mix functions + _select(buffer, dstOffset, srcOffset, t, stride) { + if (t >= 0.5) { + for (let i = 0; i !== stride; ++i) { + buffer[dstOffset + i] = buffer[srcOffset + i]; + } + } + } + _slerp(buffer, dstOffset, srcOffset, t) { + Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t); + } + _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) { + const workOffset = this._workIndex * stride; + Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); + Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t); + } + _lerp(buffer, dstOffset, srcOffset, t, stride) { + const s = 1 - t; + for (let i = 0; i !== stride; ++i) { + const j = dstOffset + i; + buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t; + } + } + _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) { + for (let i = 0; i !== stride; ++i) { + const j = dstOffset + i; + buffer[j] = buffer[j] + buffer[srcOffset + i] * t; + } + } + }; + var _RESERVED_CHARS_RE = "\\[\\]\\.:\\/"; + var _reservedRe = new RegExp("[" + _RESERVED_CHARS_RE + "]", "g"); + var _wordChar = "[^" + _RESERVED_CHARS_RE + "]"; + var _wordCharOrDot = "[^" + _RESERVED_CHARS_RE.replace("\\.", "") + "]"; + var _directoryRe = /* @__PURE__ */ /((?:WC+[\/:])*)/.source.replace("WC", _wordChar); + var _nodeRe = /* @__PURE__ */ /(WCOD+)?/.source.replace("WCOD", _wordCharOrDot); + var _objectRe = /* @__PURE__ */ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC", _wordChar); + var _propertyRe = /* @__PURE__ */ /\.(WC+)(?:\[(.+)\])?/.source.replace("WC", _wordChar); + var _trackRe = new RegExp( + "^" + _directoryRe + _nodeRe + _objectRe + _propertyRe + "$" + ); + var _supportedObjectNames = ["material", "materials", "bones", "map"]; + var Composite = class { + constructor(targetGroup, path, optionalParsedPath) { + const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path); + this._targetGroup = targetGroup; + this._bindings = targetGroup.subscribe_(path, parsedPath); + } + getValue(array, offset) { + this.bind(); + const firstValidIndex = this._targetGroup.nCachedObjects_, binding = this._bindings[firstValidIndex]; + if (binding !== void 0) binding.getValue(array, offset); + } + setValue(array, offset) { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) { + bindings[i].setValue(array, offset); + } + } + bind() { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) { + bindings[i].bind(); + } + } + unbind() { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) { + bindings[i].unbind(); + } + } + }; + var PropertyBinding = class _PropertyBinding { + constructor(rootNode, path, parsedPath) { + this.path = path; + this.parsedPath = parsedPath || _PropertyBinding.parseTrackName(path); + this.node = _PropertyBinding.findNode(rootNode, this.parsedPath.nodeName); + this.rootNode = rootNode; + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + } + static create(root, path, parsedPath) { + if (!(root && root.isAnimationObjectGroup)) { + return new _PropertyBinding(root, path, parsedPath); + } else { + return new _PropertyBinding.Composite(root, path, parsedPath); + } + } + /** + * Replaces spaces with underscores and removes unsupported characters from + * node names, to ensure compatibility with parseTrackName(). + * + * @param {string} name Node name to be sanitized. + * @return {string} + */ + static sanitizeNodeName(name) { + return name.replace(/\s/g, "_").replace(_reservedRe, ""); + } + static parseTrackName(trackName) { + const matches = _trackRe.exec(trackName); + if (matches === null) { + throw new Error("PropertyBinding: Cannot parse trackName: " + trackName); + } + const results = { + // directoryName: matches[ 1 ], // (tschw) currently unused + nodeName: matches[2], + objectName: matches[3], + objectIndex: matches[4], + propertyName: matches[5], + // required + propertyIndex: matches[6] + }; + const lastDot = results.nodeName && results.nodeName.lastIndexOf("."); + if (lastDot !== void 0 && lastDot !== -1) { + const objectName = results.nodeName.substring(lastDot + 1); + if (_supportedObjectNames.indexOf(objectName) !== -1) { + results.nodeName = results.nodeName.substring(0, lastDot); + results.objectName = objectName; + } + } + if (results.propertyName === null || results.propertyName.length === 0) { + throw new Error("PropertyBinding: can not parse propertyName from trackName: " + trackName); + } + return results; + } + static findNode(root, nodeName) { + if (nodeName === void 0 || nodeName === "" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) { + return root; + } + if (root.skeleton) { + const bone = root.skeleton.getBoneByName(nodeName); + if (bone !== void 0) { + return bone; + } + } + if (root.children) { + const searchNodeSubtree = function(children) { + for (let i = 0; i < children.length; i++) { + const childNode = children[i]; + if (childNode.name === nodeName || childNode.uuid === nodeName) { + return childNode; + } + const result = searchNodeSubtree(childNode.children); + if (result) return result; + } + return null; + }; + const subTreeNode = searchNodeSubtree(root.children); + if (subTreeNode) { + return subTreeNode; + } + } + return null; + } + // these are used to "bind" a nonexistent property + _getValue_unavailable() { + } + _setValue_unavailable() { + } + // Getters + _getValue_direct(buffer, offset) { + buffer[offset] = this.targetObject[this.propertyName]; + } + _getValue_array(buffer, offset) { + const source = this.resolvedProperty; + for (let i = 0, n = source.length; i !== n; ++i) { + buffer[offset++] = source[i]; + } + } + _getValue_arrayElement(buffer, offset) { + buffer[offset] = this.resolvedProperty[this.propertyIndex]; + } + _getValue_toArray(buffer, offset) { + this.resolvedProperty.toArray(buffer, offset); + } + // Direct + _setValue_direct(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + } + _setValue_direct_setNeedsUpdate(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + this.targetObject.needsUpdate = true; + } + _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + this.targetObject.matrixWorldNeedsUpdate = true; + } + // EntireArray + _setValue_array(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n = dest.length; i !== n; ++i) { + dest[i] = buffer[offset++]; + } + } + _setValue_array_setNeedsUpdate(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n = dest.length; i !== n; ++i) { + dest[i] = buffer[offset++]; + } + this.targetObject.needsUpdate = true; + } + _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n = dest.length; i !== n; ++i) { + dest[i] = buffer[offset++]; + } + this.targetObject.matrixWorldNeedsUpdate = true; + } + // ArrayElement + _setValue_arrayElement(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + } + _setValue_arrayElement_setNeedsUpdate(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + this.targetObject.needsUpdate = true; + } + _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + this.targetObject.matrixWorldNeedsUpdate = true; + } + // HasToFromArray + _setValue_fromArray(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + } + _setValue_fromArray_setNeedsUpdate(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + this.targetObject.needsUpdate = true; + } + _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + this.targetObject.matrixWorldNeedsUpdate = true; + } + _getValue_unbound(targetArray, offset) { + this.bind(); + this.getValue(targetArray, offset); + } + _setValue_unbound(sourceArray, offset) { + this.bind(); + this.setValue(sourceArray, offset); + } + // create getter / setter pair for a property in the scene graph + bind() { + let targetObject = this.node; + const parsedPath = this.parsedPath; + const objectName = parsedPath.objectName; + const propertyName = parsedPath.propertyName; + let propertyIndex = parsedPath.propertyIndex; + if (!targetObject) { + targetObject = _PropertyBinding.findNode(this.rootNode, parsedPath.nodeName); + this.node = targetObject; + } + this.getValue = this._getValue_unavailable; + this.setValue = this._setValue_unavailable; + if (!targetObject) { + console.warn("THREE.PropertyBinding: No target node found for track: " + this.path + "."); + return; + } + if (objectName) { + let objectIndex = parsedPath.objectIndex; + switch (objectName) { + case "materials": + if (!targetObject.material) { + console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this); + return; + } + if (!targetObject.material.materials) { + console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.", this); + return; + } + targetObject = targetObject.material.materials; + break; + case "bones": + if (!targetObject.skeleton) { + console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.", this); + return; + } + targetObject = targetObject.skeleton.bones; + for (let i = 0; i < targetObject.length; i++) { + if (targetObject[i].name === objectIndex) { + objectIndex = i; + break; + } + } + break; + case "map": + if ("map" in targetObject) { + targetObject = targetObject.map; + break; + } + if (!targetObject.material) { + console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this); + return; + } + if (!targetObject.material.map) { + console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.", this); + return; + } + targetObject = targetObject.material.map; + break; + default: + if (targetObject[objectName] === void 0) { + console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.", this); + return; + } + targetObject = targetObject[objectName]; + } + if (objectIndex !== void 0) { + if (targetObject[objectIndex] === void 0) { + console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.", this, targetObject); + return; + } + targetObject = targetObject[objectIndex]; + } + } + const nodeProperty = targetObject[propertyName]; + if (nodeProperty === void 0) { + const nodeName = parsedPath.nodeName; + console.error("THREE.PropertyBinding: Trying to update property for track: " + nodeName + "." + propertyName + " but it wasn't found.", targetObject); + return; + } + let versioning = this.Versioning.None; + this.targetObject = targetObject; + if (targetObject.needsUpdate !== void 0) { + versioning = this.Versioning.NeedsUpdate; + } else if (targetObject.matrixWorldNeedsUpdate !== void 0) { + versioning = this.Versioning.MatrixWorldNeedsUpdate; + } + let bindingType = this.BindingType.Direct; + if (propertyIndex !== void 0) { + if (propertyName === "morphTargetInfluences") { + if (!targetObject.geometry) { + console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.", this); + return; + } + if (!targetObject.geometry.morphAttributes) { + console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.", this); + return; + } + if (targetObject.morphTargetDictionary[propertyIndex] !== void 0) { + propertyIndex = targetObject.morphTargetDictionary[propertyIndex]; + } + } + bindingType = this.BindingType.ArrayElement; + this.resolvedProperty = nodeProperty; + this.propertyIndex = propertyIndex; + } else if (nodeProperty.fromArray !== void 0 && nodeProperty.toArray !== void 0) { + bindingType = this.BindingType.HasFromToArray; + this.resolvedProperty = nodeProperty; + } else if (Array.isArray(nodeProperty)) { + bindingType = this.BindingType.EntireArray; + this.resolvedProperty = nodeProperty; + } else { + this.propertyName = propertyName; + } + this.getValue = this.GetterByBindingType[bindingType]; + this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning]; + } + unbind() { + this.node = null; + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + } + }; + PropertyBinding.Composite = Composite; + PropertyBinding.prototype.BindingType = { + Direct: 0, + EntireArray: 1, + ArrayElement: 2, + HasFromToArray: 3 + }; + PropertyBinding.prototype.Versioning = { + None: 0, + NeedsUpdate: 1, + MatrixWorldNeedsUpdate: 2 + }; + PropertyBinding.prototype.GetterByBindingType = [ + PropertyBinding.prototype._getValue_direct, + PropertyBinding.prototype._getValue_array, + PropertyBinding.prototype._getValue_arrayElement, + PropertyBinding.prototype._getValue_toArray + ]; + PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [ + [ + // Direct + PropertyBinding.prototype._setValue_direct, + PropertyBinding.prototype._setValue_direct_setNeedsUpdate, + PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate + ], + [ + // EntireArray + PropertyBinding.prototype._setValue_array, + PropertyBinding.prototype._setValue_array_setNeedsUpdate, + PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate + ], + [ + // ArrayElement + PropertyBinding.prototype._setValue_arrayElement, + PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, + PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate + ], + [ + // HasToFromArray + PropertyBinding.prototype._setValue_fromArray, + PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, + PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate + ] + ]; + var AnimationObjectGroup = class { + constructor() { + this.isAnimationObjectGroup = true; + this.uuid = generateUUID(); + this._objects = Array.prototype.slice.call(arguments); + this.nCachedObjects_ = 0; + const indices = {}; + this._indicesByUUID = indices; + for (let i = 0, n = arguments.length; i !== n; ++i) { + indices[arguments[i].uuid] = i; + } + this._paths = []; + this._parsedPaths = []; + this._bindings = []; + this._bindingsIndicesByPath = {}; + const scope = this; + this.stats = { + objects: { + get total() { + return scope._objects.length; + }, + get inUse() { + return this.total - scope.nCachedObjects_; + } + }, + get bindingsPerObject() { + return scope._bindings.length; + } + }; + } + add() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, paths = this._paths, parsedPaths = this._parsedPaths, bindings = this._bindings, nBindings = bindings.length; + let knownObject = void 0, nObjects = objects.length, nCachedObjects = this.nCachedObjects_; + for (let i = 0, n = arguments.length; i !== n; ++i) { + const object = arguments[i], uuid = object.uuid; + let index = indicesByUUID[uuid]; + if (index === void 0) { + index = nObjects++; + indicesByUUID[uuid] = index; + objects.push(object); + for (let j = 0, m = nBindings; j !== m; ++j) { + bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j])); + } + } else if (index < nCachedObjects) { + knownObject = objects[index]; + const firstActiveIndex = --nCachedObjects, lastCachedObject = objects[firstActiveIndex]; + indicesByUUID[lastCachedObject.uuid] = index; + objects[index] = lastCachedObject; + indicesByUUID[uuid] = firstActiveIndex; + objects[firstActiveIndex] = object; + for (let j = 0, m = nBindings; j !== m; ++j) { + const bindingsForPath = bindings[j], lastCached = bindingsForPath[firstActiveIndex]; + let binding = bindingsForPath[index]; + bindingsForPath[index] = lastCached; + if (binding === void 0) { + binding = new PropertyBinding(object, paths[j], parsedPaths[j]); + } + bindingsForPath[firstActiveIndex] = binding; + } + } else if (objects[index] !== knownObject) { + console.error("THREE.AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes."); + } + } + this.nCachedObjects_ = nCachedObjects; + } + remove() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, bindings = this._bindings, nBindings = bindings.length; + let nCachedObjects = this.nCachedObjects_; + for (let i = 0, n = arguments.length; i !== n; ++i) { + const object = arguments[i], uuid = object.uuid, index = indicesByUUID[uuid]; + if (index !== void 0 && index >= nCachedObjects) { + const lastCachedIndex = nCachedObjects++, firstActiveObject = objects[lastCachedIndex]; + indicesByUUID[firstActiveObject.uuid] = index; + objects[index] = firstActiveObject; + indicesByUUID[uuid] = lastCachedIndex; + objects[lastCachedIndex] = object; + for (let j = 0, m = nBindings; j !== m; ++j) { + const bindingsForPath = bindings[j], firstActive = bindingsForPath[lastCachedIndex], binding = bindingsForPath[index]; + bindingsForPath[index] = firstActive; + bindingsForPath[lastCachedIndex] = binding; + } + } + } + this.nCachedObjects_ = nCachedObjects; + } + // remove & forget + uncache() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, bindings = this._bindings, nBindings = bindings.length; + let nCachedObjects = this.nCachedObjects_, nObjects = objects.length; + for (let i = 0, n = arguments.length; i !== n; ++i) { + const object = arguments[i], uuid = object.uuid, index = indicesByUUID[uuid]; + if (index !== void 0) { + delete indicesByUUID[uuid]; + if (index < nCachedObjects) { + const firstActiveIndex = --nCachedObjects, lastCachedObject = objects[firstActiveIndex], lastIndex = --nObjects, lastObject = objects[lastIndex]; + indicesByUUID[lastCachedObject.uuid] = index; + objects[index] = lastCachedObject; + indicesByUUID[lastObject.uuid] = firstActiveIndex; + objects[firstActiveIndex] = lastObject; + objects.pop(); + for (let j = 0, m = nBindings; j !== m; ++j) { + const bindingsForPath = bindings[j], lastCached = bindingsForPath[firstActiveIndex], last = bindingsForPath[lastIndex]; + bindingsForPath[index] = lastCached; + bindingsForPath[firstActiveIndex] = last; + bindingsForPath.pop(); + } + } else { + const lastIndex = --nObjects, lastObject = objects[lastIndex]; + if (lastIndex > 0) { + indicesByUUID[lastObject.uuid] = index; + } + objects[index] = lastObject; + objects.pop(); + for (let j = 0, m = nBindings; j !== m; ++j) { + const bindingsForPath = bindings[j]; + bindingsForPath[index] = bindingsForPath[lastIndex]; + bindingsForPath.pop(); + } + } + } + } + this.nCachedObjects_ = nCachedObjects; + } + // Internal interface used by befriended PropertyBinding.Composite: + subscribe_(path, parsedPath) { + const indicesByPath = this._bindingsIndicesByPath; + let index = indicesByPath[path]; + const bindings = this._bindings; + if (index !== void 0) return bindings[index]; + const paths = this._paths, parsedPaths = this._parsedPaths, objects = this._objects, nObjects = objects.length, nCachedObjects = this.nCachedObjects_, bindingsForPath = new Array(nObjects); + index = bindings.length; + indicesByPath[path] = index; + paths.push(path); + parsedPaths.push(parsedPath); + bindings.push(bindingsForPath); + for (let i = nCachedObjects, n = objects.length; i !== n; ++i) { + const object = objects[i]; + bindingsForPath[i] = new PropertyBinding(object, path, parsedPath); + } + return bindingsForPath; + } + unsubscribe_(path) { + const indicesByPath = this._bindingsIndicesByPath, index = indicesByPath[path]; + if (index !== void 0) { + const paths = this._paths, parsedPaths = this._parsedPaths, bindings = this._bindings, lastBindingsIndex = bindings.length - 1, lastBindings = bindings[lastBindingsIndex], lastBindingsPath = path[lastBindingsIndex]; + indicesByPath[lastBindingsPath] = index; + bindings[index] = lastBindings; + bindings.pop(); + parsedPaths[index] = parsedPaths[lastBindingsIndex]; + parsedPaths.pop(); + paths[index] = paths[lastBindingsIndex]; + paths.pop(); + } + } + }; + var AnimationAction = class { + constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) { + this._mixer = mixer; + this._clip = clip; + this._localRoot = localRoot; + this.blendMode = blendMode; + const tracks = clip.tracks, nTracks = tracks.length, interpolants = new Array(nTracks); + const interpolantSettings = { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + }; + for (let i = 0; i !== nTracks; ++i) { + const interpolant = tracks[i].createInterpolant(null); + interpolants[i] = interpolant; + interpolant.settings = interpolantSettings; + } + this._interpolantSettings = interpolantSettings; + this._interpolants = interpolants; + this._propertyBindings = new Array(nTracks); + this._cacheIndex = null; + this._byClipCacheIndex = null; + this._timeScaleInterpolant = null; + this._weightInterpolant = null; + this.loop = LoopRepeat; + this._loopCount = -1; + this._startTime = null; + this.time = 0; + this.timeScale = 1; + this._effectiveTimeScale = 1; + this.weight = 1; + this._effectiveWeight = 1; + this.repetitions = Infinity; + this.paused = false; + this.enabled = true; + this.clampWhenFinished = false; + this.zeroSlopeAtStart = true; + this.zeroSlopeAtEnd = true; + } + // State & Scheduling + play() { + this._mixer._activateAction(this); + return this; + } + stop() { + this._mixer._deactivateAction(this); + return this.reset(); + } + reset() { + this.paused = false; + this.enabled = true; + this.time = 0; + this._loopCount = -1; + this._startTime = null; + return this.stopFading().stopWarping(); + } + isRunning() { + return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this); + } + // return true when play has been called + isScheduled() { + return this._mixer._isActiveAction(this); + } + startAt(time) { + this._startTime = time; + return this; + } + setLoop(mode, repetitions) { + this.loop = mode; + this.repetitions = repetitions; + return this; + } + // Weight + // set the weight stopping any scheduled fading + // although .enabled = false yields an effective weight of zero, this + // method does *not* change .enabled, because it would be confusing + setEffectiveWeight(weight) { + this.weight = weight; + this._effectiveWeight = this.enabled ? weight : 0; + return this.stopFading(); + } + // return the weight considering fading and .enabled + getEffectiveWeight() { + return this._effectiveWeight; + } + fadeIn(duration) { + return this._scheduleFading(duration, 0, 1); + } + fadeOut(duration) { + return this._scheduleFading(duration, 1, 0); + } + crossFadeFrom(fadeOutAction, duration, warp) { + fadeOutAction.fadeOut(duration); + this.fadeIn(duration); + if (warp) { + const fadeInDuration = this._clip.duration, fadeOutDuration = fadeOutAction._clip.duration, startEndRatio = fadeOutDuration / fadeInDuration, endStartRatio = fadeInDuration / fadeOutDuration; + fadeOutAction.warp(1, startEndRatio, duration); + this.warp(endStartRatio, 1, duration); + } + return this; + } + crossFadeTo(fadeInAction, duration, warp) { + return fadeInAction.crossFadeFrom(this, duration, warp); + } + stopFading() { + const weightInterpolant = this._weightInterpolant; + if (weightInterpolant !== null) { + this._weightInterpolant = null; + this._mixer._takeBackControlInterpolant(weightInterpolant); + } + return this; + } + // Time Scale Control + // set the time scale stopping any scheduled warping + // although .paused = true yields an effective time scale of zero, this + // method does *not* change .paused, because it would be confusing + setEffectiveTimeScale(timeScale) { + this.timeScale = timeScale; + this._effectiveTimeScale = this.paused ? 0 : timeScale; + return this.stopWarping(); + } + // return the time scale considering warping and .paused + getEffectiveTimeScale() { + return this._effectiveTimeScale; + } + setDuration(duration) { + this.timeScale = this._clip.duration / duration; + return this.stopWarping(); + } + syncWith(action) { + this.time = action.time; + this.timeScale = action.timeScale; + return this.stopWarping(); + } + halt(duration) { + return this.warp(this._effectiveTimeScale, 0, duration); + } + warp(startTimeScale, endTimeScale, duration) { + const mixer = this._mixer, now2 = mixer.time, timeScale = this.timeScale; + let interpolant = this._timeScaleInterpolant; + if (interpolant === null) { + interpolant = mixer._lendControlInterpolant(); + this._timeScaleInterpolant = interpolant; + } + const times = interpolant.parameterPositions, values = interpolant.sampleValues; + times[0] = now2; + times[1] = now2 + duration; + values[0] = startTimeScale / timeScale; + values[1] = endTimeScale / timeScale; + return this; + } + stopWarping() { + const timeScaleInterpolant = this._timeScaleInterpolant; + if (timeScaleInterpolant !== null) { + this._timeScaleInterpolant = null; + this._mixer._takeBackControlInterpolant(timeScaleInterpolant); + } + return this; + } + // Object Accessors + getMixer() { + return this._mixer; + } + getClip() { + return this._clip; + } + getRoot() { + return this._localRoot || this._mixer._root; + } + // Interna + _update(time, deltaTime, timeDirection, accuIndex) { + if (!this.enabled) { + this._updateWeight(time); + return; + } + const startTime = this._startTime; + if (startTime !== null) { + const timeRunning = (time - startTime) * timeDirection; + if (timeRunning < 0 || timeDirection === 0) { + deltaTime = 0; + } else { + this._startTime = null; + deltaTime = timeDirection * timeRunning; + } + } + deltaTime *= this._updateTimeScale(time); + const clipTime = this._updateTime(deltaTime); + const weight = this._updateWeight(time); + if (weight > 0) { + const interpolants = this._interpolants; + const propertyMixers = this._propertyBindings; + switch (this.blendMode) { + case AdditiveAnimationBlendMode: + for (let j = 0, m = interpolants.length; j !== m; ++j) { + interpolants[j].evaluate(clipTime); + propertyMixers[j].accumulateAdditive(weight); + } + break; + case NormalAnimationBlendMode: + default: + for (let j = 0, m = interpolants.length; j !== m; ++j) { + interpolants[j].evaluate(clipTime); + propertyMixers[j].accumulate(accuIndex, weight); + } + } + } + } + _updateWeight(time) { + let weight = 0; + if (this.enabled) { + weight = this.weight; + const interpolant = this._weightInterpolant; + if (interpolant !== null) { + const interpolantValue = interpolant.evaluate(time)[0]; + weight *= interpolantValue; + if (time > interpolant.parameterPositions[1]) { + this.stopFading(); + if (interpolantValue === 0) { + this.enabled = false; + } + } + } + } + this._effectiveWeight = weight; + return weight; + } + _updateTimeScale(time) { + let timeScale = 0; + if (!this.paused) { + timeScale = this.timeScale; + const interpolant = this._timeScaleInterpolant; + if (interpolant !== null) { + const interpolantValue = interpolant.evaluate(time)[0]; + timeScale *= interpolantValue; + if (time > interpolant.parameterPositions[1]) { + this.stopWarping(); + if (timeScale === 0) { + this.paused = true; + } else { + this.timeScale = timeScale; + } + } + } + } + this._effectiveTimeScale = timeScale; + return timeScale; + } + _updateTime(deltaTime) { + const duration = this._clip.duration; + const loop = this.loop; + let time = this.time + deltaTime; + let loopCount = this._loopCount; + const pingPong = loop === LoopPingPong; + if (deltaTime === 0) { + if (loopCount === -1) return time; + return pingPong && (loopCount & 1) === 1 ? duration - time : time; + } + if (loop === LoopOnce) { + if (loopCount === -1) { + this._loopCount = 0; + this._setEndings(true, true, false); + } + handle_stop: { + if (time >= duration) { + time = duration; + } else if (time < 0) { + time = 0; + } else { + this.time = time; + break handle_stop; + } + if (this.clampWhenFinished) this.paused = true; + else this.enabled = false; + this.time = time; + this._mixer.dispatchEvent({ + type: "finished", + action: this, + direction: deltaTime < 0 ? -1 : 1 + }); + } + } else { + if (loopCount === -1) { + if (deltaTime >= 0) { + loopCount = 0; + this._setEndings(true, this.repetitions === 0, pingPong); + } else { + this._setEndings(this.repetitions === 0, true, pingPong); + } + } + if (time >= duration || time < 0) { + const loopDelta = Math.floor(time / duration); + time -= duration * loopDelta; + loopCount += Math.abs(loopDelta); + const pending = this.repetitions - loopCount; + if (pending <= 0) { + if (this.clampWhenFinished) this.paused = true; + else this.enabled = false; + time = deltaTime > 0 ? duration : 0; + this.time = time; + this._mixer.dispatchEvent({ + type: "finished", + action: this, + direction: deltaTime > 0 ? 1 : -1 + }); + } else { + if (pending === 1) { + const atStart = deltaTime < 0; + this._setEndings(atStart, !atStart, pingPong); + } else { + this._setEndings(false, false, pingPong); + } + this._loopCount = loopCount; + this.time = time; + this._mixer.dispatchEvent({ + type: "loop", + action: this, + loopDelta + }); + } + } else { + this.time = time; + } + if (pingPong && (loopCount & 1) === 1) { + return duration - time; + } + } + return time; + } + _setEndings(atStart, atEnd, pingPong) { + const settings = this._interpolantSettings; + if (pingPong) { + settings.endingStart = ZeroSlopeEnding; + settings.endingEnd = ZeroSlopeEnding; + } else { + if (atStart) { + settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding; + } else { + settings.endingStart = WrapAroundEnding; + } + if (atEnd) { + settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding; + } else { + settings.endingEnd = WrapAroundEnding; + } + } + } + _scheduleFading(duration, weightNow, weightThen) { + const mixer = this._mixer, now2 = mixer.time; + let interpolant = this._weightInterpolant; + if (interpolant === null) { + interpolant = mixer._lendControlInterpolant(); + this._weightInterpolant = interpolant; + } + const times = interpolant.parameterPositions, values = interpolant.sampleValues; + times[0] = now2; + values[0] = weightNow; + times[1] = now2 + duration; + values[1] = weightThen; + return this; + } + }; + var _controlInterpolantsResultBuffer = new Float32Array(1); + var AnimationMixer = class extends EventDispatcher { + constructor(root) { + super(); + this._root = root; + this._initMemoryManager(); + this._accuIndex = 0; + this.time = 0; + this.timeScale = 1; + } + _bindAction(action, prototypeAction) { + const root = action._localRoot || this._root, tracks = action._clip.tracks, nTracks = tracks.length, bindings = action._propertyBindings, interpolants = action._interpolants, rootUuid = root.uuid, bindingsByRoot = this._bindingsByRootAndName; + let bindingsByName = bindingsByRoot[rootUuid]; + if (bindingsByName === void 0) { + bindingsByName = {}; + bindingsByRoot[rootUuid] = bindingsByName; + } + for (let i = 0; i !== nTracks; ++i) { + const track = tracks[i], trackName = track.name; + let binding = bindingsByName[trackName]; + if (binding !== void 0) { + ++binding.referenceCount; + bindings[i] = binding; + } else { + binding = bindings[i]; + if (binding !== void 0) { + if (binding._cacheIndex === null) { + ++binding.referenceCount; + this._addInactiveBinding(binding, rootUuid, trackName); + } + continue; + } + const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath; + binding = new PropertyMixer( + PropertyBinding.create(root, trackName, path), + track.ValueTypeName, + track.getValueSize() + ); + ++binding.referenceCount; + this._addInactiveBinding(binding, rootUuid, trackName); + bindings[i] = binding; + } + interpolants[i].resultBuffer = binding.buffer; + } + } + _activateAction(action) { + if (!this._isActiveAction(action)) { + if (action._cacheIndex === null) { + const rootUuid = (action._localRoot || this._root).uuid, clipUuid = action._clip.uuid, actionsForClip = this._actionsByClip[clipUuid]; + this._bindAction( + action, + actionsForClip && actionsForClip.knownActions[0] + ); + this._addInactiveAction(action, clipUuid, rootUuid); + } + const bindings = action._propertyBindings; + for (let i = 0, n = bindings.length; i !== n; ++i) { + const binding = bindings[i]; + if (binding.useCount++ === 0) { + this._lendBinding(binding); + binding.saveOriginalState(); + } + } + this._lendAction(action); + } + } + _deactivateAction(action) { + if (this._isActiveAction(action)) { + const bindings = action._propertyBindings; + for (let i = 0, n = bindings.length; i !== n; ++i) { + const binding = bindings[i]; + if (--binding.useCount === 0) { + binding.restoreOriginalState(); + this._takeBackBinding(binding); + } + } + this._takeBackAction(action); + } + } + // Memory manager + _initMemoryManager() { + this._actions = []; + this._nActiveActions = 0; + this._actionsByClip = {}; + this._bindings = []; + this._nActiveBindings = 0; + this._bindingsByRootAndName = {}; + this._controlInterpolants = []; + this._nActiveControlInterpolants = 0; + const scope = this; + this.stats = { + actions: { + get total() { + return scope._actions.length; + }, + get inUse() { + return scope._nActiveActions; + } + }, + bindings: { + get total() { + return scope._bindings.length; + }, + get inUse() { + return scope._nActiveBindings; + } + }, + controlInterpolants: { + get total() { + return scope._controlInterpolants.length; + }, + get inUse() { + return scope._nActiveControlInterpolants; + } + } + }; + } + // Memory management for AnimationAction objects + _isActiveAction(action) { + const index = action._cacheIndex; + return index !== null && index < this._nActiveActions; + } + _addInactiveAction(action, clipUuid, rootUuid) { + const actions = this._actions, actionsByClip = this._actionsByClip; + let actionsForClip = actionsByClip[clipUuid]; + if (actionsForClip === void 0) { + actionsForClip = { + knownActions: [action], + actionByRoot: {} + }; + action._byClipCacheIndex = 0; + actionsByClip[clipUuid] = actionsForClip; + } else { + const knownActions = actionsForClip.knownActions; + action._byClipCacheIndex = knownActions.length; + knownActions.push(action); + } + action._cacheIndex = actions.length; + actions.push(action); + actionsForClip.actionByRoot[rootUuid] = action; + } + _removeInactiveAction(action) { + const actions = this._actions, lastInactiveAction = actions[actions.length - 1], cacheIndex = action._cacheIndex; + lastInactiveAction._cacheIndex = cacheIndex; + actions[cacheIndex] = lastInactiveAction; + actions.pop(); + action._cacheIndex = null; + const clipUuid = action._clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[clipUuid], knownActionsForClip = actionsForClip.knownActions, lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1], byClipCacheIndex = action._byClipCacheIndex; + lastKnownAction._byClipCacheIndex = byClipCacheIndex; + knownActionsForClip[byClipCacheIndex] = lastKnownAction; + knownActionsForClip.pop(); + action._byClipCacheIndex = null; + const actionByRoot = actionsForClip.actionByRoot, rootUuid = (action._localRoot || this._root).uuid; + delete actionByRoot[rootUuid]; + if (knownActionsForClip.length === 0) { + delete actionsByClip[clipUuid]; + } + this._removeInactiveBindingsForAction(action); + } + _removeInactiveBindingsForAction(action) { + const bindings = action._propertyBindings; + for (let i = 0, n = bindings.length; i !== n; ++i) { + const binding = bindings[i]; + if (--binding.referenceCount === 0) { + this._removeInactiveBinding(binding); + } + } + } + _lendAction(action) { + const actions = this._actions, prevIndex = action._cacheIndex, lastActiveIndex = this._nActiveActions++, firstInactiveAction = actions[lastActiveIndex]; + action._cacheIndex = lastActiveIndex; + actions[lastActiveIndex] = action; + firstInactiveAction._cacheIndex = prevIndex; + actions[prevIndex] = firstInactiveAction; + } + _takeBackAction(action) { + const actions = this._actions, prevIndex = action._cacheIndex, firstInactiveIndex = --this._nActiveActions, lastActiveAction = actions[firstInactiveIndex]; + action._cacheIndex = firstInactiveIndex; + actions[firstInactiveIndex] = action; + lastActiveAction._cacheIndex = prevIndex; + actions[prevIndex] = lastActiveAction; + } + // Memory management for PropertyMixer objects + _addInactiveBinding(binding, rootUuid, trackName) { + const bindingsByRoot = this._bindingsByRootAndName, bindings = this._bindings; + let bindingByName = bindingsByRoot[rootUuid]; + if (bindingByName === void 0) { + bindingByName = {}; + bindingsByRoot[rootUuid] = bindingByName; + } + bindingByName[trackName] = binding; + binding._cacheIndex = bindings.length; + bindings.push(binding); + } + _removeInactiveBinding(binding) { + const bindings = this._bindings, propBinding = binding.binding, rootUuid = propBinding.rootNode.uuid, trackName = propBinding.path, bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[rootUuid], lastInactiveBinding = bindings[bindings.length - 1], cacheIndex = binding._cacheIndex; + lastInactiveBinding._cacheIndex = cacheIndex; + bindings[cacheIndex] = lastInactiveBinding; + bindings.pop(); + delete bindingByName[trackName]; + if (Object.keys(bindingByName).length === 0) { + delete bindingsByRoot[rootUuid]; + } + } + _lendBinding(binding) { + const bindings = this._bindings, prevIndex = binding._cacheIndex, lastActiveIndex = this._nActiveBindings++, firstInactiveBinding = bindings[lastActiveIndex]; + binding._cacheIndex = lastActiveIndex; + bindings[lastActiveIndex] = binding; + firstInactiveBinding._cacheIndex = prevIndex; + bindings[prevIndex] = firstInactiveBinding; + } + _takeBackBinding(binding) { + const bindings = this._bindings, prevIndex = binding._cacheIndex, firstInactiveIndex = --this._nActiveBindings, lastActiveBinding = bindings[firstInactiveIndex]; + binding._cacheIndex = firstInactiveIndex; + bindings[firstInactiveIndex] = binding; + lastActiveBinding._cacheIndex = prevIndex; + bindings[prevIndex] = lastActiveBinding; + } + // Memory management of Interpolants for weight and time scale + _lendControlInterpolant() { + const interpolants = this._controlInterpolants, lastActiveIndex = this._nActiveControlInterpolants++; + let interpolant = interpolants[lastActiveIndex]; + if (interpolant === void 0) { + interpolant = new LinearInterpolant( + new Float32Array(2), + new Float32Array(2), + 1, + _controlInterpolantsResultBuffer + ); + interpolant.__cacheIndex = lastActiveIndex; + interpolants[lastActiveIndex] = interpolant; + } + return interpolant; + } + _takeBackControlInterpolant(interpolant) { + const interpolants = this._controlInterpolants, prevIndex = interpolant.__cacheIndex, firstInactiveIndex = --this._nActiveControlInterpolants, lastActiveInterpolant = interpolants[firstInactiveIndex]; + interpolant.__cacheIndex = firstInactiveIndex; + interpolants[firstInactiveIndex] = interpolant; + lastActiveInterpolant.__cacheIndex = prevIndex; + interpolants[prevIndex] = lastActiveInterpolant; + } + // return an action for a clip optionally using a custom root target + // object (this method allocates a lot of dynamic memory in case a + // previously unknown clip/root combination is specified) + clipAction(clip, optionalRoot, blendMode) { + const root = optionalRoot || this._root, rootUuid = root.uuid; + let clipObject = typeof clip === "string" ? AnimationClip.findByName(root, clip) : clip; + const clipUuid = clipObject !== null ? clipObject.uuid : clip; + const actionsForClip = this._actionsByClip[clipUuid]; + let prototypeAction = null; + if (blendMode === void 0) { + if (clipObject !== null) { + blendMode = clipObject.blendMode; + } else { + blendMode = NormalAnimationBlendMode; + } + } + if (actionsForClip !== void 0) { + const existingAction = actionsForClip.actionByRoot[rootUuid]; + if (existingAction !== void 0 && existingAction.blendMode === blendMode) { + return existingAction; + } + prototypeAction = actionsForClip.knownActions[0]; + if (clipObject === null) + clipObject = prototypeAction._clip; + } + if (clipObject === null) return null; + const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode); + this._bindAction(newAction, prototypeAction); + this._addInactiveAction(newAction, clipUuid, rootUuid); + return newAction; + } + // get an existing action + existingAction(clip, optionalRoot) { + const root = optionalRoot || this._root, rootUuid = root.uuid, clipObject = typeof clip === "string" ? AnimationClip.findByName(root, clip) : clip, clipUuid = clipObject ? clipObject.uuid : clip, actionsForClip = this._actionsByClip[clipUuid]; + if (actionsForClip !== void 0) { + return actionsForClip.actionByRoot[rootUuid] || null; + } + return null; + } + // deactivates all previously scheduled actions + stopAllAction() { + const actions = this._actions, nActions = this._nActiveActions; + for (let i = nActions - 1; i >= 0; --i) { + actions[i].stop(); + } + return this; + } + // advance the time and update apply the animation + update(deltaTime) { + deltaTime *= this.timeScale; + const actions = this._actions, nActions = this._nActiveActions, time = this.time += deltaTime, timeDirection = Math.sign(deltaTime), accuIndex = this._accuIndex ^= 1; + for (let i = 0; i !== nActions; ++i) { + const action = actions[i]; + action._update(time, deltaTime, timeDirection, accuIndex); + } + const bindings = this._bindings, nBindings = this._nActiveBindings; + for (let i = 0; i !== nBindings; ++i) { + bindings[i].apply(accuIndex); + } + return this; + } + // Allows you to seek to a specific time in an animation. + setTime(timeInSeconds) { + this.time = 0; + for (let i = 0; i < this._actions.length; i++) { + this._actions[i].time = 0; + } + return this.update(timeInSeconds); + } + // return this mixer's root target object + getRoot() { + return this._root; + } + // free all resources specific to a particular clip + uncacheClip(clip) { + const actions = this._actions, clipUuid = clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[clipUuid]; + if (actionsForClip !== void 0) { + const actionsToRemove = actionsForClip.knownActions; + for (let i = 0, n = actionsToRemove.length; i !== n; ++i) { + const action = actionsToRemove[i]; + this._deactivateAction(action); + const cacheIndex = action._cacheIndex, lastInactiveAction = actions[actions.length - 1]; + action._cacheIndex = null; + action._byClipCacheIndex = null; + lastInactiveAction._cacheIndex = cacheIndex; + actions[cacheIndex] = lastInactiveAction; + actions.pop(); + this._removeInactiveBindingsForAction(action); + } + delete actionsByClip[clipUuid]; + } + } + // free all resources specific to a particular root target object + uncacheRoot(root) { + const rootUuid = root.uuid, actionsByClip = this._actionsByClip; + for (const clipUuid in actionsByClip) { + const actionByRoot = actionsByClip[clipUuid].actionByRoot, action = actionByRoot[rootUuid]; + if (action !== void 0) { + this._deactivateAction(action); + this._removeInactiveAction(action); + } + } + const bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[rootUuid]; + if (bindingByName !== void 0) { + for (const trackName in bindingByName) { + const binding = bindingByName[trackName]; + binding.restoreOriginalState(); + this._removeInactiveBinding(binding); + } + } + } + // remove a targeted clip from the cache + uncacheAction(clip, optionalRoot) { + const action = this.existingAction(clip, optionalRoot); + if (action !== null) { + this._deactivateAction(action); + this._removeInactiveAction(action); + } + } + }; + var Uniform = class _Uniform { + constructor(value) { + this.value = value; + } + clone() { + return new _Uniform(this.value.clone === void 0 ? this.value : this.value.clone()); + } + }; + var _id = 0; + var UniformsGroup = class extends EventDispatcher { + constructor() { + super(); + this.isUniformsGroup = true; + Object.defineProperty(this, "id", { value: _id++ }); + this.name = ""; + this.usage = StaticDrawUsage; + this.uniforms = []; + } + add(uniform) { + this.uniforms.push(uniform); + return this; + } + remove(uniform) { + const index = this.uniforms.indexOf(uniform); + if (index !== -1) this.uniforms.splice(index, 1); + return this; + } + setName(name) { + this.name = name; + return this; + } + setUsage(value) { + this.usage = value; + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + return this; + } + copy(source) { + this.name = source.name; + this.usage = source.usage; + const uniformsSource = source.uniforms; + this.uniforms.length = 0; + for (let i = 0, l = uniformsSource.length; i < l; i++) { + const uniforms = Array.isArray(uniformsSource[i]) ? uniformsSource[i] : [uniformsSource[i]]; + for (let j = 0; j < uniforms.length; j++) { + this.uniforms.push(uniforms[j].clone()); + } + } + return this; + } + clone() { + return new this.constructor().copy(this); + } + }; + var InstancedInterleavedBuffer = class extends InterleavedBuffer { + constructor(array, stride, meshPerAttribute = 1) { + super(array, stride); + this.isInstancedInterleavedBuffer = true; + this.meshPerAttribute = meshPerAttribute; + } + copy(source) { + super.copy(source); + this.meshPerAttribute = source.meshPerAttribute; + return this; + } + clone(data) { + const ib = super.clone(data); + ib.meshPerAttribute = this.meshPerAttribute; + return ib; + } + toJSON(data) { + const json = super.toJSON(data); + json.isInstancedInterleavedBuffer = true; + json.meshPerAttribute = this.meshPerAttribute; + return json; + } + }; + var GLBufferAttribute = class { + constructor(buffer, type, itemSize, elementSize, count) { + this.isGLBufferAttribute = true; + this.name = ""; + this.buffer = buffer; + this.type = type; + this.itemSize = itemSize; + this.elementSize = elementSize; + this.count = count; + this.version = 0; + } + set needsUpdate(value) { + if (value === true) this.version++; + } + setBuffer(buffer) { + this.buffer = buffer; + return this; + } + setType(type, elementSize) { + this.type = type; + this.elementSize = elementSize; + return this; + } + setItemSize(itemSize) { + this.itemSize = itemSize; + return this; + } + setCount(count) { + this.count = count; + return this; + } + }; + var Raycaster = class { + constructor(origin, direction, near = 0, far = Infinity) { + this.ray = new Ray(origin, direction); + this.near = near; + this.far = far; + this.camera = null; + this.layers = new Layers(); + this.params = { + Mesh: {}, + Line: { threshold: 1 }, + LOD: {}, + Points: { threshold: 1 }, + Sprite: {} + }; + } + set(origin, direction) { + this.ray.set(origin, direction); + } + setFromCamera(coords, camera) { + if (camera.isPerspectiveCamera) { + this.ray.origin.setFromMatrixPosition(camera.matrixWorld); + this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize(); + this.camera = camera; + } else if (camera.isOrthographicCamera) { + this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); + this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld); + this.camera = camera; + } else { + console.error("THREE.Raycaster: Unsupported camera type: " + camera.type); + } + } + intersectObject(object, recursive = true, intersects2 = []) { + intersectObject(object, this, intersects2, recursive); + intersects2.sort(ascSort); + return intersects2; + } + intersectObjects(objects, recursive = true, intersects2 = []) { + for (let i = 0, l = objects.length; i < l; i++) { + intersectObject(objects[i], this, intersects2, recursive); + } + intersects2.sort(ascSort); + return intersects2; + } + }; + function ascSort(a, b) { + return a.distance - b.distance; + } + function intersectObject(object, raycaster, intersects2, recursive) { + if (object.layers.test(raycaster.layers)) { + object.raycast(raycaster, intersects2); + } + if (recursive === true) { + const children = object.children; + for (let i = 0, l = children.length; i < l; i++) { + intersectObject(children[i], raycaster, intersects2, true); + } + } + } + var Spherical = class { + constructor(radius = 1, phi = 0, theta = 0) { + this.radius = radius; + this.phi = phi; + this.theta = theta; + return this; + } + set(radius, phi, theta) { + this.radius = radius; + this.phi = phi; + this.theta = theta; + return this; + } + copy(other) { + this.radius = other.radius; + this.phi = other.phi; + this.theta = other.theta; + return this; + } + // restrict phi to be between EPS and PI-EPS + makeSafe() { + const EPS = 1e-6; + this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi)); + return this; + } + setFromVector3(v) { + return this.setFromCartesianCoords(v.x, v.y, v.z); + } + setFromCartesianCoords(x, y, z) { + this.radius = Math.sqrt(x * x + y * y + z * z); + if (this.radius === 0) { + this.theta = 0; + this.phi = 0; + } else { + this.theta = Math.atan2(x, z); + this.phi = Math.acos(clamp(y / this.radius, -1, 1)); + } + return this; + } + clone() { + return new this.constructor().copy(this); + } + }; + var Cylindrical = class { + constructor(radius = 1, theta = 0, y = 0) { + this.radius = radius; + this.theta = theta; + this.y = y; + return this; + } + set(radius, theta, y) { + this.radius = radius; + this.theta = theta; + this.y = y; + return this; + } + copy(other) { + this.radius = other.radius; + this.theta = other.theta; + this.y = other.y; + return this; + } + setFromVector3(v) { + return this.setFromCartesianCoords(v.x, v.y, v.z); + } + setFromCartesianCoords(x, y, z) { + this.radius = Math.sqrt(x * x + z * z); + this.theta = Math.atan2(x, z); + this.y = y; + return this; + } + clone() { + return new this.constructor().copy(this); + } + }; + var _vector$4 = /* @__PURE__ */ new Vector2(); + var Box2 = class { + constructor(min = new Vector2(Infinity, Infinity), max2 = new Vector2(-Infinity, -Infinity)) { + this.isBox2 = true; + this.min = min; + this.max = max2; + } + set(min, max2) { + this.min.copy(min); + this.max.copy(max2); + return this; + } + setFromPoints(points) { + this.makeEmpty(); + for (let i = 0, il = points.length; i < il; i++) { + this.expandByPoint(points[i]); + } + return this; + } + setFromCenterAndSize(center, size) { + const halfSize = _vector$4.copy(size).multiplyScalar(0.5); + this.min.copy(center).sub(halfSize); + this.max.copy(center).add(halfSize); + return this; + } + clone() { + return new this.constructor().copy(this); + } + copy(box) { + this.min.copy(box.min); + this.max.copy(box.max); + return this; + } + makeEmpty() { + this.min.x = this.min.y = Infinity; + this.max.x = this.max.y = -Infinity; + return this; + } + isEmpty() { + return this.max.x < this.min.x || this.max.y < this.min.y; + } + getCenter(target) { + return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5); + } + getSize(target) { + return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min); + } + expandByPoint(point) { + this.min.min(point); + this.max.max(point); + return this; + } + expandByVector(vector) { + this.min.sub(vector); + this.max.add(vector); + return this; + } + expandByScalar(scalar) { + this.min.addScalar(-scalar); + this.max.addScalar(scalar); + return this; + } + containsPoint(point) { + return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true; + } + containsBox(box) { + return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y; + } + getParameter(point, target) { + return target.set( + (point.x - this.min.x) / (this.max.x - this.min.x), + (point.y - this.min.y) / (this.max.y - this.min.y) + ); + } + intersectsBox(box) { + return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y ? false : true; + } + clampPoint(point, target) { + return target.copy(point).clamp(this.min, this.max); + } + distanceToPoint(point) { + return this.clampPoint(point, _vector$4).distanceTo(point); + } + intersect(box) { + this.min.max(box.min); + this.max.min(box.max); + if (this.isEmpty()) this.makeEmpty(); + return this; + } + union(box) { + this.min.min(box.min); + this.max.max(box.max); + return this; + } + translate(offset) { + this.min.add(offset); + this.max.add(offset); + return this; + } + equals(box) { + return box.min.equals(this.min) && box.max.equals(this.max); + } + }; + var _startP = /* @__PURE__ */ new Vector3(); + var _startEnd = /* @__PURE__ */ new Vector3(); + var Line3 = class { + constructor(start = new Vector3(), end = new Vector3()) { + this.start = start; + this.end = end; + } + set(start, end) { + this.start.copy(start); + this.end.copy(end); + return this; + } + copy(line) { + this.start.copy(line.start); + this.end.copy(line.end); + return this; + } + getCenter(target) { + return target.addVectors(this.start, this.end).multiplyScalar(0.5); + } + delta(target) { + return target.subVectors(this.end, this.start); + } + distanceSq() { + return this.start.distanceToSquared(this.end); + } + distance() { + return this.start.distanceTo(this.end); + } + at(t, target) { + return this.delta(target).multiplyScalar(t).add(this.start); + } + closestPointToPointParameter(point, clampToLine) { + _startP.subVectors(point, this.start); + _startEnd.subVectors(this.end, this.start); + const startEnd2 = _startEnd.dot(_startEnd); + const startEnd_startP = _startEnd.dot(_startP); + let t = startEnd_startP / startEnd2; + if (clampToLine) { + t = clamp(t, 0, 1); + } + return t; + } + closestPointToPoint(point, clampToLine, target) { + const t = this.closestPointToPointParameter(point, clampToLine); + return this.delta(target).multiplyScalar(t).add(this.start); + } + applyMatrix4(matrix) { + this.start.applyMatrix4(matrix); + this.end.applyMatrix4(matrix); + return this; + } + equals(line) { + return line.start.equals(this.start) && line.end.equals(this.end); + } + clone() { + return new this.constructor().copy(this); + } + }; + var _vector$3 = /* @__PURE__ */ new Vector3(); + var SpotLightHelper = class extends Object3D { + constructor(light, color) { + super(); + this.light = light; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "SpotLightHelper"; + const geometry = new BufferGeometry(); + const positions = [ + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1, + 0, + 1, + 0, + 0, + 0, + -1, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 1, + 0, + 0, + 0, + 0, + -1, + 1 + ]; + for (let i = 0, j = 1, l = 32; i < l; i++, j++) { + const p1 = i / l * Math.PI * 2; + const p2 = j / l * Math.PI * 2; + positions.push( + Math.cos(p1), + Math.sin(p1), + 1, + Math.cos(p2), + Math.sin(p2), + 1 + ); + } + geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); + const material = new LineBasicMaterial({ fog: false, toneMapped: false }); + this.cone = new LineSegments(geometry, material); + this.add(this.cone); + this.update(); + } + dispose() { + this.cone.geometry.dispose(); + this.cone.material.dispose(); + } + update() { + this.light.updateWorldMatrix(true, false); + this.light.target.updateWorldMatrix(true, false); + const coneLength = this.light.distance ? this.light.distance : 1e3; + const coneWidth = coneLength * Math.tan(this.light.angle); + this.cone.scale.set(coneWidth, coneWidth, coneLength); + _vector$3.setFromMatrixPosition(this.light.target.matrixWorld); + this.cone.lookAt(_vector$3); + if (this.color !== void 0) { + this.cone.material.color.set(this.color); + } else { + this.cone.material.color.copy(this.light.color); + } + } + }; + var _vector$2 = /* @__PURE__ */ new Vector3(); + var _boneMatrix = /* @__PURE__ */ new Matrix4(); + var _matrixWorldInv = /* @__PURE__ */ new Matrix4(); + var SkeletonHelper = class extends LineSegments { + constructor(object) { + const bones = getBoneList(object); + const geometry = new BufferGeometry(); + const vertices = []; + const colors = []; + const color1 = new Color(0, 0, 1); + const color2 = new Color(0, 1, 0); + for (let i = 0; i < bones.length; i++) { + const bone = bones[i]; + if (bone.parent && bone.parent.isBone) { + vertices.push(0, 0, 0); + vertices.push(0, 0, 0); + colors.push(color1.r, color1.g, color1.b); + colors.push(color2.r, color2.g, color2.b); + } + } + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + const material = new LineBasicMaterial({ vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true }); + super(geometry, material); + this.isSkeletonHelper = true; + this.type = "SkeletonHelper"; + this.root = object; + this.bones = bones; + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; + } + updateMatrixWorld(force) { + const bones = this.bones; + const geometry = this.geometry; + const position = geometry.getAttribute("position"); + _matrixWorldInv.copy(this.root.matrixWorld).invert(); + for (let i = 0, j = 0; i < bones.length; i++) { + const bone = bones[i]; + if (bone.parent && bone.parent.isBone) { + _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld); + _vector$2.setFromMatrixPosition(_boneMatrix); + position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z); + _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld); + _vector$2.setFromMatrixPosition(_boneMatrix); + position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z); + j += 2; + } + } + geometry.getAttribute("position").needsUpdate = true; + super.updateMatrixWorld(force); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + }; + function getBoneList(object) { + const boneList = []; + if (object.isBone === true) { + boneList.push(object); + } + for (let i = 0; i < object.children.length; i++) { + boneList.push.apply(boneList, getBoneList(object.children[i])); + } + return boneList; + } + var PointLightHelper = class extends Mesh { + constructor(light, sphereSize, color) { + const geometry = new SphereGeometry(sphereSize, 4, 2); + const material = new MeshBasicMaterial({ wireframe: true, fog: false, toneMapped: false }); + super(geometry, material); + this.light = light; + this.color = color; + this.type = "PointLightHelper"; + this.matrix = this.light.matrixWorld; + this.matrixAutoUpdate = false; + this.update(); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + update() { + this.light.updateWorldMatrix(true, false); + if (this.color !== void 0) { + this.material.color.set(this.color); + } else { + this.material.color.copy(this.light.color); + } + } + }; + var _vector$1 = /* @__PURE__ */ new Vector3(); + var _color1 = /* @__PURE__ */ new Color(); + var _color2 = /* @__PURE__ */ new Color(); + var HemisphereLightHelper = class extends Object3D { + constructor(light, size, color) { + super(); + this.light = light; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "HemisphereLightHelper"; + const geometry = new OctahedronGeometry(size); + geometry.rotateY(Math.PI * 0.5); + this.material = new MeshBasicMaterial({ wireframe: true, fog: false, toneMapped: false }); + if (this.color === void 0) this.material.vertexColors = true; + const position = geometry.getAttribute("position"); + const colors = new Float32Array(position.count * 3); + geometry.setAttribute("color", new BufferAttribute(colors, 3)); + this.add(new Mesh(geometry, this.material)); + this.update(); + } + dispose() { + this.children[0].geometry.dispose(); + this.children[0].material.dispose(); + } + update() { + const mesh = this.children[0]; + if (this.color !== void 0) { + this.material.color.set(this.color); + } else { + const colors = mesh.geometry.getAttribute("color"); + _color1.copy(this.light.color); + _color2.copy(this.light.groundColor); + for (let i = 0, l = colors.count; i < l; i++) { + const color = i < l / 2 ? _color1 : _color2; + colors.setXYZ(i, color.r, color.g, color.b); + } + colors.needsUpdate = true; + } + this.light.updateWorldMatrix(true, false); + mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate()); + } + }; + var GridHelper = class extends LineSegments { + constructor(size = 10, divisions = 10, color1 = 4473924, color2 = 8947848) { + color1 = new Color(color1); + color2 = new Color(color2); + const center = divisions / 2; + const step = size / divisions; + const halfSize = size / 2; + const vertices = [], colors = []; + for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) { + vertices.push(-halfSize, 0, k, halfSize, 0, k); + vertices.push(k, 0, -halfSize, k, 0, halfSize); + const color = i === center ? color1 : color2; + color.toArray(colors, j); + j += 3; + color.toArray(colors, j); + j += 3; + color.toArray(colors, j); + j += 3; + color.toArray(colors, j); + j += 3; + } + const geometry = new BufferGeometry(); + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + const material = new LineBasicMaterial({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "GridHelper"; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + }; + var PolarGridHelper = class extends LineSegments { + constructor(radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 4473924, color2 = 8947848) { + color1 = new Color(color1); + color2 = new Color(color2); + const vertices = []; + const colors = []; + if (sectors > 1) { + for (let i = 0; i < sectors; i++) { + const v = i / sectors * (Math.PI * 2); + const x = Math.sin(v) * radius; + const z = Math.cos(v) * radius; + vertices.push(0, 0, 0); + vertices.push(x, 0, z); + const color = i & 1 ? color1 : color2; + colors.push(color.r, color.g, color.b); + colors.push(color.r, color.g, color.b); + } + } + for (let i = 0; i < rings; i++) { + const color = i & 1 ? color1 : color2; + const r = radius - radius / rings * i; + for (let j = 0; j < divisions; j++) { + let v = j / divisions * (Math.PI * 2); + let x = Math.sin(v) * r; + let z = Math.cos(v) * r; + vertices.push(x, 0, z); + colors.push(color.r, color.g, color.b); + v = (j + 1) / divisions * (Math.PI * 2); + x = Math.sin(v) * r; + z = Math.cos(v) * r; + vertices.push(x, 0, z); + colors.push(color.r, color.g, color.b); + } + } + const geometry = new BufferGeometry(); + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + const material = new LineBasicMaterial({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "PolarGridHelper"; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + }; + var _v1 = /* @__PURE__ */ new Vector3(); + var _v2 = /* @__PURE__ */ new Vector3(); + var _v3 = /* @__PURE__ */ new Vector3(); + var DirectionalLightHelper = class extends Object3D { + constructor(light, size, color) { + super(); + this.light = light; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "DirectionalLightHelper"; + if (size === void 0) size = 1; + let geometry = new BufferGeometry(); + geometry.setAttribute("position", new Float32BufferAttribute([ + -size, + size, + 0, + size, + size, + 0, + size, + -size, + 0, + -size, + -size, + 0, + -size, + size, + 0 + ], 3)); + const material = new LineBasicMaterial({ fog: false, toneMapped: false }); + this.lightPlane = new Line(geometry, material); + this.add(this.lightPlane); + geometry = new BufferGeometry(); + geometry.setAttribute("position", new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3)); + this.targetLine = new Line(geometry, material); + this.add(this.targetLine); + this.update(); + } + dispose() { + this.lightPlane.geometry.dispose(); + this.lightPlane.material.dispose(); + this.targetLine.geometry.dispose(); + this.targetLine.material.dispose(); + } + update() { + this.light.updateWorldMatrix(true, false); + this.light.target.updateWorldMatrix(true, false); + _v1.setFromMatrixPosition(this.light.matrixWorld); + _v2.setFromMatrixPosition(this.light.target.matrixWorld); + _v3.subVectors(_v2, _v1); + this.lightPlane.lookAt(_v2); + if (this.color !== void 0) { + this.lightPlane.material.color.set(this.color); + this.targetLine.material.color.set(this.color); + } else { + this.lightPlane.material.color.copy(this.light.color); + this.targetLine.material.color.copy(this.light.color); + } + this.targetLine.lookAt(_v2); + this.targetLine.scale.z = _v3.length(); + } + }; + var _vector = /* @__PURE__ */ new Vector3(); + var _camera = /* @__PURE__ */ new Camera(); + var CameraHelper = class extends LineSegments { + constructor(camera) { + const geometry = new BufferGeometry(); + const material = new LineBasicMaterial({ color: 16777215, vertexColors: true, toneMapped: false }); + const vertices = []; + const colors = []; + const pointMap = {}; + addLine("n1", "n2"); + addLine("n2", "n4"); + addLine("n4", "n3"); + addLine("n3", "n1"); + addLine("f1", "f2"); + addLine("f2", "f4"); + addLine("f4", "f3"); + addLine("f3", "f1"); + addLine("n1", "f1"); + addLine("n2", "f2"); + addLine("n3", "f3"); + addLine("n4", "f4"); + addLine("p", "n1"); + addLine("p", "n2"); + addLine("p", "n3"); + addLine("p", "n4"); + addLine("u1", "u2"); + addLine("u2", "u3"); + addLine("u3", "u1"); + addLine("c", "t"); + addLine("p", "c"); + addLine("cn1", "cn2"); + addLine("cn3", "cn4"); + addLine("cf1", "cf2"); + addLine("cf3", "cf4"); + function addLine(a, b) { + addPoint(a); + addPoint(b); + } + function addPoint(id) { + vertices.push(0, 0, 0); + colors.push(0, 0, 0); + if (pointMap[id] === void 0) { + pointMap[id] = []; + } + pointMap[id].push(vertices.length / 3 - 1); + } + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + super(geometry, material); + this.type = "CameraHelper"; + this.camera = camera; + if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix(); + this.matrix = camera.matrixWorld; + this.matrixAutoUpdate = false; + this.pointMap = pointMap; + this.update(); + const colorFrustum = new Color(16755200); + const colorCone = new Color(16711680); + const colorUp = new Color(43775); + const colorTarget = new Color(16777215); + const colorCross = new Color(3355443); + this.setColors(colorFrustum, colorCone, colorUp, colorTarget, colorCross); + } + setColors(frustum, cone, up, target, cross) { + const geometry = this.geometry; + const colorAttribute = geometry.getAttribute("color"); + colorAttribute.setXYZ(0, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(1, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(2, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(3, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(4, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(5, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(6, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(7, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(8, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(9, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(10, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(11, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(12, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(13, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(14, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(15, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(16, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(17, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(18, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(19, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(20, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(21, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(22, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(23, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(24, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(25, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(26, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(27, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(28, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(29, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(30, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(31, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(32, up.r, up.g, up.b); + colorAttribute.setXYZ(33, up.r, up.g, up.b); + colorAttribute.setXYZ(34, up.r, up.g, up.b); + colorAttribute.setXYZ(35, up.r, up.g, up.b); + colorAttribute.setXYZ(36, up.r, up.g, up.b); + colorAttribute.setXYZ(37, up.r, up.g, up.b); + colorAttribute.setXYZ(38, target.r, target.g, target.b); + colorAttribute.setXYZ(39, target.r, target.g, target.b); + colorAttribute.setXYZ(40, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(41, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(42, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(43, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(44, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(45, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(46, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(47, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(48, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(49, cross.r, cross.g, cross.b); + colorAttribute.needsUpdate = true; + } + update() { + const geometry = this.geometry; + const pointMap = this.pointMap; + const w = 1, h = 1; + _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); + setPoint("c", pointMap, geometry, _camera, 0, 0, -1); + setPoint("t", pointMap, geometry, _camera, 0, 0, 1); + setPoint("n1", pointMap, geometry, _camera, -w, -h, -1); + setPoint("n2", pointMap, geometry, _camera, w, -h, -1); + setPoint("n3", pointMap, geometry, _camera, -w, h, -1); + setPoint("n4", pointMap, geometry, _camera, w, h, -1); + setPoint("f1", pointMap, geometry, _camera, -w, -h, 1); + setPoint("f2", pointMap, geometry, _camera, w, -h, 1); + setPoint("f3", pointMap, geometry, _camera, -w, h, 1); + setPoint("f4", pointMap, geometry, _camera, w, h, 1); + setPoint("u1", pointMap, geometry, _camera, w * 0.7, h * 1.1, -1); + setPoint("u2", pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1); + setPoint("u3", pointMap, geometry, _camera, 0, h * 2, -1); + setPoint("cf1", pointMap, geometry, _camera, -w, 0, 1); + setPoint("cf2", pointMap, geometry, _camera, w, 0, 1); + setPoint("cf3", pointMap, geometry, _camera, 0, -h, 1); + setPoint("cf4", pointMap, geometry, _camera, 0, h, 1); + setPoint("cn1", pointMap, geometry, _camera, -w, 0, -1); + setPoint("cn2", pointMap, geometry, _camera, w, 0, -1); + setPoint("cn3", pointMap, geometry, _camera, 0, -h, -1); + setPoint("cn4", pointMap, geometry, _camera, 0, h, -1); + geometry.getAttribute("position").needsUpdate = true; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + }; + function setPoint(point, pointMap, geometry, camera, x, y, z) { + _vector.set(x, y, z).unproject(camera); + const points = pointMap[point]; + if (points !== void 0) { + const position = geometry.getAttribute("position"); + for (let i = 0, l = points.length; i < l; i++) { + position.setXYZ(points[i], _vector.x, _vector.y, _vector.z); + } + } + } + var _box = /* @__PURE__ */ new Box3(); + var BoxHelper = class extends LineSegments { + constructor(object, color = 16776960) { + const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]); + const positions = new Float32Array(8 * 3); + const geometry = new BufferGeometry(); + geometry.setIndex(new BufferAttribute(indices, 1)); + geometry.setAttribute("position", new BufferAttribute(positions, 3)); + super(geometry, new LineBasicMaterial({ color, toneMapped: false })); + this.object = object; + this.type = "BoxHelper"; + this.matrixAutoUpdate = false; + this.update(); + } + update(object) { + if (object !== void 0) { + console.warn("THREE.BoxHelper: .update() has no longer arguments."); + } + if (this.object !== void 0) { + _box.setFromObject(this.object); + } + if (_box.isEmpty()) return; + const min = _box.min; + const max2 = _box.max; + const position = this.geometry.attributes.position; + const array = position.array; + array[0] = max2.x; + array[1] = max2.y; + array[2] = max2.z; + array[3] = min.x; + array[4] = max2.y; + array[5] = max2.z; + array[6] = min.x; + array[7] = min.y; + array[8] = max2.z; + array[9] = max2.x; + array[10] = min.y; + array[11] = max2.z; + array[12] = max2.x; + array[13] = max2.y; + array[14] = min.z; + array[15] = min.x; + array[16] = max2.y; + array[17] = min.z; + array[18] = min.x; + array[19] = min.y; + array[20] = min.z; + array[21] = max2.x; + array[22] = min.y; + array[23] = min.z; + position.needsUpdate = true; + this.geometry.computeBoundingSphere(); + } + setFromObject(object) { + this.object = object; + this.update(); + return this; + } + copy(source, recursive) { + super.copy(source, recursive); + this.object = source.object; + return this; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + }; + var Box3Helper = class extends LineSegments { + constructor(box, color = 16776960) { + const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]); + const positions = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1]; + const geometry = new BufferGeometry(); + geometry.setIndex(new BufferAttribute(indices, 1)); + geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); + super(geometry, new LineBasicMaterial({ color, toneMapped: false })); + this.box = box; + this.type = "Box3Helper"; + this.geometry.computeBoundingSphere(); + } + updateMatrixWorld(force) { + const box = this.box; + if (box.isEmpty()) return; + box.getCenter(this.position); + box.getSize(this.scale); + this.scale.multiplyScalar(0.5); + super.updateMatrixWorld(force); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + }; + var PlaneHelper = class extends Line { + constructor(plane, size = 1, hex = 16776960) { + const color = hex; + const positions = [1, -1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0]; + const geometry = new BufferGeometry(); + geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); + geometry.computeBoundingSphere(); + super(geometry, new LineBasicMaterial({ color, toneMapped: false })); + this.type = "PlaneHelper"; + this.plane = plane; + this.size = size; + const positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0]; + const geometry2 = new BufferGeometry(); + geometry2.setAttribute("position", new Float32BufferAttribute(positions2, 3)); + geometry2.computeBoundingSphere(); + this.add(new Mesh(geometry2, new MeshBasicMaterial({ color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false }))); + } + updateMatrixWorld(force) { + this.position.set(0, 0, 0); + this.scale.set(0.5 * this.size, 0.5 * this.size, 1); + this.lookAt(this.plane.normal); + this.translateZ(-this.plane.constant); + super.updateMatrixWorld(force); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + this.children[0].geometry.dispose(); + this.children[0].material.dispose(); + } + }; + var _axis = /* @__PURE__ */ new Vector3(); + var _lineGeometry; + var _coneGeometry; + var ArrowHelper = class extends Object3D { + // dir is assumed to be normalized + constructor(dir = new Vector3(0, 0, 1), origin = new Vector3(0, 0, 0), length = 1, color = 16776960, headLength = length * 0.2, headWidth = headLength * 0.2) { + super(); + this.type = "ArrowHelper"; + if (_lineGeometry === void 0) { + _lineGeometry = new BufferGeometry(); + _lineGeometry.setAttribute("position", new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3)); + _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1); + _coneGeometry.translate(0, -0.5, 0); + } + this.position.copy(origin); + this.line = new Line(_lineGeometry, new LineBasicMaterial({ color, toneMapped: false })); + this.line.matrixAutoUpdate = false; + this.add(this.line); + this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({ color, toneMapped: false })); + this.cone.matrixAutoUpdate = false; + this.add(this.cone); + this.setDirection(dir); + this.setLength(length, headLength, headWidth); + } + setDirection(dir) { + if (dir.y > 0.99999) { + this.quaternion.set(0, 0, 0, 1); + } else if (dir.y < -0.99999) { + this.quaternion.set(1, 0, 0, 0); + } else { + _axis.set(dir.z, 0, -dir.x).normalize(); + const radians = Math.acos(dir.y); + this.quaternion.setFromAxisAngle(_axis, radians); + } + } + setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) { + this.line.scale.set(1, Math.max(1e-4, length - headLength), 1); + this.line.updateMatrix(); + this.cone.scale.set(headWidth, headLength, headWidth); + this.cone.position.y = length; + this.cone.updateMatrix(); + } + setColor(color) { + this.line.material.color.set(color); + this.cone.material.color.set(color); + } + copy(source) { + super.copy(source, false); + this.line.copy(source.line); + this.cone.copy(source.cone); + return this; + } + dispose() { + this.line.geometry.dispose(); + this.line.material.dispose(); + this.cone.geometry.dispose(); + this.cone.material.dispose(); + } + }; + var AxesHelper = class extends LineSegments { + constructor(size = 1) { + const vertices = [ + 0, + 0, + 0, + size, + 0, + 0, + 0, + 0, + 0, + 0, + size, + 0, + 0, + 0, + 0, + 0, + 0, + size + ]; + const colors = [ + 1, + 0, + 0, + 1, + 0.6, + 0, + 0, + 1, + 0, + 0.6, + 1, + 0, + 0, + 0, + 1, + 0, + 0.6, + 1 + ]; + const geometry = new BufferGeometry(); + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + const material = new LineBasicMaterial({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "AxesHelper"; + } + setColors(xAxisColor, yAxisColor, zAxisColor) { + const color = new Color(); + const array = this.geometry.attributes.color.array; + color.set(xAxisColor); + color.toArray(array, 0); + color.toArray(array, 3); + color.set(yAxisColor); + color.toArray(array, 6); + color.toArray(array, 9); + color.set(zAxisColor); + color.toArray(array, 12); + color.toArray(array, 15); + this.geometry.attributes.color.needsUpdate = true; + return this; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + }; + var ShapePath = class { + constructor() { + this.type = "ShapePath"; + this.color = new Color(); + this.subPaths = []; + this.currentPath = null; + } + moveTo(x, y) { + this.currentPath = new Path(); + this.subPaths.push(this.currentPath); + this.currentPath.moveTo(x, y); + return this; + } + lineTo(x, y) { + this.currentPath.lineTo(x, y); + return this; + } + quadraticCurveTo(aCPx, aCPy, aX, aY) { + this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY); + return this; + } + bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { + this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY); + return this; + } + splineThru(pts) { + this.currentPath.splineThru(pts); + return this; + } + toShapes(isCCW) { + function toShapesNoHoles(inSubpaths) { + const shapes2 = []; + for (let i = 0, l = inSubpaths.length; i < l; i++) { + const tmpPath2 = inSubpaths[i]; + const tmpShape2 = new Shape(); + tmpShape2.curves = tmpPath2.curves; + shapes2.push(tmpShape2); + } + return shapes2; + } + function isPointInsidePolygon(inPt, inPolygon) { + const polyLen = inPolygon.length; + let inside = false; + for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) { + let edgeLowPt = inPolygon[p]; + let edgeHighPt = inPolygon[q]; + let edgeDx = edgeHighPt.x - edgeLowPt.x; + let edgeDy = edgeHighPt.y - edgeLowPt.y; + if (Math.abs(edgeDy) > Number.EPSILON) { + if (edgeDy < 0) { + edgeLowPt = inPolygon[q]; + edgeDx = -edgeDx; + edgeHighPt = inPolygon[p]; + edgeDy = -edgeDy; + } + if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue; + if (inPt.y === edgeLowPt.y) { + if (inPt.x === edgeLowPt.x) return true; + } else { + const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y); + if (perpEdge === 0) return true; + if (perpEdge < 0) continue; + inside = !inside; + } + } else { + if (inPt.y !== edgeLowPt.y) continue; + if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; + } + } + return inside; + } + const isClockWise = ShapeUtils.isClockWise; + const subPaths = this.subPaths; + if (subPaths.length === 0) return []; + let solid, tmpPath, tmpShape; + const shapes = []; + if (subPaths.length === 1) { + tmpPath = subPaths[0]; + tmpShape = new Shape(); + tmpShape.curves = tmpPath.curves; + shapes.push(tmpShape); + return shapes; + } + let holesFirst = !isClockWise(subPaths[0].getPoints()); + holesFirst = isCCW ? !holesFirst : holesFirst; + const betterShapeHoles = []; + const newShapes = []; + let newShapeHoles = []; + let mainIdx = 0; + let tmpPoints; + newShapes[mainIdx] = void 0; + newShapeHoles[mainIdx] = []; + for (let i = 0, l = subPaths.length; i < l; i++) { + tmpPath = subPaths[i]; + tmpPoints = tmpPath.getPoints(); + solid = isClockWise(tmpPoints); + solid = isCCW ? !solid : solid; + if (solid) { + if (!holesFirst && newShapes[mainIdx]) mainIdx++; + newShapes[mainIdx] = { s: new Shape(), p: tmpPoints }; + newShapes[mainIdx].s.curves = tmpPath.curves; + if (holesFirst) mainIdx++; + newShapeHoles[mainIdx] = []; + } else { + newShapeHoles[mainIdx].push({ h: tmpPath, p: tmpPoints[0] }); + } + } + if (!newShapes[0]) return toShapesNoHoles(subPaths); + if (newShapes.length > 1) { + let ambiguous = false; + let toChange = 0; + for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) { + betterShapeHoles[sIdx] = []; + } + for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) { + const sho = newShapeHoles[sIdx]; + for (let hIdx = 0; hIdx < sho.length; hIdx++) { + const ho = sho[hIdx]; + let hole_unassigned = true; + for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) { + if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) { + if (sIdx !== s2Idx) toChange++; + if (hole_unassigned) { + hole_unassigned = false; + betterShapeHoles[s2Idx].push(ho); + } else { + ambiguous = true; + } + } + } + if (hole_unassigned) { + betterShapeHoles[sIdx].push(ho); + } + } + } + if (toChange > 0 && ambiguous === false) { + newShapeHoles = betterShapeHoles; + } + } + let tmpHoles; + for (let i = 0, il = newShapes.length; i < il; i++) { + tmpShape = newShapes[i].s; + shapes.push(tmpShape); + tmpHoles = newShapeHoles[i]; + for (let j = 0, jl = tmpHoles.length; j < jl; j++) { + tmpShape.holes.push(tmpHoles[j].h); + } + } + return shapes; + } + }; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: { + revision: REVISION + } })); + } + if (typeof window !== "undefined") { + if (window.__THREE__) { + console.warn("WARNING: Multiple instances of Three.js being imported."); + } else { + window.__THREE__ = REVISION; + } + } + + // examples/jsm/controls/OrbitControls.js + var _changeEvent = { type: "change" }; + var _startEvent = { type: "start" }; + var _endEvent = { type: "end" }; + var _ray2 = new Ray(); + var _plane = new Plane(); + var TILT_LIMIT = Math.cos(70 * MathUtils.DEG2RAD); + var OrbitControls = class extends EventDispatcher { + constructor(object, domElement) { + super(); + this.object = object; + this.domElement = domElement; + this.domElement.style.touchAction = "none"; + this.enabled = true; + this.target = new Vector3(); + this.cursor = new Vector3(); + this.minDistance = 0; + this.maxDistance = Infinity; + this.minZoom = 0; + this.maxZoom = Infinity; + this.minTargetRadius = 0; + this.maxTargetRadius = Infinity; + this.minPolarAngle = 0; + this.maxPolarAngle = Math.PI; + this.minAzimuthAngle = -Infinity; + this.maxAzimuthAngle = Infinity; + this.enableDamping = false; + this.dampingFactor = 0.05; + this.enableZoom = true; + this.zoomSpeed = 1; + this.enableRotate = true; + this.rotateSpeed = 1; + this.enablePan = true; + this.panSpeed = 1; + this.screenSpacePanning = true; + this.keyPanSpeed = 7; + this.zoomToCursor = false; + this.autoRotate = false; + this.autoRotateSpeed = 2; + this.keys = { LEFT: "ArrowLeft", UP: "ArrowUp", RIGHT: "ArrowRight", BOTTOM: "ArrowDown" }; + this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }; + this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }; + this.target0 = this.target.clone(); + this.position0 = this.object.position.clone(); + this.zoom0 = this.object.zoom; + this._domElementKeyEvents = null; + this.getPolarAngle = function() { + return spherical.phi; + }; + this.getAzimuthalAngle = function() { + return spherical.theta; + }; + this.getDistance = function() { + return this.object.position.distanceTo(this.target); + }; + this.listenToKeyEvents = function(domElement2) { + domElement2.addEventListener("keydown", onKeyDown); + this._domElementKeyEvents = domElement2; + }; + this.stopListenToKeyEvents = function() { + this._domElementKeyEvents.removeEventListener("keydown", onKeyDown); + this._domElementKeyEvents = null; + }; + this.saveState = function() { + scope.target0.copy(scope.target); + scope.position0.copy(scope.object.position); + scope.zoom0 = scope.object.zoom; + }; + this.reset = function() { + scope.target.copy(scope.target0); + scope.object.position.copy(scope.position0); + scope.object.zoom = scope.zoom0; + scope.object.updateProjectionMatrix(); + scope.dispatchEvent(_changeEvent); + scope.update(); + state = STATE.NONE; + }; + this.update = (function() { + const offset = new Vector3(); + const quat = new Quaternion().setFromUnitVectors(object.up, new Vector3(0, 1, 0)); + const quatInverse = quat.clone().invert(); + const lastPosition = new Vector3(); + const lastQuaternion = new Quaternion(); + const lastTargetPosition = new Vector3(); + const twoPI = 2 * Math.PI; + return function update(deltaTime = null) { + const position = scope.object.position; + offset.copy(position).sub(scope.target); + offset.applyQuaternion(quat); + spherical.setFromVector3(offset); + if (scope.autoRotate && state === STATE.NONE) { + rotateLeft(getAutoRotationAngle(deltaTime)); + } + if (scope.enableDamping) { + spherical.theta += sphericalDelta.theta * scope.dampingFactor; + spherical.phi += sphericalDelta.phi * scope.dampingFactor; + } else { + spherical.theta += sphericalDelta.theta; + spherical.phi += sphericalDelta.phi; + } + let min = scope.minAzimuthAngle; + let max2 = scope.maxAzimuthAngle; + if (isFinite(min) && isFinite(max2)) { + if (min < -Math.PI) min += twoPI; + else if (min > Math.PI) min -= twoPI; + if (max2 < -Math.PI) max2 += twoPI; + else if (max2 > Math.PI) max2 -= twoPI; + if (min <= max2) { + spherical.theta = Math.max(min, Math.min(max2, spherical.theta)); + } else { + spherical.theta = spherical.theta > (min + max2) / 2 ? Math.max(min, spherical.theta) : Math.min(max2, spherical.theta); + } + } + spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi)); + spherical.makeSafe(); + if (scope.enableDamping === true) { + scope.target.addScaledVector(panOffset, scope.dampingFactor); + } else { + scope.target.add(panOffset); + } + scope.target.sub(scope.cursor); + scope.target.clampLength(scope.minTargetRadius, scope.maxTargetRadius); + scope.target.add(scope.cursor); + if (scope.zoomToCursor && performCursorZoom || scope.object.isOrthographicCamera) { + spherical.radius = clampDistance(spherical.radius); + } else { + spherical.radius = clampDistance(spherical.radius * scale); + } + offset.setFromSpherical(spherical); + offset.applyQuaternion(quatInverse); + position.copy(scope.target).add(offset); + scope.object.lookAt(scope.target); + if (scope.enableDamping === true) { + sphericalDelta.theta *= 1 - scope.dampingFactor; + sphericalDelta.phi *= 1 - scope.dampingFactor; + panOffset.multiplyScalar(1 - scope.dampingFactor); + } else { + sphericalDelta.set(0, 0, 0); + panOffset.set(0, 0, 0); + } + let zoomChanged = false; + if (scope.zoomToCursor && performCursorZoom) { + let newRadius = null; + if (scope.object.isPerspectiveCamera) { + const prevRadius = offset.length(); + newRadius = clampDistance(prevRadius * scale); + const radiusDelta = prevRadius - newRadius; + scope.object.position.addScaledVector(dollyDirection, radiusDelta); + scope.object.updateMatrixWorld(); + } else if (scope.object.isOrthographicCamera) { + const mouseBefore = new Vector3(mouse.x, mouse.y, 0); + mouseBefore.unproject(scope.object); + scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / scale)); + scope.object.updateProjectionMatrix(); + zoomChanged = true; + const mouseAfter = new Vector3(mouse.x, mouse.y, 0); + mouseAfter.unproject(scope.object); + scope.object.position.sub(mouseAfter).add(mouseBefore); + scope.object.updateMatrixWorld(); + newRadius = offset.length(); + } else { + console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."); + scope.zoomToCursor = false; + } + if (newRadius !== null) { + if (this.screenSpacePanning) { + scope.target.set(0, 0, -1).transformDirection(scope.object.matrix).multiplyScalar(newRadius).add(scope.object.position); + } else { + _ray2.origin.copy(scope.object.position); + _ray2.direction.set(0, 0, -1).transformDirection(scope.object.matrix); + if (Math.abs(scope.object.up.dot(_ray2.direction)) < TILT_LIMIT) { + object.lookAt(scope.target); + } else { + _plane.setFromNormalAndCoplanarPoint(scope.object.up, scope.target); + _ray2.intersectPlane(_plane, scope.target); + } + } + } + } else if (scope.object.isOrthographicCamera) { + scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / scale)); + scope.object.updateProjectionMatrix(); + zoomChanged = true; + } + scale = 1; + performCursorZoom = false; + if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS || lastTargetPosition.distanceToSquared(scope.target) > 0) { + scope.dispatchEvent(_changeEvent); + lastPosition.copy(scope.object.position); + lastQuaternion.copy(scope.object.quaternion); + lastTargetPosition.copy(scope.target); + return true; + } + return false; + }; + })(); + this.dispose = function() { + scope.domElement.removeEventListener("contextmenu", onContextMenu); + scope.domElement.removeEventListener("pointerdown", onPointerDown2); + scope.domElement.removeEventListener("pointercancel", onPointerUp2); + scope.domElement.removeEventListener("wheel", onMouseWheel); + scope.domElement.removeEventListener("pointermove", onPointerMove2); + scope.domElement.removeEventListener("pointerup", onPointerUp2); + if (scope._domElementKeyEvents !== null) { + scope._domElementKeyEvents.removeEventListener("keydown", onKeyDown); + scope._domElementKeyEvents = null; + } + }; + const scope = this; + const STATE = { + NONE: -1, + ROTATE: 0, + DOLLY: 1, + PAN: 2, + TOUCH_ROTATE: 3, + TOUCH_PAN: 4, + TOUCH_DOLLY_PAN: 5, + TOUCH_DOLLY_ROTATE: 6 + }; + let state = STATE.NONE; + const EPS = 1e-6; + const spherical = new Spherical(); + const sphericalDelta = new Spherical(); + let scale = 1; + const panOffset = new Vector3(); + const rotateStart = new Vector2(); + const rotateEnd = new Vector2(); + const rotateDelta = new Vector2(); + const panStart = new Vector2(); + const panEnd = new Vector2(); + const panDelta = new Vector2(); + const dollyStart = new Vector2(); + const dollyEnd = new Vector2(); + const dollyDelta = new Vector2(); + const dollyDirection = new Vector3(); + const mouse = new Vector2(); + let performCursorZoom = false; + const pointers = []; + const pointerPositions = {}; + function getAutoRotationAngle(deltaTime) { + if (deltaTime !== null) { + return 2 * Math.PI / 60 * scope.autoRotateSpeed * deltaTime; + } else { + return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; + } + } + function getZoomScale(delta) { + const normalized_delta = Math.abs(delta) / (100 * (window.devicePixelRatio | 0)); + return Math.pow(0.95, scope.zoomSpeed * normalized_delta); + } + function rotateLeft(angle) { + sphericalDelta.theta -= angle; + } + function rotateUp(angle) { + sphericalDelta.phi -= angle; + } + const panLeft = (function() { + const v = new Vector3(); + return function panLeft2(distance, objectMatrix) { + v.setFromMatrixColumn(objectMatrix, 0); + v.multiplyScalar(-distance); + panOffset.add(v); + }; + })(); + const panUp = (function() { + const v = new Vector3(); + return function panUp2(distance, objectMatrix) { + if (scope.screenSpacePanning === true) { + v.setFromMatrixColumn(objectMatrix, 1); + } else { + v.setFromMatrixColumn(objectMatrix, 0); + v.crossVectors(scope.object.up, v); + } + v.multiplyScalar(distance); + panOffset.add(v); + }; + })(); + const pan = (function() { + const offset = new Vector3(); + return function pan2(deltaX, deltaY) { + const element = scope.domElement; + if (scope.object.isPerspectiveCamera) { + const position = scope.object.position; + offset.copy(position).sub(scope.target); + let targetDistance = offset.length(); + targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180); + panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix); + panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix); + } else if (scope.object.isOrthographicCamera) { + panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix); + panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix); + } else { + console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."); + scope.enablePan = false; + } + }; + })(); + function dollyOut(dollyScale) { + if (scope.object.isPerspectiveCamera || scope.object.isOrthographicCamera) { + scale /= dollyScale; + } else { + console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."); + scope.enableZoom = false; + } + } + function dollyIn(dollyScale) { + if (scope.object.isPerspectiveCamera || scope.object.isOrthographicCamera) { + scale *= dollyScale; + } else { + console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."); + scope.enableZoom = false; + } + } + function updateZoomParameters(x, y) { + if (!scope.zoomToCursor) { + return; + } + performCursorZoom = true; + const rect = scope.domElement.getBoundingClientRect(); + const dx = x - rect.left; + const dy = y - rect.top; + const w = rect.width; + const h = rect.height; + mouse.x = dx / w * 2 - 1; + mouse.y = -(dy / h) * 2 + 1; + dollyDirection.set(mouse.x, mouse.y, 1).unproject(scope.object).sub(scope.object.position).normalize(); + } + function clampDistance(dist) { + return Math.max(scope.minDistance, Math.min(scope.maxDistance, dist)); + } + function handleMouseDownRotate(event) { + rotateStart.set(event.clientX, event.clientY); + } + function handleMouseDownDolly(event) { + updateZoomParameters(event.clientX, event.clientX); + dollyStart.set(event.clientX, event.clientY); + } + function handleMouseDownPan(event) { + panStart.set(event.clientX, event.clientY); + } + function handleMouseMoveRotate(event) { + rotateEnd.set(event.clientX, event.clientY); + rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed); + const element = scope.domElement; + rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); + rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight); + rotateStart.copy(rotateEnd); + scope.update(); + } + function handleMouseMoveDolly(event) { + dollyEnd.set(event.clientX, event.clientY); + dollyDelta.subVectors(dollyEnd, dollyStart); + if (dollyDelta.y > 0) { + dollyOut(getZoomScale(dollyDelta.y)); + } else if (dollyDelta.y < 0) { + dollyIn(getZoomScale(dollyDelta.y)); + } + dollyStart.copy(dollyEnd); + scope.update(); + } + function handleMouseMovePan(event) { + panEnd.set(event.clientX, event.clientY); + panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed); + pan(panDelta.x, panDelta.y); + panStart.copy(panEnd); + scope.update(); + } + function handleMouseWheel(event) { + updateZoomParameters(event.clientX, event.clientY); + if (event.deltaY < 0) { + dollyIn(getZoomScale(event.deltaY)); + } else if (event.deltaY > 0) { + dollyOut(getZoomScale(event.deltaY)); + } + scope.update(); + } + function handleKeyDown(event) { + let needsUpdate = false; + switch (event.code) { + case scope.keys.UP: + if (event.ctrlKey || event.metaKey || event.shiftKey) { + rotateUp(2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight); + } else { + pan(0, scope.keyPanSpeed); + } + needsUpdate = true; + break; + case scope.keys.BOTTOM: + if (event.ctrlKey || event.metaKey || event.shiftKey) { + rotateUp(-2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight); + } else { + pan(0, -scope.keyPanSpeed); + } + needsUpdate = true; + break; + case scope.keys.LEFT: + if (event.ctrlKey || event.metaKey || event.shiftKey) { + rotateLeft(2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight); + } else { + pan(scope.keyPanSpeed, 0); + } + needsUpdate = true; + break; + case scope.keys.RIGHT: + if (event.ctrlKey || event.metaKey || event.shiftKey) { + rotateLeft(-2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight); + } else { + pan(-scope.keyPanSpeed, 0); + } + needsUpdate = true; + break; + } + if (needsUpdate) { + event.preventDefault(); + scope.update(); + } + } + function handleTouchStartRotate(event) { + if (pointers.length === 1) { + rotateStart.set(event.pageX, event.pageY); + } else { + const position = getSecondPointerPosition(event); + const x = 0.5 * (event.pageX + position.x); + const y = 0.5 * (event.pageY + position.y); + rotateStart.set(x, y); + } + } + function handleTouchStartPan(event) { + if (pointers.length === 1) { + panStart.set(event.pageX, event.pageY); + } else { + const position = getSecondPointerPosition(event); + const x = 0.5 * (event.pageX + position.x); + const y = 0.5 * (event.pageY + position.y); + panStart.set(x, y); + } + } + function handleTouchStartDolly(event) { + const position = getSecondPointerPosition(event); + const dx = event.pageX - position.x; + const dy = event.pageY - position.y; + const distance = Math.sqrt(dx * dx + dy * dy); + dollyStart.set(0, distance); + } + function handleTouchStartDollyPan(event) { + if (scope.enableZoom) handleTouchStartDolly(event); + if (scope.enablePan) handleTouchStartPan(event); + } + function handleTouchStartDollyRotate(event) { + if (scope.enableZoom) handleTouchStartDolly(event); + if (scope.enableRotate) handleTouchStartRotate(event); + } + function handleTouchMoveRotate(event) { + if (pointers.length == 1) { + rotateEnd.set(event.pageX, event.pageY); + } else { + const position = getSecondPointerPosition(event); + const x = 0.5 * (event.pageX + position.x); + const y = 0.5 * (event.pageY + position.y); + rotateEnd.set(x, y); + } + rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed); + const element = scope.domElement; + rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); + rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight); + rotateStart.copy(rotateEnd); + } + function handleTouchMovePan(event) { + if (pointers.length === 1) { + panEnd.set(event.pageX, event.pageY); + } else { + const position = getSecondPointerPosition(event); + const x = 0.5 * (event.pageX + position.x); + const y = 0.5 * (event.pageY + position.y); + panEnd.set(x, y); + } + panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed); + pan(panDelta.x, panDelta.y); + panStart.copy(panEnd); + } + function handleTouchMoveDolly(event) { + const position = getSecondPointerPosition(event); + const dx = event.pageX - position.x; + const dy = event.pageY - position.y; + const distance = Math.sqrt(dx * dx + dy * dy); + dollyEnd.set(0, distance); + dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed)); + dollyOut(dollyDelta.y); + dollyStart.copy(dollyEnd); + const centerX = (event.pageX + position.x) * 0.5; + const centerY = (event.pageY + position.y) * 0.5; + updateZoomParameters(centerX, centerY); + } + function handleTouchMoveDollyPan(event) { + if (scope.enableZoom) handleTouchMoveDolly(event); + if (scope.enablePan) handleTouchMovePan(event); + } + function handleTouchMoveDollyRotate(event) { + if (scope.enableZoom) handleTouchMoveDolly(event); + if (scope.enableRotate) handleTouchMoveRotate(event); + } + function onPointerDown2(event) { + if (scope.enabled === false) return; + if (pointers.length === 0) { + scope.domElement.setPointerCapture(event.pointerId); + scope.domElement.addEventListener("pointermove", onPointerMove2); + scope.domElement.addEventListener("pointerup", onPointerUp2); + } + addPointer(event); + if (event.pointerType === "touch") { + onTouchStart(event); + } else { + onMouseDown(event); + } + } + function onPointerMove2(event) { + if (scope.enabled === false) return; + if (event.pointerType === "touch") { + onTouchMove(event); + } else { + onMouseMove(event); + } + } + function onPointerUp2(event) { + removePointer(event); + if (pointers.length === 0) { + scope.domElement.releasePointerCapture(event.pointerId); + scope.domElement.removeEventListener("pointermove", onPointerMove2); + scope.domElement.removeEventListener("pointerup", onPointerUp2); + } + scope.dispatchEvent(_endEvent); + state = STATE.NONE; + } + function onMouseDown(event) { + let mouseAction; + switch (event.button) { + case 0: + mouseAction = scope.mouseButtons.LEFT; + break; + case 1: + mouseAction = scope.mouseButtons.MIDDLE; + break; + case 2: + mouseAction = scope.mouseButtons.RIGHT; + break; + default: + mouseAction = -1; + } + switch (mouseAction) { + case MOUSE.DOLLY: + if (scope.enableZoom === false) return; + handleMouseDownDolly(event); + state = STATE.DOLLY; + break; + case MOUSE.ROTATE: + if (event.ctrlKey || event.metaKey || event.shiftKey) { + if (scope.enablePan === false) return; + handleMouseDownPan(event); + state = STATE.PAN; + } else { + if (scope.enableRotate === false) return; + handleMouseDownRotate(event); + state = STATE.ROTATE; + } + break; + case MOUSE.PAN: + if (event.ctrlKey || event.metaKey || event.shiftKey) { + if (scope.enableRotate === false) return; + handleMouseDownRotate(event); + state = STATE.ROTATE; + } else { + if (scope.enablePan === false) return; + handleMouseDownPan(event); + state = STATE.PAN; + } + break; + default: + state = STATE.NONE; + } + if (state !== STATE.NONE) { + scope.dispatchEvent(_startEvent); + } + } + function onMouseMove(event) { + switch (state) { + case STATE.ROTATE: + if (scope.enableRotate === false) return; + handleMouseMoveRotate(event); + break; + case STATE.DOLLY: + if (scope.enableZoom === false) return; + handleMouseMoveDolly(event); + break; + case STATE.PAN: + if (scope.enablePan === false) return; + handleMouseMovePan(event); + break; + } + } + function onMouseWheel(event) { + if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE) return; + event.preventDefault(); + scope.dispatchEvent(_startEvent); + handleMouseWheel(event); + scope.dispatchEvent(_endEvent); + } + function onKeyDown(event) { + if (scope.enabled === false || scope.enablePan === false) return; + handleKeyDown(event); + } + function onTouchStart(event) { + trackPointer(event); + switch (pointers.length) { + case 1: + switch (scope.touches.ONE) { + case TOUCH.ROTATE: + if (scope.enableRotate === false) return; + handleTouchStartRotate(event); + state = STATE.TOUCH_ROTATE; + break; + case TOUCH.PAN: + if (scope.enablePan === false) return; + handleTouchStartPan(event); + state = STATE.TOUCH_PAN; + break; + default: + state = STATE.NONE; + } + break; + case 2: + switch (scope.touches.TWO) { + case TOUCH.DOLLY_PAN: + if (scope.enableZoom === false && scope.enablePan === false) return; + handleTouchStartDollyPan(event); + state = STATE.TOUCH_DOLLY_PAN; + break; + case TOUCH.DOLLY_ROTATE: + if (scope.enableZoom === false && scope.enableRotate === false) return; + handleTouchStartDollyRotate(event); + state = STATE.TOUCH_DOLLY_ROTATE; + break; + default: + state = STATE.NONE; + } + break; + default: + state = STATE.NONE; + } + if (state !== STATE.NONE) { + scope.dispatchEvent(_startEvent); + } + } + function onTouchMove(event) { + trackPointer(event); + switch (state) { + case STATE.TOUCH_ROTATE: + if (scope.enableRotate === false) return; + handleTouchMoveRotate(event); + scope.update(); + break; + case STATE.TOUCH_PAN: + if (scope.enablePan === false) return; + handleTouchMovePan(event); + scope.update(); + break; + case STATE.TOUCH_DOLLY_PAN: + if (scope.enableZoom === false && scope.enablePan === false) return; + handleTouchMoveDollyPan(event); + scope.update(); + break; + case STATE.TOUCH_DOLLY_ROTATE: + if (scope.enableZoom === false && scope.enableRotate === false) return; + handleTouchMoveDollyRotate(event); + scope.update(); + break; + default: + state = STATE.NONE; + } + } + function onContextMenu(event) { + if (scope.enabled === false) return; + event.preventDefault(); + } + function addPointer(event) { + pointers.push(event.pointerId); + } + function removePointer(event) { + delete pointerPositions[event.pointerId]; + for (let i = 0; i < pointers.length; i++) { + if (pointers[i] == event.pointerId) { + pointers.splice(i, 1); + return; + } + } + } + function trackPointer(event) { + let position = pointerPositions[event.pointerId]; + if (position === void 0) { + position = new Vector2(); + pointerPositions[event.pointerId] = position; + } + position.set(event.pageX, event.pageY); + } + function getSecondPointerPosition(event) { + const pointerId = event.pointerId === pointers[0] ? pointers[1] : pointers[0]; + return pointerPositions[pointerId]; + } + scope.domElement.addEventListener("contextmenu", onContextMenu); + scope.domElement.addEventListener("pointerdown", onPointerDown2); + scope.domElement.addEventListener("pointercancel", onPointerUp2); + scope.domElement.addEventListener("wheel", onMouseWheel, { passive: false }); + this.update(); + } + }; + + // examples/jsm/controls/TransformControls.js + var _raycaster = new Raycaster(); + var _tempVector = new Vector3(); + var _tempVector2 = new Vector3(); + var _tempQuaternion = new Quaternion(); + var _unit = { + X: new Vector3(1, 0, 0), + Y: new Vector3(0, 1, 0), + Z: new Vector3(0, 0, 1) + }; + var _changeEvent2 = { type: "change" }; + var _mouseDownEvent = { type: "mouseDown" }; + var _mouseUpEvent = { type: "mouseUp", mode: null }; + var _objectChangeEvent = { type: "objectChange" }; + var TransformControls = class extends Object3D { + constructor(camera, domElement) { + super(); + if (domElement === void 0) { + console.warn('THREE.TransformControls: The second parameter "domElement" is now mandatory.'); + domElement = document; + } + this.isTransformControls = true; + this.visible = false; + this.domElement = domElement; + this.domElement.style.touchAction = "none"; + const _gizmo = new TransformControlsGizmo(); + this._gizmo = _gizmo; + this.add(_gizmo); + const _plane2 = new TransformControlsPlane(); + this._plane = _plane2; + this.add(_plane2); + const scope = this; + function defineProperty(propName, defaultValue) { + let propValue = defaultValue; + Object.defineProperty(scope, propName, { + get: function() { + return propValue !== void 0 ? propValue : defaultValue; + }, + set: function(value) { + if (propValue !== value) { + propValue = value; + _plane2[propName] = value; + _gizmo[propName] = value; + scope.dispatchEvent({ type: propName + "-changed", value }); + scope.dispatchEvent(_changeEvent2); + } + } + }); + scope[propName] = defaultValue; + _plane2[propName] = defaultValue; + _gizmo[propName] = defaultValue; + } + defineProperty("camera", camera); + defineProperty("object", void 0); + defineProperty("enabled", true); + defineProperty("axis", null); + defineProperty("mode", "translate"); + defineProperty("translationSnap", null); + defineProperty("rotationSnap", null); + defineProperty("scaleSnap", null); + defineProperty("space", "world"); + defineProperty("size", 1); + defineProperty("dragging", false); + defineProperty("showX", true); + defineProperty("showY", true); + defineProperty("showZ", true); + const worldPosition = new Vector3(); + const worldPositionStart = new Vector3(); + const worldQuaternion = new Quaternion(); + const worldQuaternionStart = new Quaternion(); + const cameraPosition = new Vector3(); + const cameraQuaternion = new Quaternion(); + const pointStart = new Vector3(); + const pointEnd = new Vector3(); + const rotationAxis = new Vector3(); + const rotationAngle = 0; + const eye = new Vector3(); + defineProperty("worldPosition", worldPosition); + defineProperty("worldPositionStart", worldPositionStart); + defineProperty("worldQuaternion", worldQuaternion); + defineProperty("worldQuaternionStart", worldQuaternionStart); + defineProperty("cameraPosition", cameraPosition); + defineProperty("cameraQuaternion", cameraQuaternion); + defineProperty("pointStart", pointStart); + defineProperty("pointEnd", pointEnd); + defineProperty("rotationAxis", rotationAxis); + defineProperty("rotationAngle", rotationAngle); + defineProperty("eye", eye); + this._offset = new Vector3(); + this._startNorm = new Vector3(); + this._endNorm = new Vector3(); + this._cameraScale = new Vector3(); + this._parentPosition = new Vector3(); + this._parentQuaternion = new Quaternion(); + this._parentQuaternionInv = new Quaternion(); + this._parentScale = new Vector3(); + this._worldScaleStart = new Vector3(); + this._worldQuaternionInv = new Quaternion(); + this._worldScale = new Vector3(); + this._positionStart = new Vector3(); + this._quaternionStart = new Quaternion(); + this._scaleStart = new Vector3(); + this._getPointer = getPointer.bind(this); + this._onPointerDown = onPointerDown.bind(this); + this._onPointerHover = onPointerHover.bind(this); + this._onPointerMove = onPointerMove.bind(this); + this._onPointerUp = onPointerUp.bind(this); + this.domElement.addEventListener("pointerdown", this._onPointerDown); + this.domElement.addEventListener("pointermove", this._onPointerHover); + this.domElement.addEventListener("pointerup", this._onPointerUp); + } + // updateMatrixWorld updates key transformation variables + updateMatrixWorld() { + if (this.object !== void 0) { + this.object.updateMatrixWorld(); + if (this.object.parent === null) { + console.error("TransformControls: The attached 3D object must be a part of the scene graph."); + } else { + this.object.parent.matrixWorld.decompose(this._parentPosition, this._parentQuaternion, this._parentScale); + } + this.object.matrixWorld.decompose(this.worldPosition, this.worldQuaternion, this._worldScale); + this._parentQuaternionInv.copy(this._parentQuaternion).invert(); + this._worldQuaternionInv.copy(this.worldQuaternion).invert(); + } + this.camera.updateMatrixWorld(); + this.camera.matrixWorld.decompose(this.cameraPosition, this.cameraQuaternion, this._cameraScale); + if (this.camera.isOrthographicCamera) { + this.camera.getWorldDirection(this.eye).negate(); + } else { + this.eye.copy(this.cameraPosition).sub(this.worldPosition).normalize(); + } + super.updateMatrixWorld(this); + } + pointerHover(pointer) { + if (this.object === void 0 || this.dragging === true) return; + _raycaster.setFromCamera(pointer, this.camera); + const intersect = intersectObjectWithRay(this._gizmo.picker[this.mode], _raycaster); + if (intersect) { + this.axis = intersect.object.name; + } else { + this.axis = null; + } + } + pointerDown(pointer) { + if (this.object === void 0 || this.dragging === true || pointer.button !== 0) return; + if (this.axis !== null) { + _raycaster.setFromCamera(pointer, this.camera); + const planeIntersect = intersectObjectWithRay(this._plane, _raycaster, true); + if (planeIntersect) { + this.object.updateMatrixWorld(); + this.object.parent.updateMatrixWorld(); + this._positionStart.copy(this.object.position); + this._quaternionStart.copy(this.object.quaternion); + this._scaleStart.copy(this.object.scale); + this.object.matrixWorld.decompose(this.worldPositionStart, this.worldQuaternionStart, this._worldScaleStart); + this.pointStart.copy(planeIntersect.point).sub(this.worldPositionStart); + } + this.dragging = true; + _mouseDownEvent.mode = this.mode; + this.dispatchEvent(_mouseDownEvent); + } + } + pointerMove(pointer) { + const axis = this.axis; + const mode = this.mode; + const object = this.object; + let space = this.space; + if (mode === "scale") { + space = "local"; + } else if (axis === "E" || axis === "XYZE" || axis === "XYZ") { + space = "world"; + } + if (object === void 0 || axis === null || this.dragging === false || pointer.button !== -1) return; + _raycaster.setFromCamera(pointer, this.camera); + const planeIntersect = intersectObjectWithRay(this._plane, _raycaster, true); + if (!planeIntersect) return; + this.pointEnd.copy(planeIntersect.point).sub(this.worldPositionStart); + if (mode === "translate") { + this._offset.copy(this.pointEnd).sub(this.pointStart); + if (space === "local" && axis !== "XYZ") { + this._offset.applyQuaternion(this._worldQuaternionInv); + } + if (axis.indexOf("X") === -1) this._offset.x = 0; + if (axis.indexOf("Y") === -1) this._offset.y = 0; + if (axis.indexOf("Z") === -1) this._offset.z = 0; + if (space === "local" && axis !== "XYZ") { + this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale); + } else { + this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale); + } + object.position.copy(this._offset).add(this._positionStart); + if (this.translationSnap) { + if (space === "local") { + object.position.applyQuaternion(_tempQuaternion.copy(this._quaternionStart).invert()); + if (axis.search("X") !== -1) { + object.position.x = Math.round(object.position.x / this.translationSnap) * this.translationSnap; + } + if (axis.search("Y") !== -1) { + object.position.y = Math.round(object.position.y / this.translationSnap) * this.translationSnap; + } + if (axis.search("Z") !== -1) { + object.position.z = Math.round(object.position.z / this.translationSnap) * this.translationSnap; + } + object.position.applyQuaternion(this._quaternionStart); + } + if (space === "world") { + if (object.parent) { + object.position.add(_tempVector.setFromMatrixPosition(object.parent.matrixWorld)); + } + if (axis.search("X") !== -1) { + object.position.x = Math.round(object.position.x / this.translationSnap) * this.translationSnap; + } + if (axis.search("Y") !== -1) { + object.position.y = Math.round(object.position.y / this.translationSnap) * this.translationSnap; + } + if (axis.search("Z") !== -1) { + object.position.z = Math.round(object.position.z / this.translationSnap) * this.translationSnap; + } + if (object.parent) { + object.position.sub(_tempVector.setFromMatrixPosition(object.parent.matrixWorld)); + } + } + } + } else if (mode === "scale") { + if (axis.search("XYZ") !== -1) { + let d = this.pointEnd.length() / this.pointStart.length(); + if (this.pointEnd.dot(this.pointStart) < 0) d *= -1; + _tempVector2.set(d, d, d); + } else { + _tempVector.copy(this.pointStart); + _tempVector2.copy(this.pointEnd); + _tempVector.applyQuaternion(this._worldQuaternionInv); + _tempVector2.applyQuaternion(this._worldQuaternionInv); + _tempVector2.divide(_tempVector); + if (axis.search("X") === -1) { + _tempVector2.x = 1; + } + if (axis.search("Y") === -1) { + _tempVector2.y = 1; + } + if (axis.search("Z") === -1) { + _tempVector2.z = 1; + } + } + object.scale.copy(this._scaleStart).multiply(_tempVector2); + if (this.scaleSnap) { + if (axis.search("X") !== -1) { + object.scale.x = Math.round(object.scale.x / this.scaleSnap) * this.scaleSnap || this.scaleSnap; + } + if (axis.search("Y") !== -1) { + object.scale.y = Math.round(object.scale.y / this.scaleSnap) * this.scaleSnap || this.scaleSnap; + } + if (axis.search("Z") !== -1) { + object.scale.z = Math.round(object.scale.z / this.scaleSnap) * this.scaleSnap || this.scaleSnap; + } + } + } else if (mode === "rotate") { + this._offset.copy(this.pointEnd).sub(this.pointStart); + const ROTATION_SPEED = 20 / this.worldPosition.distanceTo(_tempVector.setFromMatrixPosition(this.camera.matrixWorld)); + let _inPlaneRotation = false; + if (axis === "XYZE") { + this.rotationAxis.copy(this._offset).cross(this.eye).normalize(); + this.rotationAngle = this._offset.dot(_tempVector.copy(this.rotationAxis).cross(this.eye)) * ROTATION_SPEED; + } else if (axis === "X" || axis === "Y" || axis === "Z") { + this.rotationAxis.copy(_unit[axis]); + _tempVector.copy(_unit[axis]); + if (space === "local") { + _tempVector.applyQuaternion(this.worldQuaternion); + } + _tempVector.cross(this.eye); + if (_tempVector.length() === 0) { + _inPlaneRotation = true; + } else { + this.rotationAngle = this._offset.dot(_tempVector.normalize()) * ROTATION_SPEED; + } + } + if (axis === "E" || _inPlaneRotation) { + this.rotationAxis.copy(this.eye); + this.rotationAngle = this.pointEnd.angleTo(this.pointStart); + this._startNorm.copy(this.pointStart).normalize(); + this._endNorm.copy(this.pointEnd).normalize(); + this.rotationAngle *= this._endNorm.cross(this._startNorm).dot(this.eye) < 0 ? 1 : -1; + } + if (this.rotationSnap) this.rotationAngle = Math.round(this.rotationAngle / this.rotationSnap) * this.rotationSnap; + if (space === "local" && axis !== "E" && axis !== "XYZE") { + object.quaternion.copy(this._quaternionStart); + object.quaternion.multiply(_tempQuaternion.setFromAxisAngle(this.rotationAxis, this.rotationAngle)).normalize(); + } else { + this.rotationAxis.applyQuaternion(this._parentQuaternionInv); + object.quaternion.copy(_tempQuaternion.setFromAxisAngle(this.rotationAxis, this.rotationAngle)); + object.quaternion.multiply(this._quaternionStart).normalize(); + } + } + this.dispatchEvent(_changeEvent2); + this.dispatchEvent(_objectChangeEvent); + } + pointerUp(pointer) { + if (pointer.button !== 0) return; + if (this.dragging && this.axis !== null) { + _mouseUpEvent.mode = this.mode; + this.dispatchEvent(_mouseUpEvent); + } + this.dragging = false; + this.axis = null; + } + dispose() { + this.domElement.removeEventListener("pointerdown", this._onPointerDown); + this.domElement.removeEventListener("pointermove", this._onPointerHover); + this.domElement.removeEventListener("pointermove", this._onPointerMove); + this.domElement.removeEventListener("pointerup", this._onPointerUp); + this.traverse(function(child) { + if (child.geometry) child.geometry.dispose(); + if (child.material) child.material.dispose(); + }); + } + // Set current object + attach(object) { + this.object = object; + this.visible = true; + return this; + } + // Detach from object + detach() { + this.object = void 0; + this.visible = false; + this.axis = null; + return this; + } + reset() { + if (!this.enabled) return; + if (this.dragging) { + this.object.position.copy(this._positionStart); + this.object.quaternion.copy(this._quaternionStart); + this.object.scale.copy(this._scaleStart); + this.dispatchEvent(_changeEvent2); + this.dispatchEvent(_objectChangeEvent); + this.pointStart.copy(this.pointEnd); + } + } + getRaycaster() { + return _raycaster; + } + // TODO: deprecate + getMode() { + return this.mode; + } + setMode(mode) { + this.mode = mode; + } + setTranslationSnap(translationSnap) { + this.translationSnap = translationSnap; + } + setRotationSnap(rotationSnap) { + this.rotationSnap = rotationSnap; + } + setScaleSnap(scaleSnap) { + this.scaleSnap = scaleSnap; + } + setSize(size) { + this.size = size; + } + setSpace(space) { + this.space = space; + } + }; + function getPointer(event) { + if (this.domElement.ownerDocument.pointerLockElement) { + return { + x: 0, + y: 0, + button: event.button + }; + } else { + const rect = this.domElement.getBoundingClientRect(); + return { + x: (event.clientX - rect.left) / rect.width * 2 - 1, + y: -(event.clientY - rect.top) / rect.height * 2 + 1, + button: event.button + }; + } + } + function onPointerHover(event) { + if (!this.enabled) return; + switch (event.pointerType) { + case "mouse": + case "pen": + this.pointerHover(this._getPointer(event)); + break; + } + } + function onPointerDown(event) { + if (!this.enabled) return; + if (!document.pointerLockElement) { + this.domElement.setPointerCapture(event.pointerId); + } + this.domElement.addEventListener("pointermove", this._onPointerMove); + this.pointerHover(this._getPointer(event)); + this.pointerDown(this._getPointer(event)); + } + function onPointerMove(event) { + if (!this.enabled) return; + this.pointerMove(this._getPointer(event)); + } + function onPointerUp(event) { + if (!this.enabled) return; + this.domElement.releasePointerCapture(event.pointerId); + this.domElement.removeEventListener("pointermove", this._onPointerMove); + this.pointerUp(this._getPointer(event)); + } + function intersectObjectWithRay(object, raycaster, includeInvisible) { + const allIntersections = raycaster.intersectObject(object, true); + for (let i = 0; i < allIntersections.length; i++) { + if (allIntersections[i].object.visible || includeInvisible) { + return allIntersections[i]; + } + } + return false; + } + var _tempEuler = new Euler(); + var _alignVector = new Vector3(0, 1, 0); + var _zeroVector = new Vector3(0, 0, 0); + var _lookAtMatrix = new Matrix4(); + var _tempQuaternion2 = new Quaternion(); + var _identityQuaternion = new Quaternion(); + var _dirVector = new Vector3(); + var _tempMatrix = new Matrix4(); + var _unitX = new Vector3(1, 0, 0); + var _unitY = new Vector3(0, 1, 0); + var _unitZ = new Vector3(0, 0, 1); + var _v12 = new Vector3(); + var _v22 = new Vector3(); + var _v32 = new Vector3(); + var TransformControlsGizmo = class extends Object3D { + constructor() { + super(); + this.isTransformControlsGizmo = true; + this.type = "TransformControlsGizmo"; + const gizmoMaterial = new MeshBasicMaterial({ + depthTest: false, + depthWrite: false, + fog: false, + toneMapped: false, + transparent: true + }); + const gizmoLineMaterial = new LineBasicMaterial({ + depthTest: false, + depthWrite: false, + fog: false, + toneMapped: false, + transparent: true + }); + const matInvisible = gizmoMaterial.clone(); + matInvisible.opacity = 0.15; + const matHelper = gizmoLineMaterial.clone(); + matHelper.opacity = 0.5; + const matRed = gizmoMaterial.clone(); + matRed.color.setHex(16711680); + const matGreen = gizmoMaterial.clone(); + matGreen.color.setHex(65280); + const matBlue = gizmoMaterial.clone(); + matBlue.color.setHex(255); + const matRedTransparent = gizmoMaterial.clone(); + matRedTransparent.color.setHex(16711680); + matRedTransparent.opacity = 0.5; + const matGreenTransparent = gizmoMaterial.clone(); + matGreenTransparent.color.setHex(65280); + matGreenTransparent.opacity = 0.5; + const matBlueTransparent = gizmoMaterial.clone(); + matBlueTransparent.color.setHex(255); + matBlueTransparent.opacity = 0.5; + const matWhiteTransparent = gizmoMaterial.clone(); + matWhiteTransparent.opacity = 0.25; + const matYellowTransparent = gizmoMaterial.clone(); + matYellowTransparent.color.setHex(16776960); + matYellowTransparent.opacity = 0.25; + const matYellow = gizmoMaterial.clone(); + matYellow.color.setHex(16776960); + const matGray = gizmoMaterial.clone(); + matGray.color.setHex(7895160); + const arrowGeometry = new CylinderGeometry(0, 0.04, 0.1, 12); + arrowGeometry.translate(0, 0.05, 0); + const scaleHandleGeometry = new BoxGeometry(0.08, 0.08, 0.08); + scaleHandleGeometry.translate(0, 0.04, 0); + const lineGeometry = new BufferGeometry(); + lineGeometry.setAttribute("position", new Float32BufferAttribute([0, 0, 0, 1, 0, 0], 3)); + const lineGeometry2 = new CylinderGeometry(75e-4, 75e-4, 0.5, 3); + lineGeometry2.translate(0, 0.25, 0); + function CircleGeometry2(radius, arc) { + const geometry = new TorusGeometry(radius, 75e-4, 3, 64, arc * Math.PI * 2); + geometry.rotateY(Math.PI / 2); + geometry.rotateX(Math.PI / 2); + return geometry; + } + function TranslateHelperGeometry() { + const geometry = new BufferGeometry(); + geometry.setAttribute("position", new Float32BufferAttribute([0, 0, 0, 1, 1, 1], 3)); + return geometry; + } + const gizmoTranslate = { + X: [ + [new Mesh(arrowGeometry, matRed), [0.5, 0, 0], [0, 0, -Math.PI / 2]], + [new Mesh(arrowGeometry, matRed), [-0.5, 0, 0], [0, 0, Math.PI / 2]], + [new Mesh(lineGeometry2, matRed), [0, 0, 0], [0, 0, -Math.PI / 2]] + ], + Y: [ + [new Mesh(arrowGeometry, matGreen), [0, 0.5, 0]], + [new Mesh(arrowGeometry, matGreen), [0, -0.5, 0], [Math.PI, 0, 0]], + [new Mesh(lineGeometry2, matGreen)] + ], + Z: [ + [new Mesh(arrowGeometry, matBlue), [0, 0, 0.5], [Math.PI / 2, 0, 0]], + [new Mesh(arrowGeometry, matBlue), [0, 0, -0.5], [-Math.PI / 2, 0, 0]], + [new Mesh(lineGeometry2, matBlue), null, [Math.PI / 2, 0, 0]] + ], + XYZ: [ + [new Mesh(new OctahedronGeometry(0.1, 0), matWhiteTransparent.clone()), [0, 0, 0]] + ], + XY: [ + [new Mesh(new BoxGeometry(0.15, 0.15, 0.01), matBlueTransparent.clone()), [0.15, 0.15, 0]] + ], + YZ: [ + [new Mesh(new BoxGeometry(0.15, 0.15, 0.01), matRedTransparent.clone()), [0, 0.15, 0.15], [0, Math.PI / 2, 0]] + ], + XZ: [ + [new Mesh(new BoxGeometry(0.15, 0.15, 0.01), matGreenTransparent.clone()), [0.15, 0, 0.15], [-Math.PI / 2, 0, 0]] + ] + }; + const pickerTranslate = { + X: [ + [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0.3, 0, 0], [0, 0, -Math.PI / 2]], + [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [-0.3, 0, 0], [0, 0, Math.PI / 2]] + ], + Y: [ + [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, 0.3, 0]], + [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, -0.3, 0], [0, 0, Math.PI]] + ], + Z: [ + [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, 0, 0.3], [Math.PI / 2, 0, 0]], + [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, 0, -0.3], [-Math.PI / 2, 0, 0]] + ], + XYZ: [ + [new Mesh(new OctahedronGeometry(0.2, 0), matInvisible)] + ], + XY: [ + [new Mesh(new BoxGeometry(0.2, 0.2, 0.01), matInvisible), [0.15, 0.15, 0]] + ], + YZ: [ + [new Mesh(new BoxGeometry(0.2, 0.2, 0.01), matInvisible), [0, 0.15, 0.15], [0, Math.PI / 2, 0]] + ], + XZ: [ + [new Mesh(new BoxGeometry(0.2, 0.2, 0.01), matInvisible), [0.15, 0, 0.15], [-Math.PI / 2, 0, 0]] + ] + }; + const helperTranslate = { + START: [ + [new Mesh(new OctahedronGeometry(0.01, 2), matHelper), null, null, null, "helper"] + ], + END: [ + [new Mesh(new OctahedronGeometry(0.01, 2), matHelper), null, null, null, "helper"] + ], + DELTA: [ + [new Line(TranslateHelperGeometry(), matHelper), null, null, null, "helper"] + ], + X: [ + [new Line(lineGeometry, matHelper.clone()), [-1e3, 0, 0], null, [1e6, 1, 1], "helper"] + ], + Y: [ + [new Line(lineGeometry, matHelper.clone()), [0, -1e3, 0], [0, 0, Math.PI / 2], [1e6, 1, 1], "helper"] + ], + Z: [ + [new Line(lineGeometry, matHelper.clone()), [0, 0, -1e3], [0, -Math.PI / 2, 0], [1e6, 1, 1], "helper"] + ] + }; + const gizmoRotate = { + XYZE: [ + [new Mesh(CircleGeometry2(0.5, 1), matGray), null, [0, Math.PI / 2, 0]] + ], + X: [ + [new Mesh(CircleGeometry2(0.5, 0.5), matRed)] + ], + Y: [ + [new Mesh(CircleGeometry2(0.5, 0.5), matGreen), null, [0, 0, -Math.PI / 2]] + ], + Z: [ + [new Mesh(CircleGeometry2(0.5, 0.5), matBlue), null, [0, Math.PI / 2, 0]] + ], + E: [ + [new Mesh(CircleGeometry2(0.75, 1), matYellowTransparent), null, [0, Math.PI / 2, 0]] + ] + }; + const helperRotate = { + AXIS: [ + [new Line(lineGeometry, matHelper.clone()), [-1e3, 0, 0], null, [1e6, 1, 1], "helper"] + ] + }; + const pickerRotate = { + XYZE: [ + [new Mesh(new SphereGeometry(0.25, 10, 8), matInvisible)] + ], + X: [ + [new Mesh(new TorusGeometry(0.5, 0.1, 4, 24), matInvisible), [0, 0, 0], [0, -Math.PI / 2, -Math.PI / 2]] + ], + Y: [ + [new Mesh(new TorusGeometry(0.5, 0.1, 4, 24), matInvisible), [0, 0, 0], [Math.PI / 2, 0, 0]] + ], + Z: [ + [new Mesh(new TorusGeometry(0.5, 0.1, 4, 24), matInvisible), [0, 0, 0], [0, 0, -Math.PI / 2]] + ], + E: [ + [new Mesh(new TorusGeometry(0.75, 0.1, 2, 24), matInvisible)] + ] + }; + const gizmoScale = { + X: [ + [new Mesh(scaleHandleGeometry, matRed), [0.5, 0, 0], [0, 0, -Math.PI / 2]], + [new Mesh(lineGeometry2, matRed), [0, 0, 0], [0, 0, -Math.PI / 2]], + [new Mesh(scaleHandleGeometry, matRed), [-0.5, 0, 0], [0, 0, Math.PI / 2]] + ], + Y: [ + [new Mesh(scaleHandleGeometry, matGreen), [0, 0.5, 0]], + [new Mesh(lineGeometry2, matGreen)], + [new Mesh(scaleHandleGeometry, matGreen), [0, -0.5, 0], [0, 0, Math.PI]] + ], + Z: [ + [new Mesh(scaleHandleGeometry, matBlue), [0, 0, 0.5], [Math.PI / 2, 0, 0]], + [new Mesh(lineGeometry2, matBlue), [0, 0, 0], [Math.PI / 2, 0, 0]], + [new Mesh(scaleHandleGeometry, matBlue), [0, 0, -0.5], [-Math.PI / 2, 0, 0]] + ], + XY: [ + [new Mesh(new BoxGeometry(0.15, 0.15, 0.01), matBlueTransparent), [0.15, 0.15, 0]] + ], + YZ: [ + [new Mesh(new BoxGeometry(0.15, 0.15, 0.01), matRedTransparent), [0, 0.15, 0.15], [0, Math.PI / 2, 0]] + ], + XZ: [ + [new Mesh(new BoxGeometry(0.15, 0.15, 0.01), matGreenTransparent), [0.15, 0, 0.15], [-Math.PI / 2, 0, 0]] + ], + XYZ: [ + [new Mesh(new BoxGeometry(0.1, 0.1, 0.1), matWhiteTransparent.clone())] + ] + }; + const pickerScale = { + X: [ + [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0.3, 0, 0], [0, 0, -Math.PI / 2]], + [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [-0.3, 0, 0], [0, 0, Math.PI / 2]] + ], + Y: [ + [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, 0.3, 0]], + [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, -0.3, 0], [0, 0, Math.PI]] + ], + Z: [ + [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, 0, 0.3], [Math.PI / 2, 0, 0]], + [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, 0, -0.3], [-Math.PI / 2, 0, 0]] + ], + XY: [ + [new Mesh(new BoxGeometry(0.2, 0.2, 0.01), matInvisible), [0.15, 0.15, 0]] + ], + YZ: [ + [new Mesh(new BoxGeometry(0.2, 0.2, 0.01), matInvisible), [0, 0.15, 0.15], [0, Math.PI / 2, 0]] + ], + XZ: [ + [new Mesh(new BoxGeometry(0.2, 0.2, 0.01), matInvisible), [0.15, 0, 0.15], [-Math.PI / 2, 0, 0]] + ], + XYZ: [ + [new Mesh(new BoxGeometry(0.2, 0.2, 0.2), matInvisible), [0, 0, 0]] + ] + }; + const helperScale = { + X: [ + [new Line(lineGeometry, matHelper.clone()), [-1e3, 0, 0], null, [1e6, 1, 1], "helper"] + ], + Y: [ + [new Line(lineGeometry, matHelper.clone()), [0, -1e3, 0], [0, 0, Math.PI / 2], [1e6, 1, 1], "helper"] + ], + Z: [ + [new Line(lineGeometry, matHelper.clone()), [0, 0, -1e3], [0, -Math.PI / 2, 0], [1e6, 1, 1], "helper"] + ] + }; + function setupGizmo(gizmoMap) { + const gizmo = new Object3D(); + for (const name in gizmoMap) { + for (let i = gizmoMap[name].length; i--; ) { + const object = gizmoMap[name][i][0].clone(); + const position = gizmoMap[name][i][1]; + const rotation = gizmoMap[name][i][2]; + const scale = gizmoMap[name][i][3]; + const tag = gizmoMap[name][i][4]; + object.name = name; + object.tag = tag; + if (position) { + object.position.set(position[0], position[1], position[2]); + } + if (rotation) { + object.rotation.set(rotation[0], rotation[1], rotation[2]); + } + if (scale) { + object.scale.set(scale[0], scale[1], scale[2]); + } + object.updateMatrix(); + const tempGeometry = object.geometry.clone(); + tempGeometry.applyMatrix4(object.matrix); + object.geometry = tempGeometry; + object.renderOrder = Infinity; + object.position.set(0, 0, 0); + object.rotation.set(0, 0, 0); + object.scale.set(1, 1, 1); + gizmo.add(object); + } + } + return gizmo; + } + this.gizmo = {}; + this.picker = {}; + this.helper = {}; + this.add(this.gizmo["translate"] = setupGizmo(gizmoTranslate)); + this.add(this.gizmo["rotate"] = setupGizmo(gizmoRotate)); + this.add(this.gizmo["scale"] = setupGizmo(gizmoScale)); + this.add(this.picker["translate"] = setupGizmo(pickerTranslate)); + this.add(this.picker["rotate"] = setupGizmo(pickerRotate)); + this.add(this.picker["scale"] = setupGizmo(pickerScale)); + this.add(this.helper["translate"] = setupGizmo(helperTranslate)); + this.add(this.helper["rotate"] = setupGizmo(helperRotate)); + this.add(this.helper["scale"] = setupGizmo(helperScale)); + this.picker["translate"].visible = false; + this.picker["rotate"].visible = false; + this.picker["scale"].visible = false; + } + // updateMatrixWorld will update transformations and appearance of individual handles + updateMatrixWorld(force) { + const space = this.mode === "scale" ? "local" : this.space; + const quaternion = space === "local" ? this.worldQuaternion : _identityQuaternion; + this.gizmo["translate"].visible = this.mode === "translate"; + this.gizmo["rotate"].visible = this.mode === "rotate"; + this.gizmo["scale"].visible = this.mode === "scale"; + this.helper["translate"].visible = this.mode === "translate"; + this.helper["rotate"].visible = this.mode === "rotate"; + this.helper["scale"].visible = this.mode === "scale"; + let handles = []; + handles = handles.concat(this.picker[this.mode].children); + handles = handles.concat(this.gizmo[this.mode].children); + handles = handles.concat(this.helper[this.mode].children); + for (let i = 0; i < handles.length; i++) { + const handle = handles[i]; + handle.visible = true; + handle.rotation.set(0, 0, 0); + handle.position.copy(this.worldPosition); + let factor; + if (this.camera.isOrthographicCamera) { + factor = (this.camera.top - this.camera.bottom) / this.camera.zoom; + } else { + factor = this.worldPosition.distanceTo(this.cameraPosition) * Math.min(1.9 * Math.tan(Math.PI * this.camera.fov / 360) / this.camera.zoom, 7); + } + handle.scale.set(1, 1, 1).multiplyScalar(factor * this.size / 4); + if (handle.tag === "helper") { + handle.visible = false; + if (handle.name === "AXIS") { + handle.visible = !!this.axis; + if (this.axis === "X") { + _tempQuaternion.setFromEuler(_tempEuler.set(0, 0, 0)); + handle.quaternion.copy(quaternion).multiply(_tempQuaternion); + if (Math.abs(_alignVector.copy(_unitX).applyQuaternion(quaternion).dot(this.eye)) > 0.9) { + handle.visible = false; + } + } + if (this.axis === "Y") { + _tempQuaternion.setFromEuler(_tempEuler.set(0, 0, Math.PI / 2)); + handle.quaternion.copy(quaternion).multiply(_tempQuaternion); + if (Math.abs(_alignVector.copy(_unitY).applyQuaternion(quaternion).dot(this.eye)) > 0.9) { + handle.visible = false; + } + } + if (this.axis === "Z") { + _tempQuaternion.setFromEuler(_tempEuler.set(0, Math.PI / 2, 0)); + handle.quaternion.copy(quaternion).multiply(_tempQuaternion); + if (Math.abs(_alignVector.copy(_unitZ).applyQuaternion(quaternion).dot(this.eye)) > 0.9) { + handle.visible = false; + } + } + if (this.axis === "XYZE") { + _tempQuaternion.setFromEuler(_tempEuler.set(0, Math.PI / 2, 0)); + _alignVector.copy(this.rotationAxis); + handle.quaternion.setFromRotationMatrix(_lookAtMatrix.lookAt(_zeroVector, _alignVector, _unitY)); + handle.quaternion.multiply(_tempQuaternion); + handle.visible = this.dragging; + } + if (this.axis === "E") { + handle.visible = false; + } + } else if (handle.name === "START") { + handle.position.copy(this.worldPositionStart); + handle.visible = this.dragging; + } else if (handle.name === "END") { + handle.position.copy(this.worldPosition); + handle.visible = this.dragging; + } else if (handle.name === "DELTA") { + handle.position.copy(this.worldPositionStart); + handle.quaternion.copy(this.worldQuaternionStart); + _tempVector.set(1e-10, 1e-10, 1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1); + _tempVector.applyQuaternion(this.worldQuaternionStart.clone().invert()); + handle.scale.copy(_tempVector); + handle.visible = this.dragging; + } else { + handle.quaternion.copy(quaternion); + if (this.dragging) { + handle.position.copy(this.worldPositionStart); + } else { + handle.position.copy(this.worldPosition); + } + if (this.axis) { + handle.visible = this.axis.search(handle.name) !== -1; + } + } + continue; + } + handle.quaternion.copy(quaternion); + if (this.mode === "translate" || this.mode === "scale") { + const AXIS_HIDE_THRESHOLD = 0.99; + const PLANE_HIDE_THRESHOLD = 0.2; + if (handle.name === "X") { + if (Math.abs(_alignVector.copy(_unitX).applyQuaternion(quaternion).dot(this.eye)) > AXIS_HIDE_THRESHOLD) { + handle.scale.set(1e-10, 1e-10, 1e-10); + handle.visible = false; + } + } + if (handle.name === "Y") { + if (Math.abs(_alignVector.copy(_unitY).applyQuaternion(quaternion).dot(this.eye)) > AXIS_HIDE_THRESHOLD) { + handle.scale.set(1e-10, 1e-10, 1e-10); + handle.visible = false; + } + } + if (handle.name === "Z") { + if (Math.abs(_alignVector.copy(_unitZ).applyQuaternion(quaternion).dot(this.eye)) > AXIS_HIDE_THRESHOLD) { + handle.scale.set(1e-10, 1e-10, 1e-10); + handle.visible = false; + } + } + if (handle.name === "XY") { + if (Math.abs(_alignVector.copy(_unitZ).applyQuaternion(quaternion).dot(this.eye)) < PLANE_HIDE_THRESHOLD) { + handle.scale.set(1e-10, 1e-10, 1e-10); + handle.visible = false; + } + } + if (handle.name === "YZ") { + if (Math.abs(_alignVector.copy(_unitX).applyQuaternion(quaternion).dot(this.eye)) < PLANE_HIDE_THRESHOLD) { + handle.scale.set(1e-10, 1e-10, 1e-10); + handle.visible = false; + } + } + if (handle.name === "XZ") { + if (Math.abs(_alignVector.copy(_unitY).applyQuaternion(quaternion).dot(this.eye)) < PLANE_HIDE_THRESHOLD) { + handle.scale.set(1e-10, 1e-10, 1e-10); + handle.visible = false; + } + } + } else if (this.mode === "rotate") { + _tempQuaternion2.copy(quaternion); + _alignVector.copy(this.eye).applyQuaternion(_tempQuaternion.copy(quaternion).invert()); + if (handle.name.search("E") !== -1) { + handle.quaternion.setFromRotationMatrix(_lookAtMatrix.lookAt(this.eye, _zeroVector, _unitY)); + } + if (handle.name === "X") { + _tempQuaternion.setFromAxisAngle(_unitX, Math.atan2(-_alignVector.y, _alignVector.z)); + _tempQuaternion.multiplyQuaternions(_tempQuaternion2, _tempQuaternion); + handle.quaternion.copy(_tempQuaternion); + } + if (handle.name === "Y") { + _tempQuaternion.setFromAxisAngle(_unitY, Math.atan2(_alignVector.x, _alignVector.z)); + _tempQuaternion.multiplyQuaternions(_tempQuaternion2, _tempQuaternion); + handle.quaternion.copy(_tempQuaternion); + } + if (handle.name === "Z") { + _tempQuaternion.setFromAxisAngle(_unitZ, Math.atan2(_alignVector.y, _alignVector.x)); + _tempQuaternion.multiplyQuaternions(_tempQuaternion2, _tempQuaternion); + handle.quaternion.copy(_tempQuaternion); + } + } + handle.visible = handle.visible && (handle.name.indexOf("X") === -1 || this.showX); + handle.visible = handle.visible && (handle.name.indexOf("Y") === -1 || this.showY); + handle.visible = handle.visible && (handle.name.indexOf("Z") === -1 || this.showZ); + handle.visible = handle.visible && (handle.name.indexOf("E") === -1 || this.showX && this.showY && this.showZ); + handle.material._color = handle.material._color || handle.material.color.clone(); + handle.material._opacity = handle.material._opacity || handle.material.opacity; + handle.material.color.copy(handle.material._color); + handle.material.opacity = handle.material._opacity; + if (this.enabled && this.axis) { + if (handle.name === this.axis) { + handle.material.color.setHex(16776960); + handle.material.opacity = 1; + } else if (this.axis.split("").some(function(a) { + return handle.name === a; + })) { + handle.material.color.setHex(16776960); + handle.material.opacity = 1; + } + } + } + super.updateMatrixWorld(force); + } + }; + var TransformControlsPlane = class extends Mesh { + constructor() { + super( + new PlaneGeometry(1e5, 1e5, 2, 2), + new MeshBasicMaterial({ visible: false, wireframe: true, side: DoubleSide, transparent: true, opacity: 0.1, toneMapped: false }) + ); + this.isTransformControlsPlane = true; + this.type = "TransformControlsPlane"; + } + updateMatrixWorld(force) { + let space = this.space; + this.position.copy(this.worldPosition); + if (this.mode === "scale") space = "local"; + _v12.copy(_unitX).applyQuaternion(space === "local" ? this.worldQuaternion : _identityQuaternion); + _v22.copy(_unitY).applyQuaternion(space === "local" ? this.worldQuaternion : _identityQuaternion); + _v32.copy(_unitZ).applyQuaternion(space === "local" ? this.worldQuaternion : _identityQuaternion); + _alignVector.copy(_v22); + switch (this.mode) { + case "translate": + case "scale": + switch (this.axis) { + case "X": + _alignVector.copy(this.eye).cross(_v12); + _dirVector.copy(_v12).cross(_alignVector); + break; + case "Y": + _alignVector.copy(this.eye).cross(_v22); + _dirVector.copy(_v22).cross(_alignVector); + break; + case "Z": + _alignVector.copy(this.eye).cross(_v32); + _dirVector.copy(_v32).cross(_alignVector); + break; + case "XY": + _dirVector.copy(_v32); + break; + case "YZ": + _dirVector.copy(_v12); + break; + case "XZ": + _alignVector.copy(_v32); + _dirVector.copy(_v22); + break; + case "XYZ": + case "E": + _dirVector.set(0, 0, 0); + break; + } + break; + case "rotate": + default: + _dirVector.set(0, 0, 0); + } + if (_dirVector.length() === 0) { + this.quaternion.copy(this.cameraQuaternion); + } else { + _tempMatrix.lookAt(_tempVector.set(0, 0, 0), _dirVector, _alignVector); + this.quaternion.setFromRotationMatrix(_tempMatrix); + } + super.updateMatrixWorld(force); + } + }; + + // examples/jsm/libs/fflate.module.js + var durl = function(c) { + return URL.createObjectURL(new Blob([c], { type: "text/javascript" })); + }; + var cwk = function(u) { + return new Worker(u); + }; + try { + URL.revokeObjectURL(durl("")); + } catch (e) { + durl = function(c) { + return "data:application/javascript;charset=UTF-8," + encodeURI(c); + }; + cwk = function(u) { + return new Worker(u, { type: "module" }); + }; + } + var u8 = Uint8Array; + var u16 = Uint16Array; + var u32 = Uint32Array; + var fleb = new u8([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 2, + 2, + 2, + 2, + 3, + 3, + 3, + 3, + 4, + 4, + 4, + 4, + 5, + 5, + 5, + 5, + 0, + /* unused */ + 0, + 0, + /* impossible */ + 0 + ]); + var fdeb = new u8([ + 0, + 0, + 0, + 0, + 1, + 1, + 2, + 2, + 3, + 3, + 4, + 4, + 5, + 5, + 6, + 6, + 7, + 7, + 8, + 8, + 9, + 9, + 10, + 10, + 11, + 11, + 12, + 12, + 13, + 13, + /* unused */ + 0, + 0 + ]); + var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]); + var freb = function(eb, start) { + var b = new u16(31); + for (var i = 0; i < 31; ++i) { + b[i] = start += 1 << eb[i - 1]; + } + var r = new u32(b[30]); + for (var i = 1; i < 30; ++i) { + for (var j = b[i]; j < b[i + 1]; ++j) { + r[j] = j - b[i] << 5 | i; + } + } + return [b, r]; + }; + var _a = freb(fleb, 2); + var fl = _a[0]; + var revfl = _a[1]; + fl[28] = 258, revfl[258] = 28; + var _b = freb(fdeb, 0); + var fd = _b[0]; + var revfd = _b[1]; + var rev = new u16(32768); + for (i = 0; i < 32768; ++i) { + x = (i & 43690) >>> 1 | (i & 21845) << 1; + x = (x & 52428) >>> 2 | (x & 13107) << 2; + x = (x & 61680) >>> 4 | (x & 3855) << 4; + rev[i] = ((x & 65280) >>> 8 | (x & 255) << 8) >>> 1; + } + var x; + var i; + var hMap = (function(cd, mb, r) { + var s = cd.length; + var i = 0; + var l = new u16(mb); + for (; i < s; ++i) + ++l[cd[i] - 1]; + var le = new u16(mb); + for (i = 0; i < mb; ++i) { + le[i] = le[i - 1] + l[i - 1] << 1; + } + var co; + if (r) { + co = new u16(1 << mb); + var rvb = 15 - mb; + for (i = 0; i < s; ++i) { + if (cd[i]) { + var sv = i << 4 | cd[i]; + var r_1 = mb - cd[i]; + var v = le[cd[i] - 1]++ << r_1; + for (var m = v | (1 << r_1) - 1; v <= m; ++v) { + co[rev[v] >>> rvb] = sv; + } + } + } + } else { + co = new u16(s); + for (i = 0; i < s; ++i) { + if (cd[i]) { + co[i] = rev[le[cd[i] - 1]++] >>> 15 - cd[i]; + } + } + } + return co; + }); + var flt = new u8(288); + for (i = 0; i < 144; ++i) + flt[i] = 8; + var i; + for (i = 144; i < 256; ++i) + flt[i] = 9; + var i; + for (i = 256; i < 280; ++i) + flt[i] = 7; + var i; + for (i = 280; i < 288; ++i) + flt[i] = 8; + var i; + var fdt = new u8(32); + for (i = 0; i < 32; ++i) + fdt[i] = 5; + var i; + var flrm = /* @__PURE__ */ hMap(flt, 9, 1); + var fdrm = /* @__PURE__ */ hMap(fdt, 5, 1); + var max = function(a) { + var m = a[0]; + for (var i = 1; i < a.length; ++i) { + if (a[i] > m) + m = a[i]; + } + return m; + }; + var bits = function(d, p, m) { + var o = p / 8 | 0; + return (d[o] | d[o + 1] << 8) >> (p & 7) & m; + }; + var bits16 = function(d, p) { + var o = p / 8 | 0; + return (d[o] | d[o + 1] << 8 | d[o + 2] << 16) >> (p & 7); + }; + var shft = function(p) { + return (p / 8 | 0) + (p & 7 && 1); + }; + var slc = function(v, s, e) { + if (s == null || s < 0) + s = 0; + if (e == null || e > v.length) + e = v.length; + var n = new (v instanceof u16 ? u16 : v instanceof u32 ? u32 : u8)(e - s); + n.set(v.subarray(s, e)); + return n; + }; + var inflt = function(dat, buf, st) { + var sl = dat.length; + if (!sl || st && !st.l && sl < 5) + return buf || new u8(0); + var noBuf = !buf || st; + var noSt = !st || st.i; + if (!st) + st = {}; + if (!buf) + buf = new u8(sl * 3); + var cbuf = function(l2) { + var bl = buf.length; + if (l2 > bl) { + var nbuf = new u8(Math.max(bl * 2, l2)); + nbuf.set(buf); + buf = nbuf; + } + }; + var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n; + var tbts = sl * 8; + do { + if (!lm) { + st.f = final = bits(dat, pos, 1); + var type = bits(dat, pos + 1, 3); + pos += 3; + if (!type) { + var s = shft(pos) + 4, l = dat[s - 4] | dat[s - 3] << 8, t = s + l; + if (t > sl) { + if (noSt) + throw "unexpected EOF"; + break; + } + if (noBuf) + cbuf(bt + l); + buf.set(dat.subarray(s, t), bt); + st.b = bt += l, st.p = pos = t * 8; + continue; + } else if (type == 1) + lm = flrm, dm = fdrm, lbt = 9, dbt = 5; + else if (type == 2) { + var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4; + var tl = hLit + bits(dat, pos + 5, 31) + 1; + pos += 14; + var ldt = new u8(tl); + var clt = new u8(19); + for (var i = 0; i < hcLen; ++i) { + clt[clim[i]] = bits(dat, pos + i * 3, 7); + } + pos += hcLen * 3; + var clb = max(clt), clbmsk = (1 << clb) - 1; + var clm = hMap(clt, clb, 1); + for (var i = 0; i < tl; ) { + var r = clm[bits(dat, pos, clbmsk)]; + pos += r & 15; + var s = r >>> 4; + if (s < 16) { + ldt[i++] = s; + } else { + var c = 0, n = 0; + if (s == 16) + n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1]; + else if (s == 17) + n = 3 + bits(dat, pos, 7), pos += 3; + else if (s == 18) + n = 11 + bits(dat, pos, 127), pos += 7; + while (n--) + ldt[i++] = c; + } + } + var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit); + lbt = max(lt); + dbt = max(dt); + lm = hMap(lt, lbt, 1); + dm = hMap(dt, dbt, 1); + } else + throw "invalid block type"; + if (pos > tbts) { + if (noSt) + throw "unexpected EOF"; + break; + } + } + if (noBuf) + cbuf(bt + 131072); + var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1; + var lpos = pos; + for (; ; lpos = pos) { + var c = lm[bits16(dat, pos) & lms], sym = c >>> 4; + pos += c & 15; + if (pos > tbts) { + if (noSt) + throw "unexpected EOF"; + break; + } + if (!c) + throw "invalid length/literal"; + if (sym < 256) + buf[bt++] = sym; + else if (sym == 256) { + lpos = pos, lm = null; + break; + } else { + var add = sym - 254; + if (sym > 264) { + var i = sym - 257, b = fleb[i]; + add = bits(dat, pos, (1 << b) - 1) + fl[i]; + pos += b; + } + var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4; + if (!d) + throw "invalid distance"; + pos += d & 15; + var dt = fd[dsym]; + if (dsym > 3) { + var b = fdeb[dsym]; + dt += bits16(dat, pos) & (1 << b) - 1, pos += b; + } + if (pos > tbts) { + if (noSt) + throw "unexpected EOF"; + break; + } + if (noBuf) + cbuf(bt + 131072); + var end = bt + add; + for (; bt < end; bt += 4) { + buf[bt] = buf[bt - dt]; + buf[bt + 1] = buf[bt + 1 - dt]; + buf[bt + 2] = buf[bt + 2 - dt]; + buf[bt + 3] = buf[bt + 3 - dt]; + } + bt = end; + } + } + st.l = lm, st.p = lpos, st.b = bt; + if (lm) + final = 1, st.m = lbt, st.d = dm, st.n = dbt; + } while (!final); + return bt == buf.length ? buf : slc(buf, 0, bt); + }; + var et = /* @__PURE__ */ new u8(0); + var zlv = function(d) { + if ((d[0] & 15) != 8 || d[0] >>> 4 > 7 || (d[0] << 8 | d[1]) % 31) + throw "invalid zlib data"; + if (d[1] & 32) + throw "invalid zlib data: preset dictionaries not supported"; + }; + function unzlibSync(data, out) { + return inflt((zlv(data), data.subarray(2, -4)), out); + } + var td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder(); + var tds = 0; + try { + td.decode(et, { stream: true }); + tds = 1; + } catch (e) { + } + + // examples/jsm/curves/NURBSUtils.js + function findSpan(p, u, U) { + const n = U.length - p - 1; + if (u >= U[n]) { + return n - 1; + } + if (u <= U[p]) { + return p; + } + let low = p; + let high = n; + let mid = Math.floor((low + high) / 2); + while (u < U[mid] || u >= U[mid + 1]) { + if (u < U[mid]) { + high = mid; + } else { + low = mid; + } + mid = Math.floor((low + high) / 2); + } + return mid; + } + function calcBasisFunctions(span, u, p, U) { + const N = []; + const left = []; + const right = []; + N[0] = 1; + for (let j = 1; j <= p; ++j) { + left[j] = u - U[span + 1 - j]; + right[j] = U[span + j] - u; + let saved = 0; + for (let r = 0; r < j; ++r) { + const rv = right[r + 1]; + const lv = left[j - r]; + const temp = N[r] / (rv + lv); + N[r] = saved + rv * temp; + saved = lv * temp; + } + N[j] = saved; + } + return N; + } + function calcBSplinePoint(p, U, P, u) { + const span = findSpan(p, u, U); + const N = calcBasisFunctions(span, u, p, U); + const C = new Vector4(0, 0, 0, 0); + for (let j = 0; j <= p; ++j) { + const point = P[span - p + j]; + const Nj = N[j]; + const wNj = point.w * Nj; + C.x += point.x * wNj; + C.y += point.y * wNj; + C.z += point.z * wNj; + C.w += point.w * Nj; + } + return C; + } + function calcBasisFunctionDerivatives(span, u, p, n, U) { + const zeroArr = []; + for (let i = 0; i <= p; ++i) + zeroArr[i] = 0; + const ders = []; + for (let i = 0; i <= n; ++i) + ders[i] = zeroArr.slice(0); + const ndu = []; + for (let i = 0; i <= p; ++i) + ndu[i] = zeroArr.slice(0); + ndu[0][0] = 1; + const left = zeroArr.slice(0); + const right = zeroArr.slice(0); + for (let j = 1; j <= p; ++j) { + left[j] = u - U[span + 1 - j]; + right[j] = U[span + j] - u; + let saved = 0; + for (let r2 = 0; r2 < j; ++r2) { + const rv = right[r2 + 1]; + const lv = left[j - r2]; + ndu[j][r2] = rv + lv; + const temp = ndu[r2][j - 1] / ndu[j][r2]; + ndu[r2][j] = saved + rv * temp; + saved = lv * temp; + } + ndu[j][j] = saved; + } + for (let j = 0; j <= p; ++j) { + ders[0][j] = ndu[j][p]; + } + for (let r2 = 0; r2 <= p; ++r2) { + let s1 = 0; + let s2 = 1; + const a = []; + for (let i = 0; i <= p; ++i) { + a[i] = zeroArr.slice(0); + } + a[0][0] = 1; + for (let k = 1; k <= n; ++k) { + let d = 0; + const rk = r2 - k; + const pk = p - k; + if (r2 >= k) { + a[s2][0] = a[s1][0] / ndu[pk + 1][rk]; + d = a[s2][0] * ndu[rk][pk]; + } + const j1 = rk >= -1 ? 1 : -rk; + const j2 = r2 - 1 <= pk ? k - 1 : p - r2; + for (let j3 = j1; j3 <= j2; ++j3) { + a[s2][j3] = (a[s1][j3] - a[s1][j3 - 1]) / ndu[pk + 1][rk + j3]; + d += a[s2][j3] * ndu[rk + j3][pk]; + } + if (r2 <= pk) { + a[s2][k] = -a[s1][k - 1] / ndu[pk + 1][r2]; + d += a[s2][k] * ndu[r2][pk]; + } + ders[k][r2] = d; + const j = s1; + s1 = s2; + s2 = j; + } + } + let r = p; + for (let k = 1; k <= n; ++k) { + for (let j = 0; j <= p; ++j) { + ders[k][j] *= r; + } + r *= p - k; + } + return ders; + } + function calcBSplineDerivatives(p, U, P, u, nd) { + const du = nd < p ? nd : p; + const CK = []; + const span = findSpan(p, u, U); + const nders = calcBasisFunctionDerivatives(span, u, p, du, U); + const Pw = []; + for (let i = 0; i < P.length; ++i) { + const point = P[i].clone(); + const w = point.w; + point.x *= w; + point.y *= w; + point.z *= w; + Pw[i] = point; + } + for (let k = 0; k <= du; ++k) { + const point = Pw[span - p].clone().multiplyScalar(nders[k][0]); + for (let j = 1; j <= p; ++j) { + point.add(Pw[span - p + j].clone().multiplyScalar(nders[k][j])); + } + CK[k] = point; + } + for (let k = du + 1; k <= nd + 1; ++k) { + CK[k] = new Vector4(0, 0, 0); + } + return CK; + } + function calcKoverI(k, i) { + let nom = 1; + for (let j = 2; j <= k; ++j) { + nom *= j; + } + let denom = 1; + for (let j = 2; j <= i; ++j) { + denom *= j; + } + for (let j = 2; j <= k - i; ++j) { + denom *= j; + } + return nom / denom; + } + function calcRationalCurveDerivatives(Pders) { + const nd = Pders.length; + const Aders = []; + const wders = []; + for (let i = 0; i < nd; ++i) { + const point = Pders[i]; + Aders[i] = new Vector3(point.x, point.y, point.z); + wders[i] = point.w; + } + const CK = []; + for (let k = 0; k < nd; ++k) { + const v = Aders[k].clone(); + for (let i = 1; i <= k; ++i) { + v.sub(CK[k - i].clone().multiplyScalar(calcKoverI(k, i) * wders[i])); + } + CK[k] = v.divideScalar(wders[0]); + } + return CK; + } + function calcNURBSDerivatives(p, U, P, u, nd) { + const Pders = calcBSplineDerivatives(p, U, P, u, nd); + return calcRationalCurveDerivatives(Pders); + } + + // examples/jsm/curves/NURBSCurve.js + var NURBSCurve = class extends Curve { + constructor(degree, knots, controlPoints, startKnot, endKnot) { + super(); + this.degree = degree; + this.knots = knots; + this.controlPoints = []; + this.startKnot = startKnot || 0; + this.endKnot = endKnot || this.knots.length - 1; + for (let i = 0; i < controlPoints.length; ++i) { + const point = controlPoints[i]; + this.controlPoints[i] = new Vector4(point.x, point.y, point.z, point.w); + } + } + getPoint(t, optionalTarget = new Vector3()) { + const point = optionalTarget; + const u = this.knots[this.startKnot] + t * (this.knots[this.endKnot] - this.knots[this.startKnot]); + const hpoint = calcBSplinePoint(this.degree, this.knots, this.controlPoints, u); + if (hpoint.w !== 1) { + hpoint.divideScalar(hpoint.w); + } + return point.set(hpoint.x, hpoint.y, hpoint.z); + } + getTangent(t, optionalTarget = new Vector3()) { + const tangent = optionalTarget; + const u = this.knots[0] + t * (this.knots[this.knots.length - 1] - this.knots[0]); + const ders = calcNURBSDerivatives(this.degree, this.knots, this.controlPoints, u, 1); + tangent.copy(ders[1]).normalize(); + return tangent; + } + }; + + // examples/jsm/loaders/FBXLoader.js + var fbxTree; + var connections; + var sceneGraph; + var FBXLoader = class extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const path = scope.path === "" ? LoaderUtils.extractUrlBase(url) : scope.path; + const loader = new FileLoader(this.manager); + loader.setPath(scope.path); + loader.setResponseType("arraybuffer"); + loader.setRequestHeader(scope.requestHeader); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(buffer) { + try { + onLoad(scope.parse(buffer, path)); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(FBXBuffer, path) { + if (isFbxFormatBinary(FBXBuffer)) { + fbxTree = new BinaryParser().parse(FBXBuffer); + } else { + const FBXText = convertArrayBufferToString(FBXBuffer); + if (!isFbxFormatASCII(FBXText)) { + throw new Error("THREE.FBXLoader: Unknown format."); + } + if (getFbxVersion(FBXText) < 7e3) { + throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: " + getFbxVersion(FBXText)); + } + fbxTree = new TextParser().parse(FBXText); + } + const textureLoader = new TextureLoader(this.manager).setPath(this.resourcePath || path).setCrossOrigin(this.crossOrigin); + return new FBXTreeParser(textureLoader, this.manager).parse(fbxTree); + } + }; + var FBXTreeParser = class { + constructor(textureLoader, manager) { + this.textureLoader = textureLoader; + this.manager = manager; + } + parse() { + connections = this.parseConnections(); + const images = this.parseImages(); + const textures = this.parseTextures(images); + const materials = this.parseMaterials(textures); + const deformers = this.parseDeformers(); + const geometryMap = new GeometryParser().parse(deformers); + this.parseScene(deformers, geometryMap, materials); + return sceneGraph; + } + // Parses FBXTree.Connections which holds parent-child connections between objects (e.g. material -> texture, model->geometry ) + // and details the connection type + parseConnections() { + const connectionMap = /* @__PURE__ */ new Map(); + if ("Connections" in fbxTree) { + const rawConnections = fbxTree.Connections.connections; + rawConnections.forEach(function(rawConnection) { + const fromID = rawConnection[0]; + const toID = rawConnection[1]; + const relationship = rawConnection[2]; + if (!connectionMap.has(fromID)) { + connectionMap.set(fromID, { + parents: [], + children: [] + }); + } + const parentRelationship = { ID: toID, relationship }; + connectionMap.get(fromID).parents.push(parentRelationship); + if (!connectionMap.has(toID)) { + connectionMap.set(toID, { + parents: [], + children: [] + }); + } + const childRelationship = { ID: fromID, relationship }; + connectionMap.get(toID).children.push(childRelationship); + }); + } + return connectionMap; + } + // Parse FBXTree.Objects.Video for embedded image data + // These images are connected to textures in FBXTree.Objects.Textures + // via FBXTree.Connections. + parseImages() { + const images = {}; + const blobs = {}; + if ("Video" in fbxTree.Objects) { + const videoNodes = fbxTree.Objects.Video; + for (const nodeID in videoNodes) { + const videoNode = videoNodes[nodeID]; + const id = parseInt(nodeID); + images[id] = videoNode.RelativeFilename || videoNode.Filename; + if ("Content" in videoNode) { + const arrayBufferContent = videoNode.Content instanceof ArrayBuffer && videoNode.Content.byteLength > 0; + const base64Content = typeof videoNode.Content === "string" && videoNode.Content !== ""; + if (arrayBufferContent || base64Content) { + const image = this.parseImage(videoNodes[nodeID]); + blobs[videoNode.RelativeFilename || videoNode.Filename] = image; + } + } + } + } + for (const id in images) { + const filename = images[id]; + if (blobs[filename] !== void 0) images[id] = blobs[filename]; + else images[id] = images[id].split("\\").pop(); + } + return images; + } + // Parse embedded image data in FBXTree.Video.Content + parseImage(videoNode) { + const content = videoNode.Content; + const fileName = videoNode.RelativeFilename || videoNode.Filename; + const extension = fileName.slice(fileName.lastIndexOf(".") + 1).toLowerCase(); + let type; + switch (extension) { + case "bmp": + type = "image/bmp"; + break; + case "jpg": + case "jpeg": + type = "image/jpeg"; + break; + case "png": + type = "image/png"; + break; + case "tif": + type = "image/tiff"; + break; + case "tga": + if (this.manager.getHandler(".tga") === null) { + console.warn("FBXLoader: TGA loader not found, skipping ", fileName); + } + type = "image/tga"; + break; + default: + console.warn('FBXLoader: Image type "' + extension + '" is not supported.'); + return; + } + if (typeof content === "string") { + return "data:" + type + ";base64," + content; + } else { + const array = new Uint8Array(content); + return window.URL.createObjectURL(new Blob([array], { type })); + } + } + // Parse nodes in FBXTree.Objects.Texture + // These contain details such as UV scaling, cropping, rotation etc and are connected + // to images in FBXTree.Objects.Video + parseTextures(images) { + const textureMap = /* @__PURE__ */ new Map(); + if ("Texture" in fbxTree.Objects) { + const textureNodes = fbxTree.Objects.Texture; + for (const nodeID in textureNodes) { + const texture = this.parseTexture(textureNodes[nodeID], images); + textureMap.set(parseInt(nodeID), texture); + } + } + return textureMap; + } + // Parse individual node in FBXTree.Objects.Texture + parseTexture(textureNode, images) { + const texture = this.loadTexture(textureNode, images); + texture.ID = textureNode.id; + texture.name = textureNode.attrName; + const wrapModeU = textureNode.WrapModeU; + const wrapModeV = textureNode.WrapModeV; + const valueU = wrapModeU !== void 0 ? wrapModeU.value : 0; + const valueV = wrapModeV !== void 0 ? wrapModeV.value : 0; + texture.wrapS = valueU === 0 ? RepeatWrapping : ClampToEdgeWrapping; + texture.wrapT = valueV === 0 ? RepeatWrapping : ClampToEdgeWrapping; + if ("Scaling" in textureNode) { + const values = textureNode.Scaling.value; + texture.repeat.x = values[0]; + texture.repeat.y = values[1]; + } + if ("Translation" in textureNode) { + const values = textureNode.Translation.value; + texture.offset.x = values[0]; + texture.offset.y = values[1]; + } + return texture; + } + // load a texture specified as a blob or data URI, or via an external URL using TextureLoader + loadTexture(textureNode, images) { + let fileName; + const currentPath = this.textureLoader.path; + const children = connections.get(textureNode.id).children; + if (children !== void 0 && children.length > 0 && images[children[0].ID] !== void 0) { + fileName = images[children[0].ID]; + if (fileName.indexOf("blob:") === 0 || fileName.indexOf("data:") === 0) { + this.textureLoader.setPath(void 0); + } + } + let texture; + const extension = textureNode.FileName.slice(-3).toLowerCase(); + if (extension === "tga") { + const loader = this.manager.getHandler(".tga"); + if (loader === null) { + console.warn("FBXLoader: TGA loader not found, creating placeholder texture for", textureNode.RelativeFilename); + texture = new Texture(); + } else { + loader.setPath(this.textureLoader.path); + texture = loader.load(fileName); + } + } else if (extension === "dds") { + const loader = this.manager.getHandler(".dds"); + if (loader === null) { + console.warn("FBXLoader: DDS loader not found, creating placeholder texture for", textureNode.RelativeFilename); + texture = new Texture(); + } else { + loader.setPath(this.textureLoader.path); + texture = loader.load(fileName); + } + } else if (extension === "psd") { + console.warn("FBXLoader: PSD textures are not supported, creating placeholder texture for", textureNode.RelativeFilename); + texture = new Texture(); + } else { + texture = this.textureLoader.load(fileName); + } + this.textureLoader.setPath(currentPath); + return texture; + } + // Parse nodes in FBXTree.Objects.Material + parseMaterials(textureMap) { + const materialMap = /* @__PURE__ */ new Map(); + if ("Material" in fbxTree.Objects) { + const materialNodes = fbxTree.Objects.Material; + for (const nodeID in materialNodes) { + const material = this.parseMaterial(materialNodes[nodeID], textureMap); + if (material !== null) materialMap.set(parseInt(nodeID), material); + } + } + return materialMap; + } + // Parse single node in FBXTree.Objects.Material + // Materials are connected to texture maps in FBXTree.Objects.Textures + // FBX format currently only supports Lambert and Phong shading models + parseMaterial(materialNode, textureMap) { + const ID = materialNode.id; + const name = materialNode.attrName; + let type = materialNode.ShadingModel; + if (typeof type === "object") { + type = type.value; + } + if (!connections.has(ID)) return null; + const parameters = this.parseParameters(materialNode, textureMap, ID); + let material; + switch (type.toLowerCase()) { + case "phong": + material = new MeshPhongMaterial(); + break; + case "lambert": + material = new MeshLambertMaterial(); + break; + default: + console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.', type); + material = new MeshPhongMaterial(); + break; + } + material.setValues(parameters); + material.name = name; + return material; + } + // Parse FBX material and return parameters suitable for a three.js material + // Also parse the texture map and return any textures associated with the material + parseParameters(materialNode, textureMap, ID) { + const parameters = {}; + if (materialNode.BumpFactor) { + parameters.bumpScale = materialNode.BumpFactor.value; + } + if (materialNode.Diffuse) { + parameters.color = new Color().fromArray(materialNode.Diffuse.value).convertSRGBToLinear(); + } else if (materialNode.DiffuseColor && (materialNode.DiffuseColor.type === "Color" || materialNode.DiffuseColor.type === "ColorRGB")) { + parameters.color = new Color().fromArray(materialNode.DiffuseColor.value).convertSRGBToLinear(); + } + if (materialNode.DisplacementFactor) { + parameters.displacementScale = materialNode.DisplacementFactor.value; + } + if (materialNode.Emissive) { + parameters.emissive = new Color().fromArray(materialNode.Emissive.value).convertSRGBToLinear(); + } else if (materialNode.EmissiveColor && (materialNode.EmissiveColor.type === "Color" || materialNode.EmissiveColor.type === "ColorRGB")) { + parameters.emissive = new Color().fromArray(materialNode.EmissiveColor.value).convertSRGBToLinear(); + } + if (materialNode.EmissiveFactor) { + parameters.emissiveIntensity = parseFloat(materialNode.EmissiveFactor.value); + } + if (materialNode.Opacity) { + parameters.opacity = parseFloat(materialNode.Opacity.value); + } + if (parameters.opacity < 1) { + parameters.transparent = true; + } + if (materialNode.ReflectionFactor) { + parameters.reflectivity = materialNode.ReflectionFactor.value; + } + if (materialNode.Shininess) { + parameters.shininess = materialNode.Shininess.value; + } + if (materialNode.Specular) { + parameters.specular = new Color().fromArray(materialNode.Specular.value).convertSRGBToLinear(); + } else if (materialNode.SpecularColor && materialNode.SpecularColor.type === "Color") { + parameters.specular = new Color().fromArray(materialNode.SpecularColor.value).convertSRGBToLinear(); + } + const scope = this; + connections.get(ID).children.forEach(function(child) { + const type = child.relationship; + switch (type) { + case "Bump": + parameters.bumpMap = scope.getTexture(textureMap, child.ID); + break; + case "Maya|TEX_ao_map": + parameters.aoMap = scope.getTexture(textureMap, child.ID); + break; + case "DiffuseColor": + case "Maya|TEX_color_map": + parameters.map = scope.getTexture(textureMap, child.ID); + if (parameters.map !== void 0) { + parameters.map.colorSpace = SRGBColorSpace; + } + break; + case "DisplacementColor": + parameters.displacementMap = scope.getTexture(textureMap, child.ID); + break; + case "EmissiveColor": + parameters.emissiveMap = scope.getTexture(textureMap, child.ID); + if (parameters.emissiveMap !== void 0) { + parameters.emissiveMap.colorSpace = SRGBColorSpace; + } + break; + case "NormalMap": + case "Maya|TEX_normal_map": + parameters.normalMap = scope.getTexture(textureMap, child.ID); + break; + case "ReflectionColor": + parameters.envMap = scope.getTexture(textureMap, child.ID); + if (parameters.envMap !== void 0) { + parameters.envMap.mapping = EquirectangularReflectionMapping; + parameters.envMap.colorSpace = SRGBColorSpace; + } + break; + case "SpecularColor": + parameters.specularMap = scope.getTexture(textureMap, child.ID); + if (parameters.specularMap !== void 0) { + parameters.specularMap.colorSpace = SRGBColorSpace; + } + break; + case "TransparentColor": + case "TransparencyFactor": + parameters.alphaMap = scope.getTexture(textureMap, child.ID); + parameters.transparent = true; + break; + case "AmbientColor": + case "ShininessExponent": + // AKA glossiness map + case "SpecularFactor": + // AKA specularLevel + case "VectorDisplacementColor": + // NOTE: Seems to be a copy of DisplacementColor + default: + console.warn("THREE.FBXLoader: %s map is not supported in three.js, skipping texture.", type); + break; + } + }); + return parameters; + } + // get a texture from the textureMap for use by a material. + getTexture(textureMap, id) { + if ("LayeredTexture" in fbxTree.Objects && id in fbxTree.Objects.LayeredTexture) { + console.warn("THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer."); + id = connections.get(id).children[0].ID; + } + return textureMap.get(id); + } + // Parse nodes in FBXTree.Objects.Deformer + // Deformer node can contain skinning or Vertex Cache animation data, however only skinning is supported here + // Generates map of Skeleton-like objects for use later when generating and binding skeletons. + parseDeformers() { + const skeletons = {}; + const morphTargets = {}; + if ("Deformer" in fbxTree.Objects) { + const DeformerNodes = fbxTree.Objects.Deformer; + for (const nodeID in DeformerNodes) { + const deformerNode = DeformerNodes[nodeID]; + const relationships = connections.get(parseInt(nodeID)); + if (deformerNode.attrType === "Skin") { + const skeleton = this.parseSkeleton(relationships, DeformerNodes); + skeleton.ID = nodeID; + if (relationships.parents.length > 1) console.warn("THREE.FBXLoader: skeleton attached to more than one geometry is not supported."); + skeleton.geometryID = relationships.parents[0].ID; + skeletons[nodeID] = skeleton; + } else if (deformerNode.attrType === "BlendShape") { + const morphTarget = { + id: nodeID + }; + morphTarget.rawTargets = this.parseMorphTargets(relationships, DeformerNodes); + morphTarget.id = nodeID; + if (relationships.parents.length > 1) console.warn("THREE.FBXLoader: morph target attached to more than one geometry is not supported."); + morphTargets[nodeID] = morphTarget; + } + } + } + return { + skeletons, + morphTargets + }; + } + // Parse single nodes in FBXTree.Objects.Deformer + // The top level skeleton node has type 'Skin' and sub nodes have type 'Cluster' + // Each skin node represents a skeleton and each cluster node represents a bone + parseSkeleton(relationships, deformerNodes) { + const rawBones = []; + relationships.children.forEach(function(child) { + const boneNode = deformerNodes[child.ID]; + if (boneNode.attrType !== "Cluster") return; + const rawBone = { + ID: child.ID, + indices: [], + weights: [], + transformLink: new Matrix4().fromArray(boneNode.TransformLink.a) + // transform: new Matrix4().fromArray( boneNode.Transform.a ), + // linkMode: boneNode.Mode, + }; + if ("Indexes" in boneNode) { + rawBone.indices = boneNode.Indexes.a; + rawBone.weights = boneNode.Weights.a; + } + rawBones.push(rawBone); + }); + return { + rawBones, + bones: [] + }; + } + // The top level morph deformer node has type "BlendShape" and sub nodes have type "BlendShapeChannel" + parseMorphTargets(relationships, deformerNodes) { + const rawMorphTargets = []; + for (let i = 0; i < relationships.children.length; i++) { + const child = relationships.children[i]; + const morphTargetNode = deformerNodes[child.ID]; + const rawMorphTarget = { + name: morphTargetNode.attrName, + initialWeight: morphTargetNode.DeformPercent, + id: morphTargetNode.id, + fullWeights: morphTargetNode.FullWeights.a + }; + if (morphTargetNode.attrType !== "BlendShapeChannel") return; + rawMorphTarget.geoID = connections.get(parseInt(child.ID)).children.filter(function(child2) { + return child2.relationship === void 0; + })[0].ID; + rawMorphTargets.push(rawMorphTarget); + } + return rawMorphTargets; + } + // create the main Group() to be returned by the loader + parseScene(deformers, geometryMap, materialMap) { + sceneGraph = new Group(); + const modelMap = this.parseModels(deformers.skeletons, geometryMap, materialMap); + const modelNodes = fbxTree.Objects.Model; + const scope = this; + modelMap.forEach(function(model) { + const modelNode = modelNodes[model.ID]; + scope.setLookAtProperties(model, modelNode); + const parentConnections = connections.get(model.ID).parents; + parentConnections.forEach(function(connection) { + const parent = modelMap.get(connection.ID); + if (parent !== void 0) parent.add(model); + }); + if (model.parent === null) { + sceneGraph.add(model); + } + }); + this.bindSkeleton(deformers.skeletons, geometryMap, modelMap); + this.addGlobalSceneSettings(); + sceneGraph.traverse(function(node) { + if (node.userData.transformData) { + if (node.parent) { + node.userData.transformData.parentMatrix = node.parent.matrix; + node.userData.transformData.parentMatrixWorld = node.parent.matrixWorld; + } + const transform = generateTransform(node.userData.transformData); + node.applyMatrix4(transform); + node.updateWorldMatrix(); + } + }); + const animations = new AnimationParser().parse(); + if (sceneGraph.children.length === 1 && sceneGraph.children[0].isGroup) { + sceneGraph.children[0].animations = animations; + sceneGraph = sceneGraph.children[0]; + } + sceneGraph.animations = animations; + } + // parse nodes in FBXTree.Objects.Model + parseModels(skeletons, geometryMap, materialMap) { + const modelMap = /* @__PURE__ */ new Map(); + const modelNodes = fbxTree.Objects.Model; + for (const nodeID in modelNodes) { + const id = parseInt(nodeID); + const node = modelNodes[nodeID]; + const relationships = connections.get(id); + let model = this.buildSkeleton(relationships, skeletons, id, node.attrName); + if (!model) { + switch (node.attrType) { + case "Camera": + model = this.createCamera(relationships); + break; + case "Light": + model = this.createLight(relationships); + break; + case "Mesh": + model = this.createMesh(relationships, geometryMap, materialMap); + break; + case "NurbsCurve": + model = this.createCurve(relationships, geometryMap); + break; + case "LimbNode": + case "Root": + model = new Bone(); + break; + case "Null": + default: + model = new Group(); + break; + } + model.name = node.attrName ? PropertyBinding.sanitizeNodeName(node.attrName) : ""; + model.userData.originalName = node.attrName; + model.ID = id; + } + this.getTransformData(model, node); + modelMap.set(id, model); + } + return modelMap; + } + buildSkeleton(relationships, skeletons, id, name) { + let bone = null; + relationships.parents.forEach(function(parent) { + for (const ID in skeletons) { + const skeleton = skeletons[ID]; + skeleton.rawBones.forEach(function(rawBone, i) { + if (rawBone.ID === parent.ID) { + const subBone = bone; + bone = new Bone(); + bone.matrixWorld.copy(rawBone.transformLink); + bone.name = name ? PropertyBinding.sanitizeNodeName(name) : ""; + bone.userData.originalName = name; + bone.ID = id; + skeleton.bones[i] = bone; + if (subBone !== null) { + bone.add(subBone); + } + } + }); + } + }); + return bone; + } + // create a PerspectiveCamera or OrthographicCamera + createCamera(relationships) { + let model; + let cameraAttribute; + relationships.children.forEach(function(child) { + const attr = fbxTree.Objects.NodeAttribute[child.ID]; + if (attr !== void 0) { + cameraAttribute = attr; + } + }); + if (cameraAttribute === void 0) { + model = new Object3D(); + } else { + let type = 0; + if (cameraAttribute.CameraProjectionType !== void 0 && cameraAttribute.CameraProjectionType.value === 1) { + type = 1; + } + let nearClippingPlane = 1; + if (cameraAttribute.NearPlane !== void 0) { + nearClippingPlane = cameraAttribute.NearPlane.value / 1e3; + } + let farClippingPlane = 1e3; + if (cameraAttribute.FarPlane !== void 0) { + farClippingPlane = cameraAttribute.FarPlane.value / 1e3; + } + let width = window.innerWidth; + let height = window.innerHeight; + if (cameraAttribute.AspectWidth !== void 0 && cameraAttribute.AspectHeight !== void 0) { + width = cameraAttribute.AspectWidth.value; + height = cameraAttribute.AspectHeight.value; + } + const aspect2 = width / height; + let fov2 = 45; + if (cameraAttribute.FieldOfView !== void 0) { + fov2 = cameraAttribute.FieldOfView.value; + } + const focalLength = cameraAttribute.FocalLength ? cameraAttribute.FocalLength.value : null; + switch (type) { + case 0: + model = new PerspectiveCamera(fov2, aspect2, nearClippingPlane, farClippingPlane); + if (focalLength !== null) model.setFocalLength(focalLength); + break; + case 1: + model = new OrthographicCamera(-width / 2, width / 2, height / 2, -height / 2, nearClippingPlane, farClippingPlane); + break; + default: + console.warn("THREE.FBXLoader: Unknown camera type " + type + "."); + model = new Object3D(); + break; + } + } + return model; + } + // Create a DirectionalLight, PointLight or SpotLight + createLight(relationships) { + let model; + let lightAttribute; + relationships.children.forEach(function(child) { + const attr = fbxTree.Objects.NodeAttribute[child.ID]; + if (attr !== void 0) { + lightAttribute = attr; + } + }); + if (lightAttribute === void 0) { + model = new Object3D(); + } else { + let type; + if (lightAttribute.LightType === void 0) { + type = 0; + } else { + type = lightAttribute.LightType.value; + } + let color = 16777215; + if (lightAttribute.Color !== void 0) { + color = new Color().fromArray(lightAttribute.Color.value).convertSRGBToLinear(); + } + let intensity = lightAttribute.Intensity === void 0 ? 1 : lightAttribute.Intensity.value / 100; + if (lightAttribute.CastLightOnObject !== void 0 && lightAttribute.CastLightOnObject.value === 0) { + intensity = 0; + } + let distance = 0; + if (lightAttribute.FarAttenuationEnd !== void 0) { + if (lightAttribute.EnableFarAttenuation !== void 0 && lightAttribute.EnableFarAttenuation.value === 0) { + distance = 0; + } else { + distance = lightAttribute.FarAttenuationEnd.value; + } + } + const decay = 1; + switch (type) { + case 0: + model = new PointLight(color, intensity, distance, decay); + break; + case 1: + model = new DirectionalLight(color, intensity); + break; + case 2: + let angle = Math.PI / 3; + if (lightAttribute.InnerAngle !== void 0) { + angle = MathUtils.degToRad(lightAttribute.InnerAngle.value); + } + let penumbra = 0; + if (lightAttribute.OuterAngle !== void 0) { + penumbra = MathUtils.degToRad(lightAttribute.OuterAngle.value); + penumbra = Math.max(penumbra, 1); + } + model = new SpotLight(color, intensity, distance, angle, penumbra, decay); + break; + default: + console.warn("THREE.FBXLoader: Unknown light type " + lightAttribute.LightType.value + ", defaulting to a PointLight."); + model = new PointLight(color, intensity); + break; + } + if (lightAttribute.CastShadows !== void 0 && lightAttribute.CastShadows.value === 1) { + model.castShadow = true; + } + } + return model; + } + createMesh(relationships, geometryMap, materialMap) { + let model; + let geometry = null; + let material = null; + const materials = []; + relationships.children.forEach(function(child) { + if (geometryMap.has(child.ID)) { + geometry = geometryMap.get(child.ID); + } + if (materialMap.has(child.ID)) { + materials.push(materialMap.get(child.ID)); + } + }); + if (materials.length > 1) { + material = materials; + } else if (materials.length > 0) { + material = materials[0]; + } else { + material = new MeshPhongMaterial({ + name: Loader.DEFAULT_MATERIAL_NAME, + color: 13421772 + }); + materials.push(material); + } + if ("color" in geometry.attributes) { + materials.forEach(function(material2) { + material2.vertexColors = true; + }); + } + if (geometry.FBX_Deformer) { + model = new SkinnedMesh(geometry, material); + model.normalizeSkinWeights(); + } else { + model = new Mesh(geometry, material); + } + return model; + } + createCurve(relationships, geometryMap) { + const geometry = relationships.children.reduce(function(geo, child) { + if (geometryMap.has(child.ID)) geo = geometryMap.get(child.ID); + return geo; + }, null); + const material = new LineBasicMaterial({ + name: Loader.DEFAULT_MATERIAL_NAME, + color: 3342591, + linewidth: 1 + }); + return new Line(geometry, material); + } + // parse the model node for transform data + getTransformData(model, modelNode) { + const transformData = {}; + if ("InheritType" in modelNode) transformData.inheritType = parseInt(modelNode.InheritType.value); + if ("RotationOrder" in modelNode) transformData.eulerOrder = getEulerOrder(modelNode.RotationOrder.value); + else transformData.eulerOrder = "ZYX"; + if ("Lcl_Translation" in modelNode) transformData.translation = modelNode.Lcl_Translation.value; + if ("PreRotation" in modelNode) transformData.preRotation = modelNode.PreRotation.value; + if ("Lcl_Rotation" in modelNode) transformData.rotation = modelNode.Lcl_Rotation.value; + if ("PostRotation" in modelNode) transformData.postRotation = modelNode.PostRotation.value; + if ("Lcl_Scaling" in modelNode) transformData.scale = modelNode.Lcl_Scaling.value; + if ("ScalingOffset" in modelNode) transformData.scalingOffset = modelNode.ScalingOffset.value; + if ("ScalingPivot" in modelNode) transformData.scalingPivot = modelNode.ScalingPivot.value; + if ("RotationOffset" in modelNode) transformData.rotationOffset = modelNode.RotationOffset.value; + if ("RotationPivot" in modelNode) transformData.rotationPivot = modelNode.RotationPivot.value; + model.userData.transformData = transformData; + } + setLookAtProperties(model, modelNode) { + if ("LookAtProperty" in modelNode) { + const children = connections.get(model.ID).children; + children.forEach(function(child) { + if (child.relationship === "LookAtProperty") { + const lookAtTarget = fbxTree.Objects.Model[child.ID]; + if ("Lcl_Translation" in lookAtTarget) { + const pos = lookAtTarget.Lcl_Translation.value; + if (model.target !== void 0) { + model.target.position.fromArray(pos); + sceneGraph.add(model.target); + } else { + model.lookAt(new Vector3().fromArray(pos)); + } + } + } + }); + } + } + bindSkeleton(skeletons, geometryMap, modelMap) { + const bindMatrices = this.parsePoseNodes(); + for (const ID in skeletons) { + const skeleton = skeletons[ID]; + const parents = connections.get(parseInt(skeleton.ID)).parents; + parents.forEach(function(parent) { + if (geometryMap.has(parent.ID)) { + const geoID = parent.ID; + const geoRelationships = connections.get(geoID); + geoRelationships.parents.forEach(function(geoConnParent) { + if (modelMap.has(geoConnParent.ID)) { + const model = modelMap.get(geoConnParent.ID); + model.bind(new Skeleton(skeleton.bones), bindMatrices[geoConnParent.ID]); + } + }); + } + }); + } + } + parsePoseNodes() { + const bindMatrices = {}; + if ("Pose" in fbxTree.Objects) { + const BindPoseNode = fbxTree.Objects.Pose; + for (const nodeID in BindPoseNode) { + if (BindPoseNode[nodeID].attrType === "BindPose" && BindPoseNode[nodeID].NbPoseNodes > 0) { + const poseNodes = BindPoseNode[nodeID].PoseNode; + if (Array.isArray(poseNodes)) { + poseNodes.forEach(function(poseNode) { + bindMatrices[poseNode.Node] = new Matrix4().fromArray(poseNode.Matrix.a); + }); + } else { + bindMatrices[poseNodes.Node] = new Matrix4().fromArray(poseNodes.Matrix.a); + } + } + } + } + return bindMatrices; + } + addGlobalSceneSettings() { + if ("GlobalSettings" in fbxTree) { + if ("AmbientColor" in fbxTree.GlobalSettings) { + const ambientColor = fbxTree.GlobalSettings.AmbientColor.value; + const r = ambientColor[0]; + const g = ambientColor[1]; + const b = ambientColor[2]; + if (r !== 0 || g !== 0 || b !== 0) { + const color = new Color(r, g, b).convertSRGBToLinear(); + sceneGraph.add(new AmbientLight(color, 1)); + } + } + if ("UnitScaleFactor" in fbxTree.GlobalSettings) { + sceneGraph.userData.unitScaleFactor = fbxTree.GlobalSettings.UnitScaleFactor.value; + } + } + } + }; + var GeometryParser = class { + constructor() { + this.negativeMaterialIndices = false; + } + // Parse nodes in FBXTree.Objects.Geometry + parse(deformers) { + const geometryMap = /* @__PURE__ */ new Map(); + if ("Geometry" in fbxTree.Objects) { + const geoNodes = fbxTree.Objects.Geometry; + for (const nodeID in geoNodes) { + const relationships = connections.get(parseInt(nodeID)); + const geo = this.parseGeometry(relationships, geoNodes[nodeID], deformers); + geometryMap.set(parseInt(nodeID), geo); + } + } + if (this.negativeMaterialIndices === true) { + console.warn("THREE.FBXLoader: The FBX file contains invalid (negative) material indices. The asset might not render as expected."); + } + return geometryMap; + } + // Parse single node in FBXTree.Objects.Geometry + parseGeometry(relationships, geoNode, deformers) { + switch (geoNode.attrType) { + case "Mesh": + return this.parseMeshGeometry(relationships, geoNode, deformers); + break; + case "NurbsCurve": + return this.parseNurbsGeometry(geoNode); + break; + } + } + // Parse single node mesh geometry in FBXTree.Objects.Geometry + parseMeshGeometry(relationships, geoNode, deformers) { + const skeletons = deformers.skeletons; + const morphTargets = []; + const modelNodes = relationships.parents.map(function(parent) { + return fbxTree.Objects.Model[parent.ID]; + }); + if (modelNodes.length === 0) return; + const skeleton = relationships.children.reduce(function(skeleton2, child) { + if (skeletons[child.ID] !== void 0) skeleton2 = skeletons[child.ID]; + return skeleton2; + }, null); + relationships.children.forEach(function(child) { + if (deformers.morphTargets[child.ID] !== void 0) { + morphTargets.push(deformers.morphTargets[child.ID]); + } + }); + const modelNode = modelNodes[0]; + const transformData = {}; + if ("RotationOrder" in modelNode) transformData.eulerOrder = getEulerOrder(modelNode.RotationOrder.value); + if ("InheritType" in modelNode) transformData.inheritType = parseInt(modelNode.InheritType.value); + if ("GeometricTranslation" in modelNode) transformData.translation = modelNode.GeometricTranslation.value; + if ("GeometricRotation" in modelNode) transformData.rotation = modelNode.GeometricRotation.value; + if ("GeometricScaling" in modelNode) transformData.scale = modelNode.GeometricScaling.value; + const transform = generateTransform(transformData); + return this.genGeometry(geoNode, skeleton, morphTargets, transform); + } + // Generate a BufferGeometry from a node in FBXTree.Objects.Geometry + genGeometry(geoNode, skeleton, morphTargets, preTransform) { + const geo = new BufferGeometry(); + if (geoNode.attrName) geo.name = geoNode.attrName; + const geoInfo = this.parseGeoNode(geoNode, skeleton); + const buffers = this.genBuffers(geoInfo); + const positionAttribute = new Float32BufferAttribute(buffers.vertex, 3); + positionAttribute.applyMatrix4(preTransform); + geo.setAttribute("position", positionAttribute); + if (buffers.colors.length > 0) { + geo.setAttribute("color", new Float32BufferAttribute(buffers.colors, 3)); + } + if (skeleton) { + geo.setAttribute("skinIndex", new Uint16BufferAttribute(buffers.weightsIndices, 4)); + geo.setAttribute("skinWeight", new Float32BufferAttribute(buffers.vertexWeights, 4)); + geo.FBX_Deformer = skeleton; + } + if (buffers.normal.length > 0) { + const normalMatrix = new Matrix3().getNormalMatrix(preTransform); + const normalAttribute = new Float32BufferAttribute(buffers.normal, 3); + normalAttribute.applyNormalMatrix(normalMatrix); + geo.setAttribute("normal", normalAttribute); + } + buffers.uvs.forEach(function(uvBuffer, i) { + const name = i === 0 ? "uv" : `uv${i}`; + geo.setAttribute(name, new Float32BufferAttribute(buffers.uvs[i], 2)); + }); + if (geoInfo.material && geoInfo.material.mappingType !== "AllSame") { + let prevMaterialIndex = buffers.materialIndex[0]; + let startIndex = 0; + buffers.materialIndex.forEach(function(currentIndex, i) { + if (currentIndex !== prevMaterialIndex) { + geo.addGroup(startIndex, i - startIndex, prevMaterialIndex); + prevMaterialIndex = currentIndex; + startIndex = i; + } + }); + if (geo.groups.length > 0) { + const lastGroup = geo.groups[geo.groups.length - 1]; + const lastIndex = lastGroup.start + lastGroup.count; + if (lastIndex !== buffers.materialIndex.length) { + geo.addGroup(lastIndex, buffers.materialIndex.length - lastIndex, prevMaterialIndex); + } + } + if (geo.groups.length === 0) { + geo.addGroup(0, buffers.materialIndex.length, buffers.materialIndex[0]); + } + } + this.addMorphTargets(geo, geoNode, morphTargets, preTransform); + return geo; + } + parseGeoNode(geoNode, skeleton) { + const geoInfo = {}; + geoInfo.vertexPositions = geoNode.Vertices !== void 0 ? geoNode.Vertices.a : []; + geoInfo.vertexIndices = geoNode.PolygonVertexIndex !== void 0 ? geoNode.PolygonVertexIndex.a : []; + if (geoNode.LayerElementColor) { + geoInfo.color = this.parseVertexColors(geoNode.LayerElementColor[0]); + } + if (geoNode.LayerElementMaterial) { + geoInfo.material = this.parseMaterialIndices(geoNode.LayerElementMaterial[0]); + } + if (geoNode.LayerElementNormal) { + geoInfo.normal = this.parseNormals(geoNode.LayerElementNormal[0]); + } + if (geoNode.LayerElementUV) { + geoInfo.uv = []; + let i = 0; + while (geoNode.LayerElementUV[i]) { + if (geoNode.LayerElementUV[i].UV) { + geoInfo.uv.push(this.parseUVs(geoNode.LayerElementUV[i])); + } + i++; + } + } + geoInfo.weightTable = {}; + if (skeleton !== null) { + geoInfo.skeleton = skeleton; + skeleton.rawBones.forEach(function(rawBone, i) { + rawBone.indices.forEach(function(index, j) { + if (geoInfo.weightTable[index] === void 0) geoInfo.weightTable[index] = []; + geoInfo.weightTable[index].push({ + id: i, + weight: rawBone.weights[j] + }); + }); + }); + } + return geoInfo; + } + genBuffers(geoInfo) { + const buffers = { + vertex: [], + normal: [], + colors: [], + uvs: [], + materialIndex: [], + vertexWeights: [], + weightsIndices: [] + }; + let polygonIndex = 0; + let faceLength = 0; + let displayedWeightsWarning = false; + let facePositionIndexes = []; + let faceNormals = []; + let faceColors = []; + let faceUVs = []; + let faceWeights = []; + let faceWeightIndices = []; + const scope = this; + geoInfo.vertexIndices.forEach(function(vertexIndex, polygonVertexIndex) { + let materialIndex; + let endOfFace = false; + if (vertexIndex < 0) { + vertexIndex = vertexIndex ^ -1; + endOfFace = true; + } + let weightIndices = []; + let weights = []; + facePositionIndexes.push(vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2); + if (geoInfo.color) { + const data = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.color); + faceColors.push(data[0], data[1], data[2]); + } + if (geoInfo.skeleton) { + if (geoInfo.weightTable[vertexIndex] !== void 0) { + geoInfo.weightTable[vertexIndex].forEach(function(wt) { + weights.push(wt.weight); + weightIndices.push(wt.id); + }); + } + if (weights.length > 4) { + if (!displayedWeightsWarning) { + console.warn("THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights."); + displayedWeightsWarning = true; + } + const wIndex = [0, 0, 0, 0]; + const Weight = [0, 0, 0, 0]; + weights.forEach(function(weight, weightIndex) { + let currentWeight = weight; + let currentIndex = weightIndices[weightIndex]; + Weight.forEach(function(comparedWeight, comparedWeightIndex, comparedWeightArray) { + if (currentWeight > comparedWeight) { + comparedWeightArray[comparedWeightIndex] = currentWeight; + currentWeight = comparedWeight; + const tmp2 = wIndex[comparedWeightIndex]; + wIndex[comparedWeightIndex] = currentIndex; + currentIndex = tmp2; + } + }); + }); + weightIndices = wIndex; + weights = Weight; + } + while (weights.length < 4) { + weights.push(0); + weightIndices.push(0); + } + for (let i = 0; i < 4; ++i) { + faceWeights.push(weights[i]); + faceWeightIndices.push(weightIndices[i]); + } + } + if (geoInfo.normal) { + const data = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.normal); + faceNormals.push(data[0], data[1], data[2]); + } + if (geoInfo.material && geoInfo.material.mappingType !== "AllSame") { + materialIndex = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.material)[0]; + if (materialIndex < 0) { + scope.negativeMaterialIndices = true; + materialIndex = 0; + } + } + if (geoInfo.uv) { + geoInfo.uv.forEach(function(uv, i) { + const data = getData(polygonVertexIndex, polygonIndex, vertexIndex, uv); + if (faceUVs[i] === void 0) { + faceUVs[i] = []; + } + faceUVs[i].push(data[0]); + faceUVs[i].push(data[1]); + }); + } + faceLength++; + if (endOfFace) { + scope.genFace(buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength); + polygonIndex++; + faceLength = 0; + facePositionIndexes = []; + faceNormals = []; + faceColors = []; + faceUVs = []; + faceWeights = []; + faceWeightIndices = []; + } + }); + return buffers; + } + // See https://www.khronos.org/opengl/wiki/Calculating_a_Surface_Normal + getNormalNewell(vertices) { + const normal = new Vector3(0, 0, 0); + for (let i = 0; i < vertices.length; i++) { + const current = vertices[i]; + const next = vertices[(i + 1) % vertices.length]; + normal.x += (current.y - next.y) * (current.z + next.z); + normal.y += (current.z - next.z) * (current.x + next.x); + normal.z += (current.x - next.x) * (current.y + next.y); + } + normal.normalize(); + return normal; + } + getNormalTangentAndBitangent(vertices) { + const normalVector = this.getNormalNewell(vertices); + const up = Math.abs(normalVector.z) > 0.5 ? new Vector3(0, 1, 0) : new Vector3(0, 0, 1); + const tangent = up.cross(normalVector).normalize(); + const bitangent = normalVector.clone().cross(tangent).normalize(); + return { + normal: normalVector, + tangent, + bitangent + }; + } + flattenVertex(vertex2, normalTangent, normalBitangent) { + return new Vector2( + vertex2.dot(normalTangent), + vertex2.dot(normalBitangent) + ); + } + // Generate data for a single face in a geometry. If the face is a quad then split it into 2 tris + genFace(buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength) { + let triangles; + if (faceLength > 3) { + const vertices = []; + for (let i = 0; i < facePositionIndexes.length; i += 3) { + vertices.push(new Vector3( + geoInfo.vertexPositions[facePositionIndexes[i]], + geoInfo.vertexPositions[facePositionIndexes[i + 1]], + geoInfo.vertexPositions[facePositionIndexes[i + 2]] + )); + } + const { tangent, bitangent } = this.getNormalTangentAndBitangent(vertices); + const triangulationInput = []; + for (const vertex2 of vertices) { + triangulationInput.push(this.flattenVertex(vertex2, tangent, bitangent)); + } + triangles = ShapeUtils.triangulateShape(triangulationInput, []); + } else { + triangles = [[0, 1, 2]]; + } + for (const [i0, i1, i2] of triangles) { + buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i0 * 3]]); + buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i0 * 3 + 1]]); + buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i0 * 3 + 2]]); + buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i1 * 3]]); + buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i1 * 3 + 1]]); + buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i1 * 3 + 2]]); + buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i2 * 3]]); + buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i2 * 3 + 1]]); + buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i2 * 3 + 2]]); + if (geoInfo.skeleton) { + buffers.vertexWeights.push(faceWeights[i0 * 4]); + buffers.vertexWeights.push(faceWeights[i0 * 4 + 1]); + buffers.vertexWeights.push(faceWeights[i0 * 4 + 2]); + buffers.vertexWeights.push(faceWeights[i0 * 4 + 3]); + buffers.vertexWeights.push(faceWeights[i1 * 4]); + buffers.vertexWeights.push(faceWeights[i1 * 4 + 1]); + buffers.vertexWeights.push(faceWeights[i1 * 4 + 2]); + buffers.vertexWeights.push(faceWeights[i1 * 4 + 3]); + buffers.vertexWeights.push(faceWeights[i2 * 4]); + buffers.vertexWeights.push(faceWeights[i2 * 4 + 1]); + buffers.vertexWeights.push(faceWeights[i2 * 4 + 2]); + buffers.vertexWeights.push(faceWeights[i2 * 4 + 3]); + buffers.weightsIndices.push(faceWeightIndices[i0 * 4]); + buffers.weightsIndices.push(faceWeightIndices[i0 * 4 + 1]); + buffers.weightsIndices.push(faceWeightIndices[i0 * 4 + 2]); + buffers.weightsIndices.push(faceWeightIndices[i0 * 4 + 3]); + buffers.weightsIndices.push(faceWeightIndices[i1 * 4]); + buffers.weightsIndices.push(faceWeightIndices[i1 * 4 + 1]); + buffers.weightsIndices.push(faceWeightIndices[i1 * 4 + 2]); + buffers.weightsIndices.push(faceWeightIndices[i1 * 4 + 3]); + buffers.weightsIndices.push(faceWeightIndices[i2 * 4]); + buffers.weightsIndices.push(faceWeightIndices[i2 * 4 + 1]); + buffers.weightsIndices.push(faceWeightIndices[i2 * 4 + 2]); + buffers.weightsIndices.push(faceWeightIndices[i2 * 4 + 3]); + } + if (geoInfo.color) { + buffers.colors.push(faceColors[i0 * 3]); + buffers.colors.push(faceColors[i0 * 3 + 1]); + buffers.colors.push(faceColors[i0 * 3 + 2]); + buffers.colors.push(faceColors[i1 * 3]); + buffers.colors.push(faceColors[i1 * 3 + 1]); + buffers.colors.push(faceColors[i1 * 3 + 2]); + buffers.colors.push(faceColors[i2 * 3]); + buffers.colors.push(faceColors[i2 * 3 + 1]); + buffers.colors.push(faceColors[i2 * 3 + 2]); + } + if (geoInfo.material && geoInfo.material.mappingType !== "AllSame") { + buffers.materialIndex.push(materialIndex); + buffers.materialIndex.push(materialIndex); + buffers.materialIndex.push(materialIndex); + } + if (geoInfo.normal) { + buffers.normal.push(faceNormals[i0 * 3]); + buffers.normal.push(faceNormals[i0 * 3 + 1]); + buffers.normal.push(faceNormals[i0 * 3 + 2]); + buffers.normal.push(faceNormals[i1 * 3]); + buffers.normal.push(faceNormals[i1 * 3 + 1]); + buffers.normal.push(faceNormals[i1 * 3 + 2]); + buffers.normal.push(faceNormals[i2 * 3]); + buffers.normal.push(faceNormals[i2 * 3 + 1]); + buffers.normal.push(faceNormals[i2 * 3 + 2]); + } + if (geoInfo.uv) { + geoInfo.uv.forEach(function(uv, j) { + if (buffers.uvs[j] === void 0) buffers.uvs[j] = []; + buffers.uvs[j].push(faceUVs[j][i0 * 2]); + buffers.uvs[j].push(faceUVs[j][i0 * 2 + 1]); + buffers.uvs[j].push(faceUVs[j][i1 * 2]); + buffers.uvs[j].push(faceUVs[j][i1 * 2 + 1]); + buffers.uvs[j].push(faceUVs[j][i2 * 2]); + buffers.uvs[j].push(faceUVs[j][i2 * 2 + 1]); + }); + } + } + } + addMorphTargets(parentGeo, parentGeoNode, morphTargets, preTransform) { + if (morphTargets.length === 0) return; + parentGeo.morphTargetsRelative = true; + parentGeo.morphAttributes.position = []; + const scope = this; + morphTargets.forEach(function(morphTarget) { + morphTarget.rawTargets.forEach(function(rawTarget) { + const morphGeoNode = fbxTree.Objects.Geometry[rawTarget.geoID]; + if (morphGeoNode !== void 0) { + scope.genMorphGeometry(parentGeo, parentGeoNode, morphGeoNode, preTransform, rawTarget.name); + } + }); + }); + } + // a morph geometry node is similar to a standard node, and the node is also contained + // in FBXTree.Objects.Geometry, however it can only have attributes for position, normal + // and a special attribute Index defining which vertices of the original geometry are affected + // Normal and position attributes only have data for the vertices that are affected by the morph + genMorphGeometry(parentGeo, parentGeoNode, morphGeoNode, preTransform, name) { + const vertexIndices = parentGeoNode.PolygonVertexIndex !== void 0 ? parentGeoNode.PolygonVertexIndex.a : []; + const morphPositionsSparse = morphGeoNode.Vertices !== void 0 ? morphGeoNode.Vertices.a : []; + const indices = morphGeoNode.Indexes !== void 0 ? morphGeoNode.Indexes.a : []; + const length = parentGeo.attributes.position.count * 3; + const morphPositions = new Float32Array(length); + for (let i = 0; i < indices.length; i++) { + const morphIndex = indices[i] * 3; + morphPositions[morphIndex] = morphPositionsSparse[i * 3]; + morphPositions[morphIndex + 1] = morphPositionsSparse[i * 3 + 1]; + morphPositions[morphIndex + 2] = morphPositionsSparse[i * 3 + 2]; + } + const morphGeoInfo = { + vertexIndices, + vertexPositions: morphPositions + }; + const morphBuffers = this.genBuffers(morphGeoInfo); + const positionAttribute = new Float32BufferAttribute(morphBuffers.vertex, 3); + positionAttribute.name = name || morphGeoNode.attrName; + positionAttribute.applyMatrix4(preTransform); + parentGeo.morphAttributes.position.push(positionAttribute); + } + // Parse normal from FBXTree.Objects.Geometry.LayerElementNormal if it exists + parseNormals(NormalNode) { + const mappingType = NormalNode.MappingInformationType; + const referenceType = NormalNode.ReferenceInformationType; + const buffer = NormalNode.Normals.a; + let indexBuffer = []; + if (referenceType === "IndexToDirect") { + if ("NormalIndex" in NormalNode) { + indexBuffer = NormalNode.NormalIndex.a; + } else if ("NormalsIndex" in NormalNode) { + indexBuffer = NormalNode.NormalsIndex.a; + } + } + return { + dataSize: 3, + buffer, + indices: indexBuffer, + mappingType, + referenceType + }; + } + // Parse UVs from FBXTree.Objects.Geometry.LayerElementUV if it exists + parseUVs(UVNode) { + const mappingType = UVNode.MappingInformationType; + const referenceType = UVNode.ReferenceInformationType; + const buffer = UVNode.UV.a; + let indexBuffer = []; + if (referenceType === "IndexToDirect") { + indexBuffer = UVNode.UVIndex.a; + } + return { + dataSize: 2, + buffer, + indices: indexBuffer, + mappingType, + referenceType + }; + } + // Parse Vertex Colors from FBXTree.Objects.Geometry.LayerElementColor if it exists + parseVertexColors(ColorNode) { + const mappingType = ColorNode.MappingInformationType; + const referenceType = ColorNode.ReferenceInformationType; + const buffer = ColorNode.Colors.a; + let indexBuffer = []; + if (referenceType === "IndexToDirect") { + indexBuffer = ColorNode.ColorIndex.a; + } + for (let i = 0, c = new Color(); i < buffer.length; i += 4) { + c.fromArray(buffer, i).convertSRGBToLinear().toArray(buffer, i); + } + return { + dataSize: 4, + buffer, + indices: indexBuffer, + mappingType, + referenceType + }; + } + // Parse mapping and material data in FBXTree.Objects.Geometry.LayerElementMaterial if it exists + parseMaterialIndices(MaterialNode) { + const mappingType = MaterialNode.MappingInformationType; + const referenceType = MaterialNode.ReferenceInformationType; + if (mappingType === "NoMappingInformation") { + return { + dataSize: 1, + buffer: [0], + indices: [0], + mappingType: "AllSame", + referenceType + }; + } + const materialIndexBuffer = MaterialNode.Materials.a; + const materialIndices = []; + for (let i = 0; i < materialIndexBuffer.length; ++i) { + materialIndices.push(i); + } + return { + dataSize: 1, + buffer: materialIndexBuffer, + indices: materialIndices, + mappingType, + referenceType + }; + } + // Generate a NurbGeometry from a node in FBXTree.Objects.Geometry + parseNurbsGeometry(geoNode) { + const order = parseInt(geoNode.Order); + if (isNaN(order)) { + console.error("THREE.FBXLoader: Invalid Order %s given for geometry ID: %s", geoNode.Order, geoNode.id); + return new BufferGeometry(); + } + const degree = order - 1; + const knots = geoNode.KnotVector.a; + const controlPoints = []; + const pointsValues = geoNode.Points.a; + for (let i = 0, l = pointsValues.length; i < l; i += 4) { + controlPoints.push(new Vector4().fromArray(pointsValues, i)); + } + let startKnot, endKnot; + if (geoNode.Form === "Closed") { + controlPoints.push(controlPoints[0]); + } else if (geoNode.Form === "Periodic") { + startKnot = degree; + endKnot = knots.length - 1 - startKnot; + for (let i = 0; i < degree; ++i) { + controlPoints.push(controlPoints[i]); + } + } + const curve = new NURBSCurve(degree, knots, controlPoints, startKnot, endKnot); + const points = curve.getPoints(controlPoints.length * 12); + return new BufferGeometry().setFromPoints(points); + } + }; + var AnimationParser = class { + // take raw animation clips and turn them into three.js animation clips + parse() { + const animationClips = []; + const rawClips = this.parseClips(); + if (rawClips !== void 0) { + for (const key in rawClips) { + const rawClip = rawClips[key]; + const clip = this.addClip(rawClip); + animationClips.push(clip); + } + } + return animationClips; + } + parseClips() { + if (fbxTree.Objects.AnimationCurve === void 0) return void 0; + const curveNodesMap = this.parseAnimationCurveNodes(); + this.parseAnimationCurves(curveNodesMap); + const layersMap = this.parseAnimationLayers(curveNodesMap); + const rawClips = this.parseAnimStacks(layersMap); + return rawClips; + } + // parse nodes in FBXTree.Objects.AnimationCurveNode + // each AnimationCurveNode holds data for an animation transform for a model (e.g. left arm rotation ) + // and is referenced by an AnimationLayer + parseAnimationCurveNodes() { + const rawCurveNodes = fbxTree.Objects.AnimationCurveNode; + const curveNodesMap = /* @__PURE__ */ new Map(); + for (const nodeID in rawCurveNodes) { + const rawCurveNode = rawCurveNodes[nodeID]; + if (rawCurveNode.attrName.match(/S|R|T|DeformPercent/) !== null) { + const curveNode = { + id: rawCurveNode.id, + attr: rawCurveNode.attrName, + curves: {} + }; + curveNodesMap.set(curveNode.id, curveNode); + } + } + return curveNodesMap; + } + // parse nodes in FBXTree.Objects.AnimationCurve and connect them up to + // previously parsed AnimationCurveNodes. Each AnimationCurve holds data for a single animated + // axis ( e.g. times and values of x rotation) + parseAnimationCurves(curveNodesMap) { + const rawCurves = fbxTree.Objects.AnimationCurve; + for (const nodeID in rawCurves) { + const animationCurve = { + id: rawCurves[nodeID].id, + times: rawCurves[nodeID].KeyTime.a.map(convertFBXTimeToSeconds), + values: rawCurves[nodeID].KeyValueFloat.a + }; + const relationships = connections.get(animationCurve.id); + if (relationships !== void 0) { + const animationCurveID = relationships.parents[0].ID; + const animationCurveRelationship = relationships.parents[0].relationship; + if (animationCurveRelationship.match(/X/)) { + curveNodesMap.get(animationCurveID).curves["x"] = animationCurve; + } else if (animationCurveRelationship.match(/Y/)) { + curveNodesMap.get(animationCurveID).curves["y"] = animationCurve; + } else if (animationCurveRelationship.match(/Z/)) { + curveNodesMap.get(animationCurveID).curves["z"] = animationCurve; + } else if (animationCurveRelationship.match(/DeformPercent/) && curveNodesMap.has(animationCurveID)) { + curveNodesMap.get(animationCurveID).curves["morph"] = animationCurve; + } + } + } + } + // parse nodes in FBXTree.Objects.AnimationLayer. Each layers holds references + // to various AnimationCurveNodes and is referenced by an AnimationStack node + // note: theoretically a stack can have multiple layers, however in practice there always seems to be one per stack + parseAnimationLayers(curveNodesMap) { + const rawLayers = fbxTree.Objects.AnimationLayer; + const layersMap = /* @__PURE__ */ new Map(); + for (const nodeID in rawLayers) { + const layerCurveNodes = []; + const connection = connections.get(parseInt(nodeID)); + if (connection !== void 0) { + const children = connection.children; + children.forEach(function(child, i) { + if (curveNodesMap.has(child.ID)) { + const curveNode = curveNodesMap.get(child.ID); + if (curveNode.curves.x !== void 0 || curveNode.curves.y !== void 0 || curveNode.curves.z !== void 0) { + if (layerCurveNodes[i] === void 0) { + const modelID = connections.get(child.ID).parents.filter(function(parent) { + return parent.relationship !== void 0; + })[0].ID; + if (modelID !== void 0) { + const rawModel = fbxTree.Objects.Model[modelID.toString()]; + if (rawModel === void 0) { + console.warn("THREE.FBXLoader: Encountered a unused curve.", child); + return; + } + const node = { + modelName: rawModel.attrName ? PropertyBinding.sanitizeNodeName(rawModel.attrName) : "", + ID: rawModel.id, + initialPosition: [0, 0, 0], + initialRotation: [0, 0, 0], + initialScale: [1, 1, 1] + }; + sceneGraph.traverse(function(child2) { + if (child2.ID === rawModel.id) { + node.transform = child2.matrix; + if (child2.userData.transformData) node.eulerOrder = child2.userData.transformData.eulerOrder; + } + }); + if (!node.transform) node.transform = new Matrix4(); + if ("PreRotation" in rawModel) node.preRotation = rawModel.PreRotation.value; + if ("PostRotation" in rawModel) node.postRotation = rawModel.PostRotation.value; + layerCurveNodes[i] = node; + } + } + if (layerCurveNodes[i]) layerCurveNodes[i][curveNode.attr] = curveNode; + } else if (curveNode.curves.morph !== void 0) { + if (layerCurveNodes[i] === void 0) { + const deformerID = connections.get(child.ID).parents.filter(function(parent) { + return parent.relationship !== void 0; + })[0].ID; + const morpherID = connections.get(deformerID).parents[0].ID; + const geoID = connections.get(morpherID).parents[0].ID; + const modelID = connections.get(geoID).parents[0].ID; + const rawModel = fbxTree.Objects.Model[modelID]; + const node = { + modelName: rawModel.attrName ? PropertyBinding.sanitizeNodeName(rawModel.attrName) : "", + morphName: fbxTree.Objects.Deformer[deformerID].attrName + }; + layerCurveNodes[i] = node; + } + layerCurveNodes[i][curveNode.attr] = curveNode; + } + } + }); + layersMap.set(parseInt(nodeID), layerCurveNodes); + } + } + return layersMap; + } + // parse nodes in FBXTree.Objects.AnimationStack. These are the top level node in the animation + // hierarchy. Each Stack node will be used to create a AnimationClip + parseAnimStacks(layersMap) { + const rawStacks = fbxTree.Objects.AnimationStack; + const rawClips = {}; + for (const nodeID in rawStacks) { + const children = connections.get(parseInt(nodeID)).children; + if (children.length > 1) { + console.warn("THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers."); + } + const layer = layersMap.get(children[0].ID); + rawClips[nodeID] = { + name: rawStacks[nodeID].attrName, + layer + }; + } + return rawClips; + } + addClip(rawClip) { + let tracks = []; + const scope = this; + rawClip.layer.forEach(function(rawTracks) { + tracks = tracks.concat(scope.generateTracks(rawTracks)); + }); + return new AnimationClip(rawClip.name, -1, tracks); + } + generateTracks(rawTracks) { + const tracks = []; + let initialPosition = new Vector3(); + let initialScale = new Vector3(); + if (rawTracks.transform) rawTracks.transform.decompose(initialPosition, new Quaternion(), initialScale); + initialPosition = initialPosition.toArray(); + initialScale = initialScale.toArray(); + if (rawTracks.T !== void 0 && Object.keys(rawTracks.T.curves).length > 0) { + const positionTrack = this.generateVectorTrack(rawTracks.modelName, rawTracks.T.curves, initialPosition, "position"); + if (positionTrack !== void 0) tracks.push(positionTrack); + } + if (rawTracks.R !== void 0 && Object.keys(rawTracks.R.curves).length > 0) { + const rotationTrack = this.generateRotationTrack(rawTracks.modelName, rawTracks.R.curves, rawTracks.preRotation, rawTracks.postRotation, rawTracks.eulerOrder); + if (rotationTrack !== void 0) tracks.push(rotationTrack); + } + if (rawTracks.S !== void 0 && Object.keys(rawTracks.S.curves).length > 0) { + const scaleTrack = this.generateVectorTrack(rawTracks.modelName, rawTracks.S.curves, initialScale, "scale"); + if (scaleTrack !== void 0) tracks.push(scaleTrack); + } + if (rawTracks.DeformPercent !== void 0) { + const morphTrack = this.generateMorphTrack(rawTracks); + if (morphTrack !== void 0) tracks.push(morphTrack); + } + return tracks; + } + generateVectorTrack(modelName, curves, initialValue, type) { + const times = this.getTimesForAllAxes(curves); + const values = this.getKeyframeTrackValues(times, curves, initialValue); + return new VectorKeyframeTrack(modelName + "." + type, times, values); + } + generateRotationTrack(modelName, curves, preRotation, postRotation, eulerOrder) { + let times; + let values; + if (curves.x !== void 0 && curves.y !== void 0 && curves.z !== void 0) { + const result = this.interpolateRotations(curves.x, curves.y, curves.z, eulerOrder); + times = result[0]; + values = result[1]; + } + if (preRotation !== void 0) { + preRotation = preRotation.map(MathUtils.degToRad); + preRotation.push(eulerOrder); + preRotation = new Euler().fromArray(preRotation); + preRotation = new Quaternion().setFromEuler(preRotation); + } + if (postRotation !== void 0) { + postRotation = postRotation.map(MathUtils.degToRad); + postRotation.push(eulerOrder); + postRotation = new Euler().fromArray(postRotation); + postRotation = new Quaternion().setFromEuler(postRotation).invert(); + } + const quaternion = new Quaternion(); + const euler = new Euler(); + const quaternionValues = []; + if (!values || !times) return new QuaternionKeyframeTrack(modelName + ".quaternion", [], []); + for (let i = 0; i < values.length; i += 3) { + euler.set(values[i], values[i + 1], values[i + 2], eulerOrder); + quaternion.setFromEuler(euler); + if (preRotation !== void 0) quaternion.premultiply(preRotation); + if (postRotation !== void 0) quaternion.multiply(postRotation); + if (i > 2) { + const prevQuat = new Quaternion().fromArray( + quaternionValues, + (i - 3) / 3 * 4 + ); + if (prevQuat.dot(quaternion) < 0) { + quaternion.set(-quaternion.x, -quaternion.y, -quaternion.z, -quaternion.w); + } + } + quaternion.toArray(quaternionValues, i / 3 * 4); + } + return new QuaternionKeyframeTrack(modelName + ".quaternion", times, quaternionValues); + } + generateMorphTrack(rawTracks) { + const curves = rawTracks.DeformPercent.curves.morph; + const values = curves.values.map(function(val) { + return val / 100; + }); + const morphNum = sceneGraph.getObjectByName(rawTracks.modelName).morphTargetDictionary[rawTracks.morphName]; + return new NumberKeyframeTrack(rawTracks.modelName + ".morphTargetInfluences[" + morphNum + "]", curves.times, values); + } + // For all animated objects, times are defined separately for each axis + // Here we'll combine the times into one sorted array without duplicates + getTimesForAllAxes(curves) { + let times = []; + if (curves.x !== void 0) times = times.concat(curves.x.times); + if (curves.y !== void 0) times = times.concat(curves.y.times); + if (curves.z !== void 0) times = times.concat(curves.z.times); + times = times.sort(function(a, b) { + return a - b; + }); + if (times.length > 1) { + let targetIndex = 1; + let lastValue = times[0]; + for (let i = 1; i < times.length; i++) { + const currentValue = times[i]; + if (currentValue !== lastValue) { + times[targetIndex] = currentValue; + lastValue = currentValue; + targetIndex++; + } + } + times = times.slice(0, targetIndex); + } + return times; + } + getKeyframeTrackValues(times, curves, initialValue) { + const prevValue = initialValue; + const values = []; + let xIndex = -1; + let yIndex = -1; + let zIndex = -1; + times.forEach(function(time) { + if (curves.x) xIndex = curves.x.times.indexOf(time); + if (curves.y) yIndex = curves.y.times.indexOf(time); + if (curves.z) zIndex = curves.z.times.indexOf(time); + if (xIndex !== -1) { + const xValue = curves.x.values[xIndex]; + values.push(xValue); + prevValue[0] = xValue; + } else { + values.push(prevValue[0]); + } + if (yIndex !== -1) { + const yValue = curves.y.values[yIndex]; + values.push(yValue); + prevValue[1] = yValue; + } else { + values.push(prevValue[1]); + } + if (zIndex !== -1) { + const zValue = curves.z.values[zIndex]; + values.push(zValue); + prevValue[2] = zValue; + } else { + values.push(prevValue[2]); + } + }); + return values; + } + // Rotations are defined as Euler angles which can have values of any size + // These will be converted to quaternions which don't support values greater than + // PI, so we'll interpolate large rotations + interpolateRotations(curvex, curvey, curvez, eulerOrder) { + const times = []; + const values = []; + times.push(curvex.times[0]); + values.push(MathUtils.degToRad(curvex.values[0])); + values.push(MathUtils.degToRad(curvey.values[0])); + values.push(MathUtils.degToRad(curvez.values[0])); + for (let i = 1; i < curvex.values.length; i++) { + const initialValue = [ + curvex.values[i - 1], + curvey.values[i - 1], + curvez.values[i - 1] + ]; + if (isNaN(initialValue[0]) || isNaN(initialValue[1]) || isNaN(initialValue[2])) { + continue; + } + const initialValueRad = initialValue.map(MathUtils.degToRad); + const currentValue = [ + curvex.values[i], + curvey.values[i], + curvez.values[i] + ]; + if (isNaN(currentValue[0]) || isNaN(currentValue[1]) || isNaN(currentValue[2])) { + continue; + } + const currentValueRad = currentValue.map(MathUtils.degToRad); + const valuesSpan = [ + currentValue[0] - initialValue[0], + currentValue[1] - initialValue[1], + currentValue[2] - initialValue[2] + ]; + const absoluteSpan = [ + Math.abs(valuesSpan[0]), + Math.abs(valuesSpan[1]), + Math.abs(valuesSpan[2]) + ]; + if (absoluteSpan[0] >= 180 || absoluteSpan[1] >= 180 || absoluteSpan[2] >= 180) { + const maxAbsSpan = Math.max(...absoluteSpan); + const numSubIntervals = maxAbsSpan / 180; + const E1 = new Euler(...initialValueRad, eulerOrder); + const E2 = new Euler(...currentValueRad, eulerOrder); + const Q1 = new Quaternion().setFromEuler(E1); + const Q2 = new Quaternion().setFromEuler(E2); + if (Q1.dot(Q2)) { + Q2.set(-Q2.x, -Q2.y, -Q2.z, -Q2.w); + } + const initialTime = curvex.times[i - 1]; + const timeSpan = curvex.times[i] - initialTime; + const Q = new Quaternion(); + const E = new Euler(); + for (let t = 0; t < 1; t += 1 / numSubIntervals) { + Q.copy(Q1.clone().slerp(Q2.clone(), t)); + times.push(initialTime + t * timeSpan); + E.setFromQuaternion(Q, eulerOrder); + values.push(E.x); + values.push(E.y); + values.push(E.z); + } + } else { + times.push(curvex.times[i]); + values.push(MathUtils.degToRad(curvex.values[i])); + values.push(MathUtils.degToRad(curvey.values[i])); + values.push(MathUtils.degToRad(curvez.values[i])); + } + } + return [times, values]; + } + }; + var TextParser = class { + getPrevNode() { + return this.nodeStack[this.currentIndent - 2]; + } + getCurrentNode() { + return this.nodeStack[this.currentIndent - 1]; + } + getCurrentProp() { + return this.currentProp; + } + pushStack(node) { + this.nodeStack.push(node); + this.currentIndent += 1; + } + popStack() { + this.nodeStack.pop(); + this.currentIndent -= 1; + } + setCurrentProp(val, name) { + this.currentProp = val; + this.currentPropName = name; + } + parse(text) { + this.currentIndent = 0; + this.allNodes = new FBXTree(); + this.nodeStack = []; + this.currentProp = []; + this.currentPropName = ""; + const scope = this; + const split = text.split(/[\r\n]+/); + split.forEach(function(line, i) { + const matchComment = line.match(/^[\s\t]*;/); + const matchEmpty = line.match(/^[\s\t]*$/); + if (matchComment || matchEmpty) return; + const matchBeginning = line.match("^\\t{" + scope.currentIndent + "}(\\w+):(.*){", ""); + const matchProperty = line.match("^\\t{" + scope.currentIndent + "}(\\w+):[\\s\\t\\r\\n](.*)"); + const matchEnd = line.match("^\\t{" + (scope.currentIndent - 1) + "}}"); + if (matchBeginning) { + scope.parseNodeBegin(line, matchBeginning); + } else if (matchProperty) { + scope.parseNodeProperty(line, matchProperty, split[++i]); + } else if (matchEnd) { + scope.popStack(); + } else if (line.match(/^[^\s\t}]/)) { + scope.parseNodePropertyContinued(line); + } + }); + return this.allNodes; + } + parseNodeBegin(line, property) { + const nodeName = property[1].trim().replace(/^"/, "").replace(/"$/, ""); + const nodeAttrs = property[2].split(",").map(function(attr) { + return attr.trim().replace(/^"/, "").replace(/"$/, ""); + }); + const node = { name: nodeName }; + const attrs = this.parseNodeAttr(nodeAttrs); + const currentNode = this.getCurrentNode(); + if (this.currentIndent === 0) { + this.allNodes.add(nodeName, node); + } else { + if (nodeName in currentNode) { + if (nodeName === "PoseNode") { + currentNode.PoseNode.push(node); + } else if (currentNode[nodeName].id !== void 0) { + currentNode[nodeName] = {}; + currentNode[nodeName][currentNode[nodeName].id] = currentNode[nodeName]; + } + if (attrs.id !== "") currentNode[nodeName][attrs.id] = node; + } else if (typeof attrs.id === "number") { + currentNode[nodeName] = {}; + currentNode[nodeName][attrs.id] = node; + } else if (nodeName !== "Properties70") { + if (nodeName === "PoseNode") currentNode[nodeName] = [node]; + else currentNode[nodeName] = node; + } + } + if (typeof attrs.id === "number") node.id = attrs.id; + if (attrs.name !== "") node.attrName = attrs.name; + if (attrs.type !== "") node.attrType = attrs.type; + this.pushStack(node); + } + parseNodeAttr(attrs) { + let id = attrs[0]; + if (attrs[0] !== "") { + id = parseInt(attrs[0]); + if (isNaN(id)) { + id = attrs[0]; + } + } + let name = "", type = ""; + if (attrs.length > 1) { + name = attrs[1].replace(/^(\w+)::/, ""); + type = attrs[2]; + } + return { id, name, type }; + } + parseNodeProperty(line, property, contentLine) { + let propName = property[1].replace(/^"/, "").replace(/"$/, "").trim(); + let propValue = property[2].replace(/^"/, "").replace(/"$/, "").trim(); + if (propName === "Content" && propValue === ",") { + propValue = contentLine.replace(/"/g, "").replace(/,$/, "").trim(); + } + const currentNode = this.getCurrentNode(); + const parentName = currentNode.name; + if (parentName === "Properties70") { + this.parseNodeSpecialProperty(line, propName, propValue); + return; + } + if (propName === "C") { + const connProps = propValue.split(",").slice(1); + const from = parseInt(connProps[0]); + const to = parseInt(connProps[1]); + let rest = propValue.split(",").slice(3); + rest = rest.map(function(elem) { + return elem.trim().replace(/^"/, ""); + }); + propName = "connections"; + propValue = [from, to]; + append(propValue, rest); + if (currentNode[propName] === void 0) { + currentNode[propName] = []; + } + } + if (propName === "Node") currentNode.id = propValue; + if (propName in currentNode && Array.isArray(currentNode[propName])) { + currentNode[propName].push(propValue); + } else { + if (propName !== "a") currentNode[propName] = propValue; + else currentNode.a = propValue; + } + this.setCurrentProp(currentNode, propName); + if (propName === "a" && propValue.slice(-1) !== ",") { + currentNode.a = parseNumberArray(propValue); + } + } + parseNodePropertyContinued(line) { + const currentNode = this.getCurrentNode(); + currentNode.a += line; + if (line.slice(-1) !== ",") { + currentNode.a = parseNumberArray(currentNode.a); + } + } + // parse "Property70" + parseNodeSpecialProperty(line, propName, propValue) { + const props = propValue.split('",').map(function(prop) { + return prop.trim().replace(/^\"/, "").replace(/\s/, "_"); + }); + const innerPropName = props[0]; + const innerPropType1 = props[1]; + const innerPropType2 = props[2]; + const innerPropFlag = props[3]; + let innerPropValue = props[4]; + switch (innerPropType1) { + case "int": + case "enum": + case "bool": + case "ULongLong": + case "double": + case "Number": + case "FieldOfView": + innerPropValue = parseFloat(innerPropValue); + break; + case "Color": + case "ColorRGB": + case "Vector3D": + case "Lcl_Translation": + case "Lcl_Rotation": + case "Lcl_Scaling": + innerPropValue = parseNumberArray(innerPropValue); + break; + } + this.getPrevNode()[innerPropName] = { + "type": innerPropType1, + "type2": innerPropType2, + "flag": innerPropFlag, + "value": innerPropValue + }; + this.setCurrentProp(this.getPrevNode(), innerPropName); + } + }; + var BinaryParser = class { + parse(buffer) { + const reader = new BinaryReader(buffer); + reader.skip(23); + const version = reader.getUint32(); + if (version < 6400) { + throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: " + version); + } + const allNodes = new FBXTree(); + while (!this.endOfContent(reader)) { + const node = this.parseNode(reader, version); + if (node !== null) allNodes.add(node.name, node); + } + return allNodes; + } + // Check if reader has reached the end of content. + endOfContent(reader) { + if (reader.size() % 16 === 0) { + return (reader.getOffset() + 160 + 16 & ~15) >= reader.size(); + } else { + return reader.getOffset() + 160 + 16 >= reader.size(); + } + } + // recursively parse nodes until the end of the file is reached + parseNode(reader, version) { + const node = {}; + const endOffset = version >= 7500 ? reader.getUint64() : reader.getUint32(); + const numProperties = version >= 7500 ? reader.getUint64() : reader.getUint32(); + version >= 7500 ? reader.getUint64() : reader.getUint32(); + const nameLen = reader.getUint8(); + const name = reader.getString(nameLen); + if (endOffset === 0) return null; + const propertyList = []; + for (let i = 0; i < numProperties; i++) { + propertyList.push(this.parseProperty(reader)); + } + const id = propertyList.length > 0 ? propertyList[0] : ""; + const attrName = propertyList.length > 1 ? propertyList[1] : ""; + const attrType = propertyList.length > 2 ? propertyList[2] : ""; + node.singleProperty = numProperties === 1 && reader.getOffset() === endOffset ? true : false; + while (endOffset > reader.getOffset()) { + const subNode = this.parseNode(reader, version); + if (subNode !== null) this.parseSubNode(name, node, subNode); + } + node.propertyList = propertyList; + if (typeof id === "number") node.id = id; + if (attrName !== "") node.attrName = attrName; + if (attrType !== "") node.attrType = attrType; + if (name !== "") node.name = name; + return node; + } + parseSubNode(name, node, subNode) { + if (subNode.singleProperty === true) { + const value = subNode.propertyList[0]; + if (Array.isArray(value)) { + node[subNode.name] = subNode; + subNode.a = value; + } else { + node[subNode.name] = value; + } + } else if (name === "Connections" && subNode.name === "C") { + const array = []; + subNode.propertyList.forEach(function(property, i) { + if (i !== 0) array.push(property); + }); + if (node.connections === void 0) { + node.connections = []; + } + node.connections.push(array); + } else if (subNode.name === "Properties70") { + const keys = Object.keys(subNode); + keys.forEach(function(key) { + node[key] = subNode[key]; + }); + } else if (name === "Properties70" && subNode.name === "P") { + let innerPropName = subNode.propertyList[0]; + let innerPropType1 = subNode.propertyList[1]; + const innerPropType2 = subNode.propertyList[2]; + const innerPropFlag = subNode.propertyList[3]; + let innerPropValue; + if (innerPropName.indexOf("Lcl ") === 0) innerPropName = innerPropName.replace("Lcl ", "Lcl_"); + if (innerPropType1.indexOf("Lcl ") === 0) innerPropType1 = innerPropType1.replace("Lcl ", "Lcl_"); + if (innerPropType1 === "Color" || innerPropType1 === "ColorRGB" || innerPropType1 === "Vector" || innerPropType1 === "Vector3D" || innerPropType1.indexOf("Lcl_") === 0) { + innerPropValue = [ + subNode.propertyList[4], + subNode.propertyList[5], + subNode.propertyList[6] + ]; + } else { + innerPropValue = subNode.propertyList[4]; + } + node[innerPropName] = { + "type": innerPropType1, + "type2": innerPropType2, + "flag": innerPropFlag, + "value": innerPropValue + }; + } else if (node[subNode.name] === void 0) { + if (typeof subNode.id === "number") { + node[subNode.name] = {}; + node[subNode.name][subNode.id] = subNode; + } else { + node[subNode.name] = subNode; + } + } else { + if (subNode.name === "PoseNode") { + if (!Array.isArray(node[subNode.name])) { + node[subNode.name] = [node[subNode.name]]; + } + node[subNode.name].push(subNode); + } else if (node[subNode.name][subNode.id] === void 0) { + node[subNode.name][subNode.id] = subNode; + } + } + } + parseProperty(reader) { + const type = reader.getString(1); + let length; + switch (type) { + case "C": + return reader.getBoolean(); + case "D": + return reader.getFloat64(); + case "F": + return reader.getFloat32(); + case "I": + return reader.getInt32(); + case "L": + return reader.getInt64(); + case "R": + length = reader.getUint32(); + return reader.getArrayBuffer(length); + case "S": + length = reader.getUint32(); + return reader.getString(length); + case "Y": + return reader.getInt16(); + case "b": + case "c": + case "d": + case "f": + case "i": + case "l": + const arrayLength = reader.getUint32(); + const encoding = reader.getUint32(); + const compressedLength = reader.getUint32(); + if (encoding === 0) { + switch (type) { + case "b": + case "c": + return reader.getBooleanArray(arrayLength); + case "d": + return reader.getFloat64Array(arrayLength); + case "f": + return reader.getFloat32Array(arrayLength); + case "i": + return reader.getInt32Array(arrayLength); + case "l": + return reader.getInt64Array(arrayLength); + } + } + const data = unzlibSync(new Uint8Array(reader.getArrayBuffer(compressedLength))); + const reader2 = new BinaryReader(data.buffer); + switch (type) { + case "b": + case "c": + return reader2.getBooleanArray(arrayLength); + case "d": + return reader2.getFloat64Array(arrayLength); + case "f": + return reader2.getFloat32Array(arrayLength); + case "i": + return reader2.getInt32Array(arrayLength); + case "l": + return reader2.getInt64Array(arrayLength); + } + break; + // cannot happen but is required by the DeepScan + default: + throw new Error("THREE.FBXLoader: Unknown property type " + type); + } + } + }; + var BinaryReader = class { + constructor(buffer, littleEndian) { + this.dv = new DataView(buffer); + this.offset = 0; + this.littleEndian = littleEndian !== void 0 ? littleEndian : true; + this._textDecoder = new TextDecoder(); + } + getOffset() { + return this.offset; + } + size() { + return this.dv.buffer.byteLength; + } + skip(length) { + this.offset += length; + } + // seems like true/false representation depends on exporter. + // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54) + // then sees LSB. + getBoolean() { + return (this.getUint8() & 1) === 1; + } + getBooleanArray(size) { + const a = []; + for (let i = 0; i < size; i++) { + a.push(this.getBoolean()); + } + return a; + } + getUint8() { + const value = this.dv.getUint8(this.offset); + this.offset += 1; + return value; + } + getInt16() { + const value = this.dv.getInt16(this.offset, this.littleEndian); + this.offset += 2; + return value; + } + getInt32() { + const value = this.dv.getInt32(this.offset, this.littleEndian); + this.offset += 4; + return value; + } + getInt32Array(size) { + const a = []; + for (let i = 0; i < size; i++) { + a.push(this.getInt32()); + } + return a; + } + getUint32() { + const value = this.dv.getUint32(this.offset, this.littleEndian); + this.offset += 4; + return value; + } + // JavaScript doesn't support 64-bit integer so calculate this here + // 1 << 32 will return 1 so using multiply operation instead here. + // There's a possibility that this method returns wrong value if the value + // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER. + // TODO: safely handle 64-bit integer + getInt64() { + let low, high; + if (this.littleEndian) { + low = this.getUint32(); + high = this.getUint32(); + } else { + high = this.getUint32(); + low = this.getUint32(); + } + if (high & 2147483648) { + high = ~high & 4294967295; + low = ~low & 4294967295; + if (low === 4294967295) high = high + 1 & 4294967295; + low = low + 1 & 4294967295; + return -(high * 4294967296 + low); + } + return high * 4294967296 + low; + } + getInt64Array(size) { + const a = []; + for (let i = 0; i < size; i++) { + a.push(this.getInt64()); + } + return a; + } + // Note: see getInt64() comment + getUint64() { + let low, high; + if (this.littleEndian) { + low = this.getUint32(); + high = this.getUint32(); + } else { + high = this.getUint32(); + low = this.getUint32(); + } + return high * 4294967296 + low; + } + getFloat32() { + const value = this.dv.getFloat32(this.offset, this.littleEndian); + this.offset += 4; + return value; + } + getFloat32Array(size) { + const a = []; + for (let i = 0; i < size; i++) { + a.push(this.getFloat32()); + } + return a; + } + getFloat64() { + const value = this.dv.getFloat64(this.offset, this.littleEndian); + this.offset += 8; + return value; + } + getFloat64Array(size) { + const a = []; + for (let i = 0; i < size; i++) { + a.push(this.getFloat64()); + } + return a; + } + getArrayBuffer(size) { + const value = this.dv.buffer.slice(this.offset, this.offset + size); + this.offset += size; + return value; + } + getString(size) { + const start = this.offset; + let a = new Uint8Array(this.dv.buffer, start, size); + this.skip(size); + const nullByte = a.indexOf(0); + if (nullByte >= 0) a = new Uint8Array(this.dv.buffer, start, nullByte); + return this._textDecoder.decode(a); + } + }; + var FBXTree = class { + add(key, val) { + this[key] = val; + } + }; + function isFbxFormatBinary(buffer) { + const CORRECT = "Kaydara FBX Binary \0"; + return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString(buffer, 0, CORRECT.length); + } + function isFbxFormatASCII(text) { + const CORRECT = ["K", "a", "y", "d", "a", "r", "a", "\\", "F", "B", "X", "\\", "B", "i", "n", "a", "r", "y", "\\", "\\"]; + let cursor = 0; + function read(offset) { + const result = text[offset - 1]; + text = text.slice(cursor + offset); + cursor++; + return result; + } + for (let i = 0; i < CORRECT.length; ++i) { + const num = read(1); + if (num === CORRECT[i]) { + return false; + } + } + return true; + } + function getFbxVersion(text) { + const versionRegExp = /FBXVersion: (\d+)/; + const match = text.match(versionRegExp); + if (match) { + const version = parseInt(match[1]); + return version; + } + throw new Error("THREE.FBXLoader: Cannot find the version number for the file given."); + } + function convertFBXTimeToSeconds(time) { + return time / 46186158e3; + } + var dataArray = []; + function getData(polygonVertexIndex, polygonIndex, vertexIndex, infoObject) { + let index; + switch (infoObject.mappingType) { + case "ByPolygonVertex": + index = polygonVertexIndex; + break; + case "ByPolygon": + index = polygonIndex; + break; + case "ByVertice": + index = vertexIndex; + break; + case "AllSame": + index = infoObject.indices[0]; + break; + default: + console.warn("THREE.FBXLoader: unknown attribute mapping type " + infoObject.mappingType); + } + if (infoObject.referenceType === "IndexToDirect") index = infoObject.indices[index]; + const from = index * infoObject.dataSize; + const to = from + infoObject.dataSize; + return slice(dataArray, infoObject.buffer, from, to); + } + var tempEuler = new Euler(); + var tempVec = new Vector3(); + function generateTransform(transformData) { + const lTranslationM = new Matrix4(); + const lPreRotationM = new Matrix4(); + const lRotationM = new Matrix4(); + const lPostRotationM = new Matrix4(); + const lScalingM = new Matrix4(); + const lScalingPivotM = new Matrix4(); + const lScalingOffsetM = new Matrix4(); + const lRotationOffsetM = new Matrix4(); + const lRotationPivotM = new Matrix4(); + const lParentGX = new Matrix4(); + const lParentLX = new Matrix4(); + const lGlobalT = new Matrix4(); + const inheritType = transformData.inheritType ? transformData.inheritType : 0; + if (transformData.translation) lTranslationM.setPosition(tempVec.fromArray(transformData.translation)); + if (transformData.preRotation) { + const array = transformData.preRotation.map(MathUtils.degToRad); + array.push(transformData.eulerOrder || Euler.DEFAULT_ORDER); + lPreRotationM.makeRotationFromEuler(tempEuler.fromArray(array)); + } + if (transformData.rotation) { + const array = transformData.rotation.map(MathUtils.degToRad); + array.push(transformData.eulerOrder || Euler.DEFAULT_ORDER); + lRotationM.makeRotationFromEuler(tempEuler.fromArray(array)); + } + if (transformData.postRotation) { + const array = transformData.postRotation.map(MathUtils.degToRad); + array.push(transformData.eulerOrder || Euler.DEFAULT_ORDER); + lPostRotationM.makeRotationFromEuler(tempEuler.fromArray(array)); + lPostRotationM.invert(); + } + if (transformData.scale) lScalingM.scale(tempVec.fromArray(transformData.scale)); + if (transformData.scalingOffset) lScalingOffsetM.setPosition(tempVec.fromArray(transformData.scalingOffset)); + if (transformData.scalingPivot) lScalingPivotM.setPosition(tempVec.fromArray(transformData.scalingPivot)); + if (transformData.rotationOffset) lRotationOffsetM.setPosition(tempVec.fromArray(transformData.rotationOffset)); + if (transformData.rotationPivot) lRotationPivotM.setPosition(tempVec.fromArray(transformData.rotationPivot)); + if (transformData.parentMatrixWorld) { + lParentLX.copy(transformData.parentMatrix); + lParentGX.copy(transformData.parentMatrixWorld); + } + const lLRM = lPreRotationM.clone().multiply(lRotationM).multiply(lPostRotationM); + const lParentGRM = new Matrix4(); + lParentGRM.extractRotation(lParentGX); + const lParentTM = new Matrix4(); + lParentTM.copyPosition(lParentGX); + const lParentGRSM = lParentTM.clone().invert().multiply(lParentGX); + const lParentGSM = lParentGRM.clone().invert().multiply(lParentGRSM); + const lLSM = lScalingM; + const lGlobalRS = new Matrix4(); + if (inheritType === 0) { + lGlobalRS.copy(lParentGRM).multiply(lLRM).multiply(lParentGSM).multiply(lLSM); + } else if (inheritType === 1) { + lGlobalRS.copy(lParentGRM).multiply(lParentGSM).multiply(lLRM).multiply(lLSM); + } else { + const lParentLSM = new Matrix4().scale(new Vector3().setFromMatrixScale(lParentLX)); + const lParentLSM_inv = lParentLSM.clone().invert(); + const lParentGSM_noLocal = lParentGSM.clone().multiply(lParentLSM_inv); + lGlobalRS.copy(lParentGRM).multiply(lLRM).multiply(lParentGSM_noLocal).multiply(lLSM); + } + const lRotationPivotM_inv = lRotationPivotM.clone().invert(); + const lScalingPivotM_inv = lScalingPivotM.clone().invert(); + let lTransform = lTranslationM.clone().multiply(lRotationOffsetM).multiply(lRotationPivotM).multiply(lPreRotationM).multiply(lRotationM).multiply(lPostRotationM).multiply(lRotationPivotM_inv).multiply(lScalingOffsetM).multiply(lScalingPivotM).multiply(lScalingM).multiply(lScalingPivotM_inv); + const lLocalTWithAllPivotAndOffsetInfo = new Matrix4().copyPosition(lTransform); + const lGlobalTranslation = lParentGX.clone().multiply(lLocalTWithAllPivotAndOffsetInfo); + lGlobalT.copyPosition(lGlobalTranslation); + lTransform = lGlobalT.clone().multiply(lGlobalRS); + lTransform.premultiply(lParentGX.invert()); + return lTransform; + } + function getEulerOrder(order) { + order = order || 0; + const enums = [ + "ZYX", + // -> XYZ extrinsic + "YZX", + // -> XZY extrinsic + "XZY", + // -> YZX extrinsic + "ZXY", + // -> YXZ extrinsic + "YXZ", + // -> ZXY extrinsic + "XYZ" + // -> ZYX extrinsic + //'SphericXYZ', // not possible to support + ]; + if (order === 6) { + console.warn("THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect."); + return enums[0]; + } + return enums[order]; + } + function parseNumberArray(value) { + const array = value.split(",").map(function(val) { + return parseFloat(val); + }); + return array; + } + function convertArrayBufferToString(buffer, from, to) { + if (from === void 0) from = 0; + if (to === void 0) to = buffer.byteLength; + return new TextDecoder().decode(new Uint8Array(buffer, from, to)); + } + function append(a, b) { + for (let i = 0, j = a.length, l = b.length; i < l; i++, j++) { + a[j] = b[i]; + } + } + function slice(a, b, from, to) { + for (let i = from, j = 0; i < to; i++, j++) { + a[j] = b[i]; + } + return a; + } + + // examples/jsm/utils/TextureUtils.js + var _renderer; + var fullscreenQuadGeometry; + var fullscreenQuadMaterial; + var fullscreenQuad; + function decompress(texture, maxTextureSize = Infinity, renderer = null) { + if (!fullscreenQuadGeometry) fullscreenQuadGeometry = new PlaneGeometry(2, 2, 1, 1); + if (!fullscreenQuadMaterial) fullscreenQuadMaterial = new ShaderMaterial({ + uniforms: { blitTexture: new Uniform(texture) }, + vertexShader: ` + varying vec2 vUv; + void main(){ + vUv = uv; + gl_Position = vec4(position.xy * 1.0,0.,.999999); + }`, + fragmentShader: ` + uniform sampler2D blitTexture; + varying vec2 vUv; + + void main(){ + gl_FragColor = vec4(vUv.xy, 0, 1); + + #ifdef IS_SRGB + gl_FragColor = LinearTosRGB( texture2D( blitTexture, vUv) ); + #else + gl_FragColor = texture2D( blitTexture, vUv); + #endif + }` + }); + fullscreenQuadMaterial.uniforms.blitTexture.value = texture; + fullscreenQuadMaterial.defines.IS_SRGB = texture.colorSpace == SRGBColorSpace; + fullscreenQuadMaterial.needsUpdate = true; + if (!fullscreenQuad) { + fullscreenQuad = new Mesh(fullscreenQuadGeometry, fullscreenQuadMaterial); + fullscreenQuad.frustrumCulled = false; + } + const _camera2 = new PerspectiveCamera(); + const _scene = new Scene(); + _scene.add(fullscreenQuad); + if (renderer === null) { + renderer = _renderer = new WebGLRenderer({ antialias: false }); + } + const width = Math.min(texture.image.width, maxTextureSize); + const height = Math.min(texture.image.height, maxTextureSize); + renderer.setSize(width, height); + renderer.clear(); + renderer.render(_scene, _camera2); + const canvas = document.createElement("canvas"); + const context = canvas.getContext("2d"); + canvas.width = width; + canvas.height = height; + context.drawImage(renderer.domElement, 0, 0, width, height); + const readableTexture = new CanvasTexture(canvas); + readableTexture.minFilter = texture.minFilter; + readableTexture.magFilter = texture.magFilter; + readableTexture.wrapS = texture.wrapS; + readableTexture.wrapT = texture.wrapT; + readableTexture.name = texture.name; + if (_renderer) { + _renderer.forceContextLoss(); + _renderer.dispose(); + _renderer = null; + } + return readableTexture; + } + + // examples/jsm/exporters/GLTFExporter.js + var 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" + ] + }; + var GLTFExporter = class { + constructor() { + 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 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); + }); + } + register(callback) { + if (this.pluginCallbacks.indexOf(callback) === -1) { + this.pluginCallbacks.push(callback); + } + return this; + } + unregister(callback) { + if (this.pluginCallbacks.indexOf(callback) !== -1) { + this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1); + } + return this; + } + /** + * Parse scenes and generate GLTF output + * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes + * @param {Function} onDone Callback on completed + * @param {Function} onError Callback on errors + * @param {Object} 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.write(input, onDone, options).catch(onError); + } + parseAsync(input, options) { + const scope = this; + return new Promise(function(resolve, reject) { + scope.parse(input, resolve, reject, options); + }); + } + }; + var WEBGL_CONSTANTS = { + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6, + BYTE: 5120, + UNSIGNED_BYTE: 5121, + SHORT: 5122, + UNSIGNED_SHORT: 5123, + INT: 5124, + UNSIGNED_INT: 5125, + FLOAT: 5126, + ARRAY_BUFFER: 34962, + ELEMENT_ARRAY_BUFFER: 34963, + NEAREST: 9728, + LINEAR: 9729, + NEAREST_MIPMAP_NEAREST: 9984, + LINEAR_MIPMAP_NEAREST: 9985, + NEAREST_MIPMAP_LINEAR: 9986, + LINEAR_MIPMAP_LINEAR: 9987, + CLAMP_TO_EDGE: 33071, + MIRRORED_REPEAT: 33648, + REPEAT: 10497 + }; + var KHR_MESH_QUANTIZATION = "KHR_mesh_quantization"; + var 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; + var PATH_PROPERTIES = { + scale: "scale", + position: "translation", + quaternion: "rotation", + morphTargetInfluences: "weights" + }; + var DEFAULT_SPECULAR_COLOR = new Color(); + var GLB_HEADER_BYTES = 12; + var GLB_HEADER_MAGIC = 1179937895; + var GLB_VERSION = 2; + var GLB_CHUNK_PREFIX_BYTES = 8; + var GLB_CHUNK_TYPE_JSON = 1313821514; + var GLB_CHUNK_TYPE_BIN = 5130562; + function equalArray(array1, array2) { + return array1.length === array2.length && array1.every(function(element, index) { + return element === array2[index]; + }); + } + function stringToArrayBuffer(text) { + return new TextEncoder().encode(text).buffer; + } + function isIdentityMatrix(matrix) { + return equalArray(matrix.elements, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); + } + 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) { + 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; + } + function getPaddedBufferSize(bufferSize) { + return Math.ceil(bufferSize / 4) * 4; + } + 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 (canvas.toBlob !== void 0) { + return new Promise((resolve) => canvas.toBlob(resolve, mimeType)); + } + let quality; + if (mimeType === "image/jpeg") { + quality = 0.92; + } else if (mimeType === "image/webp") { + quality = 0.8; + } + return canvas.convertToBlob({ + type: mimeType, + quality + }); + } + var GLTFWriter = class { + constructor() { + this.plugins = []; + this.options = {}; + this.pending = []; + this.buffers = []; + this.byteOffset = 0; + this.buffers = []; + this.nodeMap = /* @__PURE__ */ new Map(); + this.skins = []; + this.extensionsUsed = {}; + this.extensionsRequired = {}; + this.uids = /* @__PURE__ */ new Map(); + this.uid = 0; + this.json = { + asset: { + version: "2.0", + generator: "THREE.GLTFExporter" + } + }; + this.cache = { + meshes: /* @__PURE__ */ new Map(), + attributes: /* @__PURE__ */ new Map(), + attributesNormalized: /* @__PURE__ */ new Map(), + materials: /* @__PURE__ */ new Map(), + textures: /* @__PURE__ */ new Map(), + images: /* @__PURE__ */ new Map() + }; + } + setPlugins(plugins) { + this.plugins = plugins; + } + /** + * Parse scenes and generate GLTF output + * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes + * @param {Function} onDone Callback on completed + * @param {Object} options options + */ + async write(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) { + this.options.trs = true; + } + this.processInput(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; + const blob = new Blob(buffers, { type: "application/octet-stream" }); + const extensionsUsedList = Object.keys(extensionsUsed); + const extensionsRequiredList = Object.keys(extensionsRequired); + if (extensionsUsedList.length > 0) json.extensionsUsed = extensionsUsedList; + if (extensionsRequiredList.length > 0) json.extensionsRequired = extensionsRequiredList; + if (json.buffers && json.buffers.length > 0) json.buffers[0].byteLength = blob.size; + if (options.binary === true) { + const reader = new FileReader(); + reader.readAsArrayBuffer(blob); + reader.onloadend = function() { + 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); + const jsonChunk = getPaddedArrayBuffer(stringToArrayBuffer(JSON.stringify(json)), 32); + const jsonChunkPrefix = new DataView(new ArrayBuffer(GLB_CHUNK_PREFIX_BYTES)); + jsonChunkPrefix.setUint32(0, jsonChunk.byteLength, true); + jsonChunkPrefix.setUint32(4, GLB_CHUNK_TYPE_JSON, true); + 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} 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 === void 0) 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} object + * @return {Integer} + */ + getUID(attribute, isRelativeCopy = false) { + if (this.uids.has(attribute) === false) { + const uids2 = /* @__PURE__ */ new Map(); + uids2.set(true, this.uid++); + uids2.set(false, this.uid++); + this.uids.set(attribute, uids2); + } + 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++) { + if (Math.abs(v.fromBufferAttribute(normal, i).length() - 1) > 5e-4) 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) { + v.setX(1); + } 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; + } + } + buildMetalRoughTexture(metalnessMap, roughnessMap) { + if (metalnessMap === roughnessMap) return metalnessMap; + function getEncodingConversion(map) { + if (map.colorSpace === SRGBColorSpace) { + return function SRGBToLinear2(c) { + return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4); + }; + } + return function LinearToLinear(c) { + return c; + }; + } + console.warn("THREE.GLTFExporter: Merged metalnessMap and roughnessMap textures."); + if (metalnessMap instanceof CompressedTexture) { + metalnessMap = decompress(metalnessMap); + } + if (roughnessMap instanceof CompressedTexture) { + roughnessMap = decompress(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"); + 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."); + } + return texture; + } + /** + * Process a buffer to append to the default one. + * @param {ArrayBuffer} buffer + * @return {Integer} + */ + processBuffer(buffer) { + const json = this.json; + const buffers = this.buffers; + if (!json.buffers) json.buffers = [{ byteLength: 0 }]; + 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 (Optional) Target usage of the BufferView + * @return {Object} + */ + processBufferView(attribute, componentType, start, count, target) { + const json = this.json; + if (!json.bufferViews) json.bufferViews = []; + 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; + } + const byteLength = getPaddedBufferSize(count * attribute.itemSize * componentSize); + 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) { + 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; + } + } + const bufferViewDef = { + buffer: this.processBuffer(dataView.buffer), + byteOffset: this.byteOffset, + byteLength + }; + if (target !== void 0) bufferViewDef.target = target; + if (target === WEBGL_CONSTANTS.ARRAY_BUFFER) { + bufferViewDef.byteStride = attribute.itemSize * componentSize; + } + this.byteOffset += byteLength; + json.bufferViews.push(bufferViewDef); + 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} + */ + 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 {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range + * @param {Integer} start (Optional) + * @param {Integer} count (Optional) + * @return {Integer|null} 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; + 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 === void 0) start = 0; + if (count === void 0 || count === Infinity) count = attribute.count; + if (count === 0) return null; + const minMax = getMinMax(attribute, start, count); + let bufferViewTarget; + if (geometry !== void 0) { + 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, + 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 {Integer} format of the image (RGBAFormat) + * @param {Boolean} flipY before writing out the image + * @param {String} mimeType export format + * @return {Integer} 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] !== void 0) return cachedImages[key]; + if (!json.images) json.images = []; + const imageDef = { 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"); + if (flipY === true) { + ctx.translate(0, canvas.height); + ctx.scale(1, -1); + } + if (image.data !== void 0) { + 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 { + ctx.drawImage(image, 0, 0, canvas.width, canvas.height); + } + if (options.binary === true) { + pending.push( + getToBlobPromise(canvas, mimeType).then((blob) => writer.processBufferViewImage(blob)).then((bufferViewIndex) => { + imageDef.bufferView = bufferViewIndex; + }) + ); + } else { + if (canvas.toDataURL !== void 0) { + imageDef.uri = canvas.toDataURL(mimeType); + } else { + pending.push( + getToBlobPromise(canvas, mimeType).then((blob) => new FileReader().readAsDataURL(blob)).then((dataURL) => { + imageDef.uri = dataURL; + }) + ); + } + } + 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 {Integer} 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 {Integer} Index of the processed texture in the "textures" array + */ + processTexture(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 = []; + if (map instanceof CompressedTexture) { + map = decompress(map, options.maxTextureSize); + } + let mimeType = map.userData.mimeType; + if (mimeType === "image/webp") mimeType = "image/png"; + const textureDef = { + sampler: this.processSampler(map), + source: this.processImage(map.image, map.format, map.flipY, mimeType) + }; + if (map.name) textureDef.name = map.name; + this._invokeAll(function(ext) { + ext.writeTexture && 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 + * @return {Integer|null} Index of the processed material in the "materials" array + */ + processMaterial(material) { + const cache = this.cache; + const json = this.json; + if (cache.materials.has(material)) return cache.materials.get(material); + if (material.isShaderMaterial) { + console.warn("GLTFExporter: THREE.ShaderMaterial not supported."); + return null; + } + if (!json.materials) json.materials = []; + const materialDef = { pbrMetallicRoughness: {} }; + if (material.isMeshStandardMaterial !== true && material.isMeshBasicMaterial !== true) { + console.warn("GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results."); + } + 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.5; + materialDef.pbrMetallicRoughness.roughnessFactor = 0.5; + } + if (material.metalnessMap || material.roughnessMap) { + const metalRoughTexture = this.buildMetalRoughTexture(material.metalnessMap, material.roughnessMap); + const metalRoughMapDef = { + index: this.processTexture(metalRoughTexture), + channel: metalRoughTexture.channel + }; + this.applyTextureTransform(metalRoughMapDef, metalRoughTexture); + materialDef.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef; + } + if (material.map) { + const baseColorMapDef = { + index: this.processTexture(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(); + } + if (material.emissiveMap) { + const emissiveMapDef = { + index: this.processTexture(material.emissiveMap), + texCoord: material.emissiveMap.channel + }; + this.applyTextureTransform(emissiveMapDef, material.emissiveMap); + materialDef.emissiveTexture = emissiveMapDef; + } + } + if (material.normalMap) { + const normalMapDef = { + index: this.processTexture(material.normalMap), + texCoord: material.normalMap.channel + }; + if (material.normalScale && material.normalScale.x !== 1) { + normalMapDef.scale = material.normalScale.x; + } + this.applyTextureTransform(normalMapDef, material.normalMap); + materialDef.normalTexture = normalMapDef; + } + if (material.aoMap) { + const occlusionMapDef = { + index: this.processTexture(material.aoMap), + texCoord: material.aoMap.channel + }; + if (material.aoMapIntensity !== 1) { + occlusionMapDef.strength = material.aoMapIntensity; + } + this.applyTextureTransform(occlusionMapDef, material.aoMap); + materialDef.occlusionTexture = occlusionMapDef; + } + if (material.transparent) { + materialDef.alphaMode = "BLEND"; + } else { + if (material.alphaTest > 0) { + materialDef.alphaMode = "MASK"; + materialDef.alphaCutoff = material.alphaTest; + } + } + if (material.side === DoubleSide) materialDef.doubleSided = true; + if (material.name !== "") materialDef.name = material.name; + this.serializeUserData(material, materialDef); + this._invokeAll(function(ext) { + ext.writeMaterial && ext.writeMaterial(material, materialDef); + }); + const index = json.materials.push(materialDef) - 1; + cache.materials.set(material, index); + return index; + } + /** + * Process mesh + * @param {THREE.Mesh} mesh Mesh to process + * @return {Integer|null} Index of the processed mesh in the "meshes" array + */ + processMesh(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; + 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 = []; + 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 !== void 0 && !this.isNormalizedNormalAttribute(originalNormal)) { + console.warn("THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one."); + geometry.setAttribute("normal", this.createNormalizedNormalAttribute(originalNormal)); + } + let modifiedAttribute = null; + for (let attributeName in geometry.attributes) { + if (attributeName.slice(0, 5) === "morph") continue; + const attribute = geometry.attributes[attributeName]; + attributeName = nameConversion[attributeName] || attributeName.toUpperCase(); + const validVertexAttributes = /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/; + if (!validVertexAttributes.test(attributeName)) attributeName = "_" + attributeName; + if (cache.attributes.has(this.getUID(attribute))) { + attributes[attributeName] = cache.attributes.get(this.getUID(attribute)); + continue; + } + 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 = new BufferAttribute(new Uint16Array(array), attribute.itemSize, attribute.normalized); + } + 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 !== void 0) geometry.setAttribute("normal", originalNormal); + if (Object.keys(attributes).length === 0) return null; + if (mesh.morphTargetInfluences !== void 0 && mesh.morphTargetInfluences.length > 0) { + const weights = []; + const targetNames = []; + const reverseDictionary = {}; + if (mesh.morphTargetDictionary !== void 0) { + 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) { + 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(); + const baseAttribute = geometry.attributes[attributeName]; + if (cache.attributes.has(this.getUID(attribute, true))) { + target[gltfAttributeName] = cache.attributes.get(this.getUID(attribute, true)); + continue; + } + 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 !== void 0) 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: void 0, count: void 0 }]; + for (let i = 0, il = groups.length; i < il; i++) { + const primitive = { + mode, + 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 !== void 0 || groups[i].count !== void 0) { + 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 = this.processMaterial(materials[groups[i].materialIndex]); + if (material !== null) primitive.material = material; + primitives.push(primitive); + } + if (didForceIndices === true) { + geometry.setIndex(null); + } + meshDef.primitives = primitives; + if (!json.meshes) json.meshes = []; + this._invokeAll(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 = void 0; + 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 {Integer} 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 ? 1e-3 : camera.far, + znear: camera.near < 0 ? 0 : camera.near + }; + } else { + cameraDef.perspective = { + aspectRatio: camera.aspect, + yfov: MathUtils.degToRad(camera.fov), + zfar: camera.far <= 0 ? 1e-3 : camera.far, + znear: camera.near < 0 ? 0 : camera.near + }; + } + 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|null} + */ + 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 = void 0; + } + } + if (!trackNode || !trackProperty) { + console.warn('THREE.GLTFExporter: Could not export animation track "%s".', track.name); + return null; + } + const inputItemSize = 1; + let outputItemSize = track.values.length / track.times.length; + if (trackProperty === PATH_PROPERTIES.morphTargetInfluences) { + outputItemSize /= trackNode.morphTargetInfluences.length; + } + let interpolation; + if (track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true) { + interpolation = "CUBICSPLINE"; + 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 + }); + channels.push({ + sampler: samplers.length - 1, + target: { + node: nodeMap.get(trackNode), + path: trackProperty + } + }); + } + json.animations.push({ + name: clip.name || "clip_" + json.animations.length, + samplers, + channels + }); + return json.animations.length - 1; + } + /** + * @param {THREE.Object3D} object + * @return {number|null} + */ + processSkin(object) { + const json = this.json; + const nodeMap = this.nodeMap; + const node = json.nodes[nodeMap.get(object)]; + const skeleton = object.skeleton; + if (skeleton === void 0) return null; + const rootJoint = object.skeleton.bones[0]; + if (rootJoint === void 0) 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 === void 0) json.skins = []; + json.skins.push({ + inverseBindMatrices: this.processAccessor(new BufferAttribute(inverseBindMatrices, 16)), + joints, + skeleton: nodeMap.get(rootJoint) + }); + const skinIndex = node.skin = json.skins.length - 1; + return skinIndex; + } + /** + * Process Object3D node + * @param {THREE.Object3D} node Object3D to processNode + * @return {Integer} Index of the node in the nodes list + */ + processNode(object) { + const json = this.json; + const options = this.options; + const nodeMap = this.nodeMap; + if (!json.nodes) json.nodes = []; + 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; + } + } + if (object.name !== "") nodeDef.name = String(object.name); + this.serializeUserData(object, nodeDef); + if (object.isMesh || object.isLine || object.isPoints) { + const meshIndex = this.processMesh(object); + if (meshIndex !== null) nodeDef.mesh = meshIndex; + } else if (object.isCamera) { + nodeDef.camera = this.processCamera(object); + } + if (object.isSkinnedMesh) this.skins.push(object); + 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 nodeIndex2 = this.processNode(child); + if (nodeIndex2 !== null) children.push(nodeIndex2); + } + } + if (children.length > 0) nodeDef.children = children; + } + this._invokeAll(function(ext) { + ext.writeNode && ext.writeNode(object, nodeDef); + }); + const nodeIndex = json.nodes.push(nodeDef) - 1; + nodeMap.set(object, nodeIndex); + return nodeIndex; + } + /** + * Process Scene + * @param {Scene} node Scene to process + */ + processScene(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 = this.processNode(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 + */ + processObjects(objects) { + const scene = new Scene(); + scene.name = "AuxScene"; + for (let i = 0; i < objects.length; i++) { + scene.children.push(objects[i]); + } + this.processScene(scene); + } + /** + * @param {THREE.Object3D|Array} input + */ + processInput(input) { + const options = this.options; + input = input instanceof Array ? input : [input]; + this._invokeAll(function(ext) { + ext.beforeParse && ext.beforeParse(input); + }); + const objectsWithoutScene = []; + for (let i = 0; i < input.length; i++) { + if (input[i] instanceof Scene) { + this.processScene(input[i]); + } else { + objectsWithoutScene.push(input[i]); + } + } + if (objectsWithoutScene.length > 0) this.processObjects(objectsWithoutScene); + for (let i = 0; i < this.skins.length; ++i) { + this.processSkin(this.skins[i]); + } + for (let i = 0; i < options.animations.length; ++i) { + this.processAnimation(options.animations[i], input[0]); + } + this._invokeAll(function(ext) { + ext.afterParse && ext.afterParse(input); + }); + } + _invokeAll(func) { + for (let i = 0, il = this.plugins.length; i < il; i++) { + func(this.plugins[i]); + } + } + }; + var GLTFLightExtension = class { + 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 - light.penumbra) * light.angle; + lightDef.spot.outerConeAngle = light.angle; + } + if (light.decay !== void 0 && 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 }; + } + }; + var GLTFMaterialsUnlitExtension = class { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_unlit"; + } + writeMaterial(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; + materialDef.pbrMetallicRoughness.roughnessFactor = 0.9; + } + }; + var GLTFMaterialsClearcoatExtension = class { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_clearcoat"; + } + writeMaterial(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: writer.processTexture(material.clearcoatMap), + texCoord: material.clearcoatMap.channel + }; + writer.applyTextureTransform(clearcoatMapDef, material.clearcoatMap); + extensionDef.clearcoatTexture = clearcoatMapDef; + } + extensionDef.clearcoatRoughnessFactor = material.clearcoatRoughness; + if (material.clearcoatRoughnessMap) { + const clearcoatRoughnessMapDef = { + index: writer.processTexture(material.clearcoatRoughnessMap), + texCoord: material.clearcoatRoughnessMap.channel + }; + writer.applyTextureTransform(clearcoatRoughnessMapDef, material.clearcoatRoughnessMap); + extensionDef.clearcoatRoughnessTexture = clearcoatRoughnessMapDef; + } + if (material.clearcoatNormalMap) { + const clearcoatNormalMapDef = { + index: writer.processTexture(material.clearcoatNormalMap), + texCoord: material.clearcoatNormalMap.channel + }; + writer.applyTextureTransform(clearcoatNormalMapDef, material.clearcoatNormalMap); + extensionDef.clearcoatNormalTexture = clearcoatNormalMapDef; + } + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } + }; + var GLTFMaterialsIridescenceExtension = class { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_iridescence"; + } + writeMaterial(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: writer.processTexture(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: writer.processTexture(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; + } + }; + var GLTFMaterialsTransmissionExtension = class { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_transmission"; + } + writeMaterial(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: writer.processTexture(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; + } + }; + var GLTFMaterialsVolumeExtension = class { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_volume"; + } + writeMaterial(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: writer.processTexture(material.thicknessMap), + texCoord: material.thicknessMap.channel + }; + writer.applyTextureTransform(thicknessMapDef, material.thicknessMap); + extensionDef.thicknessTexture = thicknessMapDef; + } + extensionDef.attenuationDistance = material.attenuationDistance; + extensionDef.attenuationColor = material.attenuationColor.toArray(); + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } + }; + var GLTFMaterialsIorExtension = class { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_ior"; + } + writeMaterial(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; + } + }; + var GLTFMaterialsSpecularExtension = class { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_specular"; + } + writeMaterial(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.specularIntensity === 1 && 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: writer.processTexture(material.specularIntensityMap), + texCoord: material.specularIntensityMap.channel + }; + writer.applyTextureTransform(specularIntensityMapDef, material.specularIntensityMap); + extensionDef.specularTexture = specularIntensityMapDef; + } + if (material.specularColorMap) { + const specularColorMapDef = { + index: writer.processTexture(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; + } + }; + var GLTFMaterialsSheenExtension = class { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_sheen"; + } + writeMaterial(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.sheen == 0) return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + if (material.sheenRoughnessMap) { + const sheenRoughnessMapDef = { + index: writer.processTexture(material.sheenRoughnessMap), + texCoord: material.sheenRoughnessMap.channel + }; + writer.applyTextureTransform(sheenRoughnessMapDef, material.sheenRoughnessMap); + extensionDef.sheenRoughnessTexture = sheenRoughnessMapDef; + } + if (material.sheenColorMap) { + const sheenColorMapDef = { + index: writer.processTexture(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; + } + }; + var GLTFMaterialsAnisotropyExtension = class { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_anisotropy"; + } + writeMaterial(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.anisotropy == 0) return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + if (material.anisotropyMap) { + const anisotropyMapDef = { index: writer.processTexture(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; + } + }; + var GLTFMaterialsEmissiveStrengthExtension = class { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_emissive_strength"; + } + writeMaterial(material, materialDef) { + if (!material.isMeshStandardMaterial || material.emissiveIntensity === 1) 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; + } + }; + var GLTFMaterialsBumpExtension = class { + constructor(writer) { + this.writer = writer; + this.name = "EXT_materials_bump"; + } + writeMaterial(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: writer.processTexture(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; + } + }; + var GLTFMeshGpuInstancing = class { + 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; + } + }; + GLTFExporter.Utils = { + insertKeyframe: function(track, time) { + const tolerance = 1e-3; + 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 === void 0) { + tracks.push(sourceTrack); + continue; + } + if (sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear) { + if (sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { + 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 === void 0) { + throw new Error("THREE.GLTFExporter: Morph target name not found: " + sourceTrackBinding.propertyIndex); + } + let mergedTrack; + if (mergedTracks[sourceTrackNode.uuid] === void 0) { + 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]; + } + 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 (let j = 0; j < mergedTrack.times.length; j++) { + mergedTrack.values[j * targetCount + targetIndex] = sourceInterpolant.evaluate(mergedTrack.times[j]); + } + 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; + } + }; + + // bundle-entry.js + window.THREE = three_module_exports; + window.OrbitControls = OrbitControls; + window.TransformControls = TransformControls; + window.FBXLoader = FBXLoader; + window.GLTFExporter = GLTFExporter; +})(); +/** + * @license + * Copyright 2010-2023 Three.js Authors + * SPDX-License-Identifier: MIT + */ +/*! +fflate - fast JavaScript compression/decompression + +Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE +version 0.6.9 +*/ diff --git a/javascript/js/viewer-bundle-vtk.js b/javascript/js/viewer-bundle-vtk.js new file mode 100644 index 00000000..dea138b4 --- /dev/null +++ b/javascript/js/viewer-bundle-vtk.js @@ -0,0 +1,2 @@ +/*! For license information please see viewer-bundle-vtk.js.LICENSE.txt */ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.GeomPackViewer=t():e.GeomPackViewer=t()}(globalThis,()=>(()=>{"use strict";var e={d:(t,r)=>{for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};function r(e,t,r){var n=Math.round(255*e),o=Math.round(255*t),i=Math.round(255*r);return"rgb(".concat(n,", ").concat(o,", ").concat(i,")")}function n(e){return 3===(e=e.replace(/^#/,"")).length&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]),[parseInt(e.substr(0,2),16)/255,parseInt(e.substr(2,2),16)/255,parseInt(e.substr(4,2),16)/255]}function o(e,t,r){var n=function(e){var t=Math.round(255*e).toString(16);return 1===t.length?"0"+t:t};return"#"+n(e)+n(t)+n(r)}e.r(t),e.d(t,{ActorManager:()=>Z,AxisIndicator:()=>xt,BaseViewer:()=>ir,BoundsUtils:()=>d,CameraController:()=>R,ColorUtils:()=>i,ControlTypes:()=>le,ControlsBar:()=>pe,DualLayoutMode:()=>Jr,DualViewer:()=>tn,FieldVisualization:()=>It,FormatTypes:()=>qe,GLTFLoader:()=>He,LoaderFactory:()=>ct,MessageHandler:()=>P,MessageTypes:()=>g,OBJLoader:()=>ke,Representation:()=>X,STLLoader:()=>me,ScreenshotCapture:()=>gt,SettingTypes:()=>te,SettingsPanel:()=>ie,StandardControls:()=>ue,StandardViewer:()=>Cr,TextureManager:()=>Ut,TexturedViewer:()=>Rr,VTPLoader:()=>_e,ViewerFactory:()=>sn,ViewerTypes:()=>an,combineBounds:()=>f,createDualViewer:()=>en,createMessageListener:()=>S,createStandardViewer:()=>Sr,createTexturedViewer:()=>Br,default:()=>cn,detectFormat:()=>Je,extractFilename:()=>C,getCenter:()=>c,getDimensions:()=>u,getLoaderConfig:()=>st,getMaxDimension:()=>l,hexToRgb:()=>n,isValidBounds:()=>p,loadMesh:()=>nt,loadMeshes:()=>it,requiresRenderer:()=>$e,rgbToHex:()=>o,rgbToString:()=>r,sendError:()=>m,sendMeshLoaded:()=>O,sendScreenshot:()=>w,sendToParent:()=>b,supportsFields:()=>et,supportsTextures:()=>Qe});const i={rgbToString:r,hexToRgb:n,rgbToHex:o};function a(e,t){if(e){if("string"==typeof e)return s(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?s(e,t):void 0}}function s(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,i=!0,s=!1;return{s:function(){t=t.call(e)},n:function(){var e=t.next();return i=e.done,e},e:function(e){s=!0,o=e},f:function(){try{i||null==t.return||t.return()}finally{if(s)throw o}}}}(e);try{for(r.s();!(t=r.n()).done;){var n=t.value;if(!Number.isFinite(n))return!1}}catch(e){r.e(e)}finally{r.f()}return e[1]>=e[0]&&e[3]>=e[2]&&e[5]>=e[4]}const d={getCenter:c,getMaxDimension:l,getDimensions:u,combineBounds:f,isValidBounds:p};function h(e){return h="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},h(e)}function y(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function v(e,t,r){return(t=function(e){var t=function(e){if("object"!=h(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var r=t.call(e,"string");if("object"!=h(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==h(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var g={LOAD_MESH:"LOAD_MESH",LOAD_DUAL_MESH:"LOAD_DUAL_MESH",MESH_LOADED:"MESH_LOADED",MESH_ERROR:"MESH_ERROR",SCREENSHOT:"SCREENSHOT"};function b(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};window.parent&&window.parent!==window&&window.parent.postMessage(function(e){for(var t=1;te.length)&&(t=e.length);for(var r=0,n=Array(t);r2&&void 0!==arguments[2]?arguments[2]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.renderer=t,this.renderWindow=r,this.config=x(x({},_),n),this.currentBounds=null},t=[{key:"getCamera",value:function(){return this.renderer.getActiveCamera()}},{key:"setBounds",value:function(e){this.currentBounds=e}},{key:"positionInitialCamera",value:function(e){this.currentBounds=e;var t=this.getCamera(),r=c(e),n=l(e)*this.config.distanceMultiplier,o=this.config.initialViewOffset,i=[r[0]+o[0]*n,r[1]+o[1]*n,r[2]+o[2]*n];t.setPosition.apply(t,i),t.setFocalPoint.apply(t,k(r)),t.setViewUp.apply(t,k(this.config.initialViewUp)),this.renderer.resetCamera(),this.renderWindow.render()}},{key:"setCameraView",value:function(e){var t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:null)||this.currentBounds;if(t){var r=L[e];if(r){var n=this.getCamera(),o=c(t),i=l(t)*this.config.distanceMultiplier,a=[o[0]+r.offset[0]*i,o[1]+r.offset[1]*i,o[2]+r.offset[2]*i];n.setPosition.apply(n,a),n.setFocalPoint.apply(n,k(o)),n.setViewUp.apply(n,k(r.viewUp)),this.renderer.resetCamera(),this.renderWindow.render()}else console.warn("[CameraController] Unknown view direction: ".concat(e))}else console.warn("[CameraController] No bounds available for setCameraView")}},{key:"resetCamera",value:function(){this.currentBounds?this.renderer.resetCamera(this.currentBounds):this.renderer.resetCamera(),this.renderWindow.render()}},{key:"resetClippingRange",value:function(){this.renderer.resetCameraClippingRange(),this.renderWindow.render()}},{key:"setParallelProjection",value:function(e){this.getCamera().setParallelProjection(e),this.renderWindow.render()}},{key:"getParallelProjection",value:function(){return this.getCamera().getParallelProjection()}},{key:"synchronizeFrom",value:function(e){var t=this.getCamera();t.setPosition.apply(t,k(e.getPosition())),t.setFocalPoint.apply(t,k(e.getFocalPoint())),t.setViewUp.apply(t,k(e.getViewUp())),t.setParallelProjection(e.getParallelProjection()),t.setClippingRange.apply(t,k(e.getClippingRange())),t.setParallelScale(e.getParallelScale()),t.setViewAngle(e.getViewAngle())}},{key:"getState",value:function(){var e=this.getCamera();return{position:e.getPosition(),focalPoint:e.getFocalPoint(),viewUp:e.getViewUp(),parallelProjection:e.getParallelProjection(),clippingRange:e.getClippingRange(),parallelScale:e.getParallelScale(),viewAngle:e.getViewAngle()}}},{key:"setState",value:function(e){var t=this.getCamera();e.position&&t.setPosition.apply(t,k(e.position)),e.focalPoint&&t.setFocalPoint.apply(t,k(e.focalPoint)),e.viewUp&&t.setViewUp.apply(t,k(e.viewUp)),void 0!==e.parallelProjection&&t.setParallelProjection(e.parallelProjection),e.clippingRange&&t.setClippingRange.apply(t,k(e.clippingRange)),void 0!==e.parallelScale&&t.setParallelScale(e.parallelScale),void 0!==e.viewAngle&&t.setViewAngle(e.viewAngle),this.renderWindow.render()}},{key:"focusOnPoint",value:function(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=this.getCamera(),o=n.getFocalPoint(),i=n.getPosition(),a=[i[0]-o[0],i[1]-o[1],i[2]-o[2]],s=Math.sqrt(Math.pow(a[0],2)+Math.pow(a[1],2)+Math.pow(a[2],2));s>0?(a[0]/=s,a[1]/=s,a[2]/=s):(a[0]=0,a[1]=0,a[2]=1),t=null!==r?r*this.config.distanceMultiplier:this.currentBounds?.3*l(this.currentBounds):10;var c=[e[0]+a[0]*t,e[1]+a[1]*t,e[2]+a[2]*t];n.setFocalPoint.apply(n,k(e)),n.setPosition.apply(n,c),this.renderer.resetCameraClippingRange(),this.renderWindow.render()}}],t&&M(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();const R=B;function V(e){return V="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},V(e)}function I(e){return function(e){if(Array.isArray(e))return D(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return D(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?D(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function D(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r-1&&this.actors.splice(t,1)}},{key:"clearActors",value:function(){this.actors=[]}},{key:"setActors",value:function(e){var t=this;this.actors=Array.isArray(e)?e:[e],this.actors.forEach(function(e){return t.configureActor(e,t.settings)})}},{key:"configureActor",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=z(z({},this.settings),t),o=e.getProperty();if(o){if(r.color){var i="string"==typeof r.color?n(r.color):r.color;o.setColor.apply(o,I(i))}if(r.edgeColor){var a="string"==typeof r.edgeColor?n(r.edgeColor):r.edgeColor;o.setEdgeColor.apply(o,I(a))}void 0!==r.ambient&&o.setAmbient(r.ambient),void 0!==r.diffuse&&o.setDiffuse(r.diffuse),void 0!==r.specular&&o.setSpecular(r.specular),void 0!==r.specularPower&&o.setSpecularPower(r.specularPower),void 0!==r.edgeVisibility&&o.setEdgeVisibility(r.edgeVisibility),void 0!==r.lineWidth&&o.setLineWidth(r.lineWidth),void 0!==r.pointSize&&o.setPointSize(r.pointSize),void 0!==r.representation&&o.setRepresentation(r.representation),void 0!==r.opacity&&o.setOpacity(r.opacity)}else console.warn("[ActorManager] Actor has no property object")}},{key:"applySettings",value:function(e){var t=this,r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];this.settings=z(z({},this.settings),e),this.actors.forEach(function(e){return t.configureActor(e,t.settings)}),r&&this.renderWindow.render()}},{key:"setEdgeVisibility",value:function(e){this.applySettings({edgeVisibility:e})}},{key:"setColor",value:function(e){this.applySettings({color:e})}},{key:"setOpacity",value:function(e){this.applySettings({opacity:e})}},{key:"setRepresentation",value:function(e){this.applySettings({representation:e})}},{key:"setLineWidth",value:function(e){this.applySettings({lineWidth:e})}},{key:"setPointSize",value:function(e){this.applySettings({pointSize:e})}},{key:"getSettings",value:function(){return z({},this.settings)}},{key:"applyPanelSettings",value:function(e){var t={};void 0!==e.meshColor&&(t.color=e.meshColor),void 0!==e.pointSize&&(t.pointSize=parseFloat(e.pointSize)),void 0!==e.edgeWidth&&(t.lineWidth=parseFloat(e.edgeWidth)),void 0!==e.representation&&(t.representation=parseInt(e.representation,10)),void 0!==e.opacity&&(t.opacity=parseFloat(e.opacity)),this.applySettings(t)}},{key:"configureForTexture",value:function(e){var t=e.getProperty(),r=e.getMapper();t&&("function"==typeof t.setMetallic&&t.setMetallic(0),"function"==typeof t.setRoughness&&t.setRoughness(1),"function"==typeof t.setInterpolation&&t.setInterpolation(2),"function"==typeof t.setRMTexture&&t.setRMTexture(null),"function"==typeof t.setMetallicRoughnessTexture&&t.setMetallicRoughnessTexture(null)),r&&(r.setScalarVisibility(!1),r.modified())}},{key:"setScalarVisibility",value:function(e,t){e&&(e.setScalarVisibility(t),e.modified())}}],t&&W(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();const Z=Y;function K(e){return K="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},K(e)}function q(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function J(e){for(var t=1;t0&&void 0!==arguments[0]?arguments[0]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.container=r.container||document.body,this.onApply=r.onApply||function(){},this.enabledSettings=r.enabledSettings||null,this.includeColormapSettings=r.includeColormapSettings||!1,this.panelElement=null,this.overlayElement=null,this.currentValues={},this.settingsConfig=this._buildSettingsConfig(),this.settingsConfig.forEach(function(e){t.currentValues[e.id]=e.default})},(t=[{key:"_buildSettingsConfig",value:function(){var e=this,t=[].concat(re);return this.includeColormapSettings&&(t=t.concat(ne)),this.enabledSettings&&(t=t.filter(function(t){return e.enabledSettings.includes(t.id)})),t}},{key:"generateHTML",value:function(){var e=this,t=null,r='\n
\n
\n

Appearance Settings

\n ';return this.settingsConfig.forEach(function(n){n.section&&n.section!==t&&(t=n.section,r+='\n
\n \n
\n ")),r+=e._generateSettingRow(n)}),r+='\n
\n \n \n
\n
\n '}},{key:"_generateSettingRow",value:function(e){var t="";switch(e.type){case te.NUMBER:t='\n \n ');break;case te.COLOR:t='');break;case te.SELECT:t='";break;case te.CHECKBOX:var r=e.default?"checked":"";return'\n
\n \n
\n ")}return'\n
\n \n ").concat(t,"\n
\n ")}},{key:"render",value:function(){var e=document.createElement("div");e.innerHTML=this.generateHTML(),this.overlayElement=e.querySelector("#settingsOverlay"),this.panelElement=e.querySelector("#settingsPanel"),this.container.appendChild(this.overlayElement),this.container.appendChild(this.panelElement),this._setupEventListeners()}},{key:"attachToExisting",value:function(e,t){this.panelElement=e,this.overlayElement=t,this._setupEventListeners()}},{key:"_setupEventListeners",value:function(){var e=this,t=this.panelElement.querySelector("#applySettings");t&&t.addEventListener("click",function(){return e._handleApply()});var r=this.panelElement.querySelector("#cancelSettings");r&&r.addEventListener("click",function(){return e.close()}),this.overlayElement&&this.overlayElement.addEventListener("click",function(){return e.close()})}},{key:"_handleApply",value:function(){var e=this.getValues();this.currentValues=J({},e),this.onApply(e),this.close()}},{key:"open",value:function(){this.setValues(this.currentValues),this.panelElement&&this.panelElement.classList.add("visible"),this.overlayElement&&this.overlayElement.classList.add("visible")}},{key:"close",value:function(){this.panelElement&&this.panelElement.classList.remove("visible"),this.overlayElement&&this.overlayElement.classList.remove("visible")}},{key:"getValues",value:function(){var e={};return this.settingsConfig.forEach(function(t){var r=document.getElementById(t.id);r&&(t.type===te.CHECKBOX?e[t.id]=r.checked:e[t.id]=r.value)}),e}},{key:"setValues",value:function(e){this.settingsConfig.forEach(function(t){var r=document.getElementById(t.id);r&&void 0!==e[t.id]&&(t.type===te.CHECKBOX?r.checked=e[t.id]:r.value=e[t.id])})}},{key:"updateCurrentValues",value:function(e){this.currentValues=J(J({},this.currentValues),e)}},{key:"getCurrentValues",value:function(){return J({},this.currentValues)}}])&&Q(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();const ie=oe;function ae(e){return ae="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ae(e)}function se(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.container=t.container,this.handlers=t.handlers||{},this.controls=t.controls||this._getDefaultControls(),this.elements={}},t=[{key:"_getDefaultControls",value:function(){return[ue.settingsButton,ue.divider,ue.edgesToggle,ue.divider,ue.cameraButtons,ue.divider,ue.fieldSelector,ue.colormapSelector,ue.screenshotButton,ue.saveMeshButton]}},{key:"generateHTML",value:function(){var e=this,t="";return this.controls.forEach(function(r){if(r)switch(r.type){case le.BUTTON:t+=e._generateButton(r);break;case le.CHECKBOX:t+=e._generateCheckbox(r);break;case le.SELECT:t+=e._generateSelect(r);break;case le.DIVIDER:t+='';break;case le.LABEL:t+=''.concat(r.text||"","");break;case"camera_group":t+=e._generateCameraGroup(r);break;default:"string"==typeof r.html&&(t+=r.html)}}),t}},{key:"_generateButton",value:function(e){var t=e.className||"",r="settingsButton"===e.id?"width:32px;height:32px;padding:0;font-size:16px;":"",n=r?'style="'.concat(r,'"'):"",o=t?'class="'.concat(t,'"'):"";return'")}},{key:"_generateCheckbox",value:function(e){var t=e.checked?"checked":"";return'\n \n ")}},{key:"_generateSelect",value:function(e){var t=e.wrapperClass||"",r=e.hidden?'style="display:none;"':"",n=(e.options||[]).map(function(e){return'")}).join("");return'\n \n ")}},{key:"_generateCameraGroup",value:function(e){return(e.buttons||["+X","-X","+Y","-Y","+Z","-Z"]).map(function(e){var t="view".concat(e.replace("+","Pos").replace("-","Neg"));return'")}).join("")}},{key:"render",value:function(){this.container?(this.container.innerHTML=this.generateHTML(),this._cacheElements(),this._setupEventListeners()):console.warn("[ControlsBar] No container specified")}},{key:"_cacheElements",value:function(){var e=this;this.controls.forEach(function(t){t&&t.id&&(e.elements[t.id]=document.getElementById(t.id))}),["viewPosX","viewNegX","viewPosY","viewNegY","viewPosZ","viewNegZ"].forEach(function(t){var r=document.getElementById(t);r&&(e.elements[t]=r)})}},{key:"_setupEventListeners",value:function(){var e=this;Object.keys(this.handlers).forEach(function(t){var r=e.elements[t],n=e.handlers[t];r&&n&&("checkbox"===r.type?r.addEventListener("change",function(e){return n(e.target.checked,e)}):"SELECT"===r.tagName?r.addEventListener("change",function(e){return n(e.target.value,e)}):r.addEventListener("click",n))}),this.handlers.cameraView&&["+X","-X","+Y","-Y","+Z","-Z"].forEach(function(t){var r="view".concat(t.replace("+","Pos").replace("-","Neg")),n=e.elements[r];n&&n.addEventListener("click",function(){return e.handlers.cameraView(t)})})}},{key:"getElement",value:function(e){return this.elements[e]||document.getElementById(e)}},{key:"show",value:function(e){var t=document.getElementById("".concat(e,"Label"))||this.elements[e];t&&(t.style.display="flex")}},{key:"hide",value:function(e){var t=document.getElementById("".concat(e,"Label"))||this.elements[e];t&&(t.style.display="none")}},{key:"enable",value:function(e){var t=this.elements[e];t&&(t.disabled=!1)}},{key:"disable",value:function(e){var t=this.elements[e];t&&(t.disabled=!0)}},{key:"setButtonText",value:function(e,t){var r=this.elements[e];r&&(r.textContent=t)}},{key:"setButtonStyle",value:function(e,t){var r=this.elements[e];r&&Object.assign(r.style,t)}},{key:"populateSelect",value:function(e,t){var r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=this.elements[e]||document.getElementById(e);n&&"SELECT"===n.tagName&&(r&&(n.innerHTML=""),t.forEach(function(e){var t=document.createElement("option");t.value=e.value,t.textContent=e.label,e.selected&&(t.selected=!0),e.disabled&&(t.disabled=!0),n.appendChild(t)}))}},{key:"addHandler",value:function(e,t){this.handlers[e]=t;var r=this.elements[e];r&&("checkbox"===r.type?r.addEventListener("change",function(e){return t(e.target.checked,e)}):"SELECT"===r.tagName?r.addEventListener("change",function(e){return t(e.target.value,e)}):r.addEventListener("click",t))}}],t&&se(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();const pe=fe;function de(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof s?n:s,l=Object.create(c.prototype);return he(l,"_invoke",function(r,n,o){var i,s,c,l=0,u=o||[],f=!1,p={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,s=0,c=e,p.n=r,a}};function d(r,n){for(s=r,c=n,t=0;!f&&l&&!o&&t3?(o=h===n)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&dn||n>h)&&(i[4]=r,i[5]=n,p.n=h,s=0))}if(o||r>1)return a;throw f=!0,n}return function(o,u,h){if(l>1)throw TypeError("Generator is already running");for(f&&1===u&&d(u,h),s=u,c=h;(t=s<2?e:c)||!f;){i||(s?s<3?(s>1&&(p.n=-1),d(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(o="next"),t=i[o]){if(!(t=t.call(i,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,s<2&&(s=0)}else 1===s&&(t=i.return)&&t.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),s=1);i=e}else if((t=(f=p.n<0)?c:r.call(n,p))!==a)break}catch(t){i=e,s=1,c=t}finally{l=1}}return{value:t,done:f}}}(r,o,i),!0),l}var a={};function s(){}function c(){}function l(){}t=Object.getPrototypeOf;var u=[][n]?t(t([][n]())):(he(t={},n,function(){return this}),t),f=l.prototype=s.prototype=Object.create(u);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,he(e,o,"GeneratorFunction")),e.prototype=Object.create(f),e}return c.prototype=l,he(f,"constructor",l),he(l,"constructor",c),c.displayName="GeneratorFunction",he(l,o,"GeneratorFunction"),he(f),he(f,o,"Generator"),he(f,n,function(){return this}),he(f,"toString",function(){return"[object Generator]"}),(de=function(){return{w:i,m:p}})()}function he(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}he=function(e,t,r,n){function i(t,r){he(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(i("next",0),i("throw",1),i("return",2))},he(e,t,r,n)}function ye(e,t,r,n,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,o)}function ve(e,t){return ge.apply(this,arguments)}function ge(){var e;return e=de().m(function e(t,r){var n,o,i,a,s;return de().w(function(e){for(;;)switch(e.n){case 0:if(n=r.IO.Geometry.vtkSTLReader,o=r.Filters.Core.vtkPolyDataNormals,(i=n.newInstance()).parseAsArrayBuffer(t),i.getOutputData()){e.n=1;break}throw new Error("Failed to parse STL data");case 1:return(a=o.newInstance()).setInputConnection(i.getOutputPort()),a.update(),s=a.getOutputData(),e.a(2,{polyData:s,reader:i,normalsFilter:a,outputPort:a.getOutputPort(),metadata:{format:"STL",numPoints:s.getNumberOfPoints(),numPolys:s.getNumberOfPolys(),bounds:s.getBounds()}})}},e)}),ge=function(){var t=this,r=arguments;return new Promise(function(n,o){var i=e.apply(t,r);function a(e){ye(i,n,o,a,s,"next",e)}function s(e){ye(i,n,o,a,s,"throw",e)}a(void 0)})},ge.apply(this,arguments)}function be(e){return e.toLowerCase().includes(".stl")}const me={load:ve,canLoad:be,format:"STL"};function we(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof s?n:s,l=Object.create(c.prototype);return Oe(l,"_invoke",function(r,n,o){var i,s,c,l=0,u=o||[],f=!1,p={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,s=0,c=e,p.n=r,a}};function d(r,n){for(s=r,c=n,t=0;!f&&l&&!o&&t3?(o=h===n)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&dn||n>h)&&(i[4]=r,i[5]=n,p.n=h,s=0))}if(o||r>1)return a;throw f=!0,n}return function(o,u,h){if(l>1)throw TypeError("Generator is already running");for(f&&1===u&&d(u,h),s=u,c=h;(t=s<2?e:c)||!f;){i||(s?s<3?(s>1&&(p.n=-1),d(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(o="next"),t=i[o]){if(!(t=t.call(i,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,s<2&&(s=0)}else 1===s&&(t=i.return)&&t.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),s=1);i=e}else if((t=(f=p.n<0)?c:r.call(n,p))!==a)break}catch(t){i=e,s=1,c=t}finally{l=1}}return{value:t,done:f}}}(r,o,i),!0),l}var a={};function s(){}function c(){}function l(){}t=Object.getPrototypeOf;var u=[][n]?t(t([][n]())):(Oe(t={},n,function(){return this}),t),f=l.prototype=s.prototype=Object.create(u);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,Oe(e,o,"GeneratorFunction")),e.prototype=Object.create(f),e}return c.prototype=l,Oe(f,"constructor",l),Oe(l,"constructor",c),c.displayName="GeneratorFunction",Oe(l,o,"GeneratorFunction"),Oe(f),Oe(f,o,"Generator"),Oe(f,n,function(){return this}),Oe(f,"toString",function(){return"[object Generator]"}),(we=function(){return{w:i,m:p}})()}function Oe(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}Oe=function(e,t,r,n){function i(t,r){Oe(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(i("next",0),i("throw",1),i("return",2))},Oe(e,t,r,n)}function Se(e,t,r,n,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,o)}function Ce(e,t){return Pe.apply(this,arguments)}function Pe(){var e;return e=we().m(function e(t,r){var n,o,i,a,s,c;return we().w(function(e){for(;;)switch(e.n){case 0:if(n=r.IO.Misc.vtkOBJReader,o=r.Filters.Core.vtkPolyDataNormals,i=n.newInstance(),a=(new TextDecoder).decode(t),i.parseAsText(a),i.getOutputData()){e.n=1;break}throw new Error("Failed to parse OBJ data");case 1:return(s=o.newInstance()).setInputConnection(i.getOutputPort()),s.update(),c=s.getOutputData(),e.a(2,{polyData:c,reader:i,normalsFilter:s,outputPort:s.getOutputPort(),metadata:{format:"OBJ",numPoints:c.getNumberOfPoints(),numPolys:c.getNumberOfPolys(),bounds:c.getBounds()}})}},e)}),Pe=function(){var t=this,r=arguments;return new Promise(function(n,o){var i=e.apply(t,r);function a(e){Se(i,n,o,a,s,"next",e)}function s(e){Se(i,n,o,a,s,"throw",e)}a(void 0)})},Pe.apply(this,arguments)}function Te(e){return e.toLowerCase().includes(".obj")}const ke={load:Ce,canLoad:Te,format:"OBJ"};function Ee(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof s?n:s,l=Object.create(c.prototype);return je(l,"_invoke",function(r,n,o){var i,s,c,l=0,u=o||[],f=!1,p={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,s=0,c=e,p.n=r,a}};function d(r,n){for(s=r,c=n,t=0;!f&&l&&!o&&t3?(o=h===n)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&dn||n>h)&&(i[4]=r,i[5]=n,p.n=h,s=0))}if(o||r>1)return a;throw f=!0,n}return function(o,u,h){if(l>1)throw TypeError("Generator is already running");for(f&&1===u&&d(u,h),s=u,c=h;(t=s<2?e:c)||!f;){i||(s?s<3?(s>1&&(p.n=-1),d(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(o="next"),t=i[o]){if(!(t=t.call(i,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,s<2&&(s=0)}else 1===s&&(t=i.return)&&t.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),s=1);i=e}else if((t=(f=p.n<0)?c:r.call(n,p))!==a)break}catch(t){i=e,s=1,c=t}finally{l=1}}return{value:t,done:f}}}(r,o,i),!0),l}var a={};function s(){}function c(){}function l(){}t=Object.getPrototypeOf;var u=[][n]?t(t([][n]())):(je(t={},n,function(){return this}),t),f=l.prototype=s.prototype=Object.create(u);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,je(e,o,"GeneratorFunction")),e.prototype=Object.create(f),e}return c.prototype=l,je(f,"constructor",l),je(l,"constructor",c),c.displayName="GeneratorFunction",je(l,o,"GeneratorFunction"),je(f),je(f,o,"Generator"),je(f,n,function(){return this}),je(f,"toString",function(){return"[object Generator]"}),(Ee=function(){return{w:i,m:p}})()}function je(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}je=function(e,t,r,n){function i(t,r){je(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(i("next",0),i("throw",1),i("return",2))},je(e,t,r,n)}function xe(e,t,r,n,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,o)}function Ae(e){for(var t=e.getPointData(),r=e.getCellData(),n=[],o=[],i=0;i0||o.length>0}}function Me(e,t){return Fe.apply(this,arguments)}function Fe(){var e;return e=Ee().m(function e(t,r){var n,o,i,a,s,c,l;return Ee().w(function(e){for(;;)switch(e.n){case 0:if(n=r.IO.XML.vtkXMLPolyDataReader,o=r.Filters.Core.vtkPolyDataNormals,(i=n.newInstance()).parseAsArrayBuffer(t),a=i.getOutputData()){e.n=1;break}throw new Error("Failed to parse VTP data");case 1:return Ae(a),(s=o.newInstance()).setInputConnection(i.getOutputPort()),s.update(),c=s.getOutputData(),l=Ae(c),e.a(2,{polyData:c,reader:i,normalsFilter:s,outputPort:s.getOutputPort(),fields:l,metadata:{format:"VTP",numPoints:c.getNumberOfPoints(),numPolys:c.getNumberOfPolys(),bounds:c.getBounds(),pointFields:l.pointFields.map(function(e){return e.name}),cellFields:l.cellFields.map(function(e){return e.name}),hasFields:l.hasFields}})}},e)}),Fe=function(){var t=this,r=arguments;return new Promise(function(n,o){var i=e.apply(t,r);function a(e){xe(i,n,o,a,s,"next",e)}function s(e){xe(i,n,o,a,s,"throw",e)}a(void 0)})},Fe.apply(this,arguments)}function Le(e){return e.toLowerCase().includes(".vtp")}const _e={load:Me,canLoad:Le,format:"VTP"};function Be(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof s?n:s,l=Object.create(c.prototype);return Re(l,"_invoke",function(r,n,o){var i,s,c,l=0,u=o||[],f=!1,p={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,s=0,c=e,p.n=r,a}};function d(r,n){for(s=r,c=n,t=0;!f&&l&&!o&&t3?(o=h===n)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&dn||n>h)&&(i[4]=r,i[5]=n,p.n=h,s=0))}if(o||r>1)return a;throw f=!0,n}return function(o,u,h){if(l>1)throw TypeError("Generator is already running");for(f&&1===u&&d(u,h),s=u,c=h;(t=s<2?e:c)||!f;){i||(s?s<3?(s>1&&(p.n=-1),d(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(o="next"),t=i[o]){if(!(t=t.call(i,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,s<2&&(s=0)}else 1===s&&(t=i.return)&&t.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),s=1);i=e}else if((t=(f=p.n<0)?c:r.call(n,p))!==a)break}catch(t){i=e,s=1,c=t}finally{l=1}}return{value:t,done:f}}}(r,o,i),!0),l}var a={};function s(){}function c(){}function l(){}t=Object.getPrototypeOf;var u=[][n]?t(t([][n]())):(Re(t={},n,function(){return this}),t),f=l.prototype=s.prototype=Object.create(u);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,Re(e,o,"GeneratorFunction")),e.prototype=Object.create(f),e}return c.prototype=l,Re(f,"constructor",l),Re(l,"constructor",c),c.displayName="GeneratorFunction",Re(l,o,"GeneratorFunction"),Re(f),Re(f,o,"Generator"),Re(f,n,function(){return this}),Re(f,"toString",function(){return"[object Generator]"}),(Be=function(){return{w:i,m:p}})()}function Re(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}Re=function(e,t,r,n){function i(t,r){Re(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(i("next",0),i("throw",1),i("return",2))},Re(e,t,r,n)}function Ve(e,t,r,n,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,o)}function Ie(e){return function(){var t=this,r=arguments;return new Promise(function(n,o){var i=e.apply(t,r);function a(e){Ve(i,n,o,a,s,"next",e)}function s(e){Ve(i,n,o,a,s,"throw",e)}a(void 0)})}}function De(e){try{return void 0!==e.IO.Geometry.vtkGLTFImporter}catch(e){return!1}}function Ge(e,t,r){return ze.apply(this,arguments)}function ze(){return ze=Ie(Be().m(function e(t,r,n){var o,i,a,s,c,l,u,f,p,d,h,y,v,g,b,m=arguments;return Be().w(function(e){for(;;)switch(e.n){case 0:if(i=(o=m.length>3&&void 0!==m[3]?m[3]:{}).applyTextureFixes,a=void 0===i||i,s=o.twoSidedLighting,c=void 0===s||s,l=r.IO.Geometry.vtkGLTFImporter){e.n=1;break}throw new Error("GLTFImporter not available in this VTK.js version");case 1:return c&&n.setTwoSidedLighting&&n.setTwoSidedLighting(!0),(u=l.newInstance()).setRenderer(n),u.setUrl(t),e.n=2,new Promise(function(e,t){u.onReady(function(){e()}),u.loadData().catch(t)});case 2:return u.importActors(),f=u.getActors(),p=Array.from(f.values()),d=!1,h=!1,y=!1,a&&p.forEach(function(e,t){var r=e.getMapper(),n=e.getProperty(),o=null==r?void 0:r.getInputData();if(o&&o.getNumberOfPoints()>0){var i=o.getPointData(),a=null==i?void 0:i.getScalars();if(!a&&i)for(var s=i.getNumberOfArrays(),c=0;c=3){a=l,i.setScalars(l);break}}if(a&&a.getNumberOfComponents()>=3&&(y=!0,console.log("[GLTFLoader] Found vertex colors:",a.getName(),"components:",a.getNumberOfComponents())),n){"function"==typeof n.setRMTexture&&n.setRMTexture(null),"function"==typeof n.setMetallicRoughnessTexture&&n.setMetallicRoughnessTexture(null);var u=null;"function"==typeof n.getBaseColorTexture&&(u=n.getBaseColorTexture()),u||"function"!=typeof n.getDiffuseTexture||(u=n.getDiffuseTexture()),u||"function"!=typeof n.getTexture||(u=n.getTexture()),u&&(d=!0,e.addTexture(u)),void 0===n.getMetallic&&void 0===n.getRoughness||(h=!0),"function"==typeof n.setMetallic&&n.setMetallic(0),"function"==typeof n.setRoughness&&n.setRoughness(1),"function"==typeof n.setInterpolation&&n.setInterpolation(2)}r&&(console.log("[GLTFLoader] Configuring mapper - hasVertexColors:",y,"hasTexture:",d),y&&!d?(console.log("[GLTFLoader] Enabling vertex color rendering"),r.setScalarVisibility(!0),r.setScalarModeToUsePointData(),r.setColorModeToDirectScalars(),n&&(console.log("[GLTFLoader] Setting actor color to white"),n.setColor(1,1,1),"function"==typeof n.setBaseColorFactor&&(console.log("[GLTFLoader] Setting PBR baseColorFactor to white"),n.setBaseColorFactor([1,1,1,1])),"function"==typeof n.setDiffuseColor&&n.setDiffuseColor(1,1,1),"function"==typeof n.setAmbientColor&&n.setAmbientColor(1,1,1),"function"==typeof n.setAmbient&&n.setAmbient(.2),"function"==typeof n.setDiffuse&&n.setDiffuse(.8))):r.setScalarVisibility(!1),r.modified())}}),v=null,p.length>0&&(v=[1/0,-1/0,1/0,-1/0,1/0,-1/0],p.forEach(function(e){var t=e.getBounds();v[0]=Math.min(v[0],t[0]),v[1]=Math.max(v[1],t[1]),v[2]=Math.min(v[2],t[2]),v[3]=Math.max(v[3],t[3]),v[4]=Math.min(v[4],t[4]),v[5]=Math.max(v[5],t[5])})),g=0,b=0,p.forEach(function(e){var t=e.getMapper(),r=null==t?void 0:t.getInputData();r&&(g+=r.getNumberOfPoints(),b+=r.getNumberOfPolys())}),e.a(2,{actors:p,importer:u,bounds:v,hasTexture:d,hasVertexColors:y,metadata:{format:"GLTF",numActors:p.length,numPoints:g,numPolys:b,bounds:v,hasTexture:d,hasVertexColors:y,hasMaterial:h}})}},e)})),ze.apply(this,arguments)}function Ne(e,t){return We.apply(this,arguments)}function We(){return(We=Ie(Be().m(function e(t,r){var n,o,i;return Be().w(function(e){for(;;)switch(e.n){case 0:if(n=r.IO.Geometry.vtkGLTFImporter){e.n=1;break}throw new Error("GLTFImporter not available");case 1:return(o=n.newInstance()).parseAsArrayBuffer(t),e.n=2,o.update();case 2:if(i=o.getOutputData()){e.n=3;break}throw new Error("Failed to extract polydata from GLTF");case 3:return e.a(2,{polyData:i,importer:o,metadata:{format:"GLTF",numPoints:i.getNumberOfPoints(),numPolys:i.getNumberOfPolys(),bounds:i.getBounds()}})}},e)}))).apply(this,arguments)}function Ue(e){var t=e.toLowerCase();return t.includes(".glb")||t.includes(".gltf")}const He={load:Ge,loadSimple:Ne,canLoad:Ue,isSupported:De,format:"GLTF"};function Xe(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof s?n:s,l=Object.create(c.prototype);return Ye(l,"_invoke",function(r,n,o){var i,s,c,l=0,u=o||[],f=!1,p={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,s=0,c=e,p.n=r,a}};function d(r,n){for(s=r,c=n,t=0;!f&&l&&!o&&t3?(o=h===n)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&dn||n>h)&&(i[4]=r,i[5]=n,p.n=h,s=0))}if(o||r>1)return a;throw f=!0,n}return function(o,u,h){if(l>1)throw TypeError("Generator is already running");for(f&&1===u&&d(u,h),s=u,c=h;(t=s<2?e:c)||!f;){i||(s?s<3?(s>1&&(p.n=-1),d(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(o="next"),t=i[o]){if(!(t=t.call(i,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,s<2&&(s=0)}else 1===s&&(t=i.return)&&t.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),s=1);i=e}else if((t=(f=p.n<0)?c:r.call(n,p))!==a)break}catch(t){i=e,s=1,c=t}finally{l=1}}return{value:t,done:f}}}(r,o,i),!0),l}var a={};function s(){}function c(){}function l(){}t=Object.getPrototypeOf;var u=[][n]?t(t([][n]())):(Ye(t={},n,function(){return this}),t),f=l.prototype=s.prototype=Object.create(u);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,Ye(e,o,"GeneratorFunction")),e.prototype=Object.create(f),e}return c.prototype=l,Ye(f,"constructor",l),Ye(l,"constructor",c),c.displayName="GeneratorFunction",Ye(l,o,"GeneratorFunction"),Ye(f),Ye(f,o,"Generator"),Ye(f,n,function(){return this}),Ye(f,"toString",function(){return"[object Generator]"}),(Xe=function(){return{w:i,m:p}})()}function Ye(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}Ye=function(e,t,r,n){function i(t,r){Ye(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(i("next",0),i("throw",1),i("return",2))},Ye(e,t,r,n)}function Ze(e,t,r,n,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,o)}function Ke(e){return function(){var t=this,r=arguments;return new Promise(function(n,o){var i=e.apply(t,r);function a(e){Ze(i,n,o,a,s,"next",e)}function s(e){Ze(i,n,o,a,s,"throw",e)}a(void 0)})}}var qe={STL:"STL",OBJ:"OBJ",VTP:"VTP",GLTF:"GLTF",GLB:"GLB"};function Je(e){var t=e.toLowerCase();return t.includes(".stl")?qe.STL:t.includes(".obj")?qe.OBJ:t.includes(".vtp")?qe.VTP:t.includes(".glb")?qe.GLB:t.includes(".gltf")?qe.GLTF:null}function $e(e){return e===qe.GLTF||e===qe.GLB}function Qe(e){return e===qe.GLTF||e===qe.GLB}function et(e){return e===qe.VTP}function tt(e){return rt.apply(this,arguments)}function rt(){return(rt=Ke(Xe().m(function e(t){var r;return Xe().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,fetch(t);case 1:if((r=e.v).ok){e.n=2;break}throw new Error("HTTP ".concat(r.status,": ").concat(r.statusText));case 2:return e.a(2,r.arrayBuffer())}},e)}))).apply(this,arguments)}function nt(e,t){return ot.apply(this,arguments)}function ot(){return ot=Ke(Xe().m(function e(t,r){var n,o,i,a,s,c,l,u,f,p,d=arguments;return Xe().w(function(e){for(;;)switch(e.n){case 0:if(o=(n=d.length>2&&void 0!==d[2]?d[2]:{}).renderer,i=void 0===o?null:o,a=n.withTextures,s=void 0===a||a,c=n.twoSidedLighting,l=void 0===c||c,u=Je(t)){e.n=1;break}throw new Error("Unsupported file format: ".concat(t));case 1:if(console.log("[LoaderFactory] Loading ".concat(u," file:"),t),u!==qe.GLTF&&u!==qe.GLB||!s||!i){e.n=2;break}return e.a(2,Ge(t,r,i,{applyTextureFixes:!0,twoSidedLighting:l}));case 2:return e.n=3,tt(t);case 3:f=e.v,p=u,e.n=p===qe.STL?4:p===qe.OBJ?5:p===qe.VTP?6:p===qe.GLTF||p===qe.GLB?7:8;break;case 4:return e.a(2,ve(f,r));case 5:return e.a(2,Ce(f,r));case 6:return e.a(2,Me(f,r));case 7:return e.a(2,Ne(f,r));case 8:throw new Error("No loader available for format: ".concat(u));case 9:return e.a(2)}},e)})),ot.apply(this,arguments)}function it(e,t){return at.apply(this,arguments)}function at(){return at=Ke(Xe().m(function e(t,r){var n,o=arguments;return Xe().w(function(e){for(;;)if(0===e.n)return n=o.length>2&&void 0!==o[2]?o[2]:{},e.a(2,Promise.all(t.map(function(e){return nt(e,r,n)})))},e)})),at.apply(this,arguments)}function st(e){switch(e){case qe.STL:return{load:ve,canLoad:be,requiresRenderer:!1,supportsTextures:!1,supportsFields:!1};case qe.OBJ:return{load:Ce,canLoad:Te,requiresRenderer:!1,supportsTextures:!1,supportsFields:!1};case qe.VTP:return{load:Me,canLoad:Le,requiresRenderer:!1,supportsTextures:!1,supportsFields:!0};case qe.GLTF:case qe.GLB:return{load:Ge,loadSimple:Ne,canLoad:Ue,isSupported:De,requiresRenderer:!0,supportsTextures:!0,supportsFields:!1};default:return null}}const ct={loadMesh:nt,loadMeshes:it,detectFormat:Je,requiresRenderer:$e,supportsTextures:Qe,supportsFields:et,getLoaderConfig:st,FormatTypes:qe};function lt(e){return lt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},lt(e)}function ut(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof s?n:s,l=Object.create(c.prototype);return ft(l,"_invoke",function(r,n,o){var i,s,c,l=0,u=o||[],f=!1,p={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,s=0,c=e,p.n=r,a}};function d(r,n){for(s=r,c=n,t=0;!f&&l&&!o&&t3?(o=h===n)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&dn||n>h)&&(i[4]=r,i[5]=n,p.n=h,s=0))}if(o||r>1)return a;throw f=!0,n}return function(o,u,h){if(l>1)throw TypeError("Generator is already running");for(f&&1===u&&d(u,h),s=u,c=h;(t=s<2?e:c)||!f;){i||(s?s<3?(s>1&&(p.n=-1),d(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(o="next"),t=i[o]){if(!(t=t.call(i,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,s<2&&(s=0)}else 1===s&&(t=i.return)&&t.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),s=1);i=e}else if((t=(f=p.n<0)?c:r.call(n,p))!==a)break}catch(t){i=e,s=1,c=t}finally{l=1}}return{value:t,done:f}}}(r,o,i),!0),l}var a={};function s(){}function c(){}function l(){}t=Object.getPrototypeOf;var u=[][n]?t(t([][n]())):(ft(t={},n,function(){return this}),t),f=l.prototype=s.prototype=Object.create(u);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,ft(e,o,"GeneratorFunction")),e.prototype=Object.create(f),e}return c.prototype=l,ft(f,"constructor",l),ft(l,"constructor",c),c.displayName="GeneratorFunction",ft(l,o,"GeneratorFunction"),ft(f),ft(f,o,"Generator"),ft(f,n,function(){return this}),ft(f,"toString",function(){return"[object Generator]"}),(ut=function(){return{w:i,m:p}})()}function ft(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}ft=function(e,t,r,n){function i(t,r){ft(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(i("next",0),i("throw",1),i("return",2))},ft(e,t,r,n)}function pt(e,t,r,n,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,o)}function dt(e){return function(){var t=this,r=arguments;return new Promise(function(n,o){var i=e.apply(t,r);function a(e){pt(i,n,o,a,s,"next",e)}function s(e){pt(i,n,o,a,s,"throw",e)}a(void 0)})}}function ht(e,t){for(var r=0;r0&&void 0!==i[0]?i[0]:"screenshot.png",e.p=1,e.n=2,this.capture();case 2:r=e.v,(n=document.createElement("a")).href=r,n.download=t,n.style.display="none",document.body.appendChild(n),n.click(),document.body.removeChild(n),console.log("[ScreenshotCapture] Screenshot downloaded:",t),e.n=4;break;case 3:throw e.p=3,o=e.v,console.error("[ScreenshotCapture] Error downloading screenshot:",o),o;case 4:return e.a(2)}},e,this,[[1,3]])})),function(){return o.apply(this,arguments)})},{key:"captureAsBlob",value:(n=dt(ut().m(function e(){var t,r;return ut().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,this.capture();case 1:return t=e.v,e.n=2,fetch(t);case 2:return r=e.v,e.a(2,r.blob())}},e,this)})),function(){return n.apply(this,arguments)})}],r=[{key:"generateFilename",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"screenshot",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"png",r=(new Date).toISOString().replace(/[:.]/g,"-").replace("T","_").slice(0,19);return"".concat(e,"_").concat(r,".").concat(t)}}],t&&ht(e.prototype,t),r&&ht(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,r,n,o,i,a}();const gt=vt;function bt(e){return bt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},bt(e)}function mt(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function wt(e){for(var t=1;t2&&void 0!==arguments[2]?arguments[2]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.vtk=t,this.interactor=r,this.config=wt(wt({},Et),n),this.vtkOrientationMarkerWidget=t.Interaction.Widgets.vtkOrientationMarkerWidget,this.vtkAnnotatedCubeActor=t.Rendering.Core.vtkAnnotatedCubeActor,this.widget=null,this.cubeActor=null,this.enabled=this.config.enabled,this._createWidget()},(t=[{key:"_createWidget",value:function(){this.cubeActor=this.vtkAnnotatedCubeActor.newInstance(),this.cubeActor.setDefaultStyle({text:"+X",fontStyle:"bold",fontFamily:"Arial",fontColor:"white",fontSizeScale:function(e){return e/2},faceColor:this.config.faceColor,faceRotation:0,edgeThickness:.1,edgeColor:"white",resolution:400}),this.cubeActor.setXPlusFaceProperty({text:"+X",faceColor:Pt}),this.cubeActor.setXMinusFaceProperty({text:"-X",faceColor:Pt}),this.cubeActor.setYPlusFaceProperty({text:"+Y",faceColor:Tt}),this.cubeActor.setYMinusFaceProperty({text:"-Y",faceColor:Tt}),this.cubeActor.setZPlusFaceProperty({text:"+Z",faceColor:kt}),this.cubeActor.setZMinusFaceProperty({text:"-Z",faceColor:kt}),this.widget=this.vtkOrientationMarkerWidget.newInstance({actor:this.cubeActor,interactor:this.interactor}),this._applyCornerConfig(),this.widget.setViewportSize(this.config.viewportSize),this.widget.setMinPixelSize(this.config.minPixelSize),this.widget.setMaxPixelSize(this.config.maxPixelSize),this.widget.setEnabled(this.enabled)}},{key:"_applyCornerConfig",value:function(){var e=this.vtkOrientationMarkerWidget.Corners,t={BOTTOM_LEFT:e.BOTTOM_LEFT,BOTTOM_RIGHT:e.BOTTOM_RIGHT,TOP_LEFT:e.TOP_LEFT,TOP_RIGHT:e.TOP_RIGHT}[this.config.corner]||e.BOTTOM_LEFT;this.widget.setViewportCorner(t)}},{key:"enable",value:function(){this.enabled=!0,this.widget&&this.widget.setEnabled(!0)}},{key:"disable",value:function(){this.enabled=!1,this.widget&&this.widget.setEnabled(!1)}},{key:"toggle",value:function(){return this.enabled?this.disable():this.enable(),this.enabled}},{key:"setEnabled",value:function(e){e?this.enable():this.disable()}},{key:"isEnabled",value:function(){return this.enabled}},{key:"setCorner",value:function(e){this.config.corner=e,this._applyCornerConfig()}},{key:"setViewportSize",value:function(e){this.config.viewportSize=e,this.widget&&this.widget.setViewportSize(e)}},{key:"setAxisColors",value:function(e){e.x&&(this.cubeActor.setXPlusFaceProperty({faceColor:e.x}),this.cubeActor.setXMinusFaceProperty({faceColor:e.x})),e.y&&(this.cubeActor.setYPlusFaceProperty({faceColor:e.y}),this.cubeActor.setYMinusFaceProperty({faceColor:e.y})),e.z&&(this.cubeActor.setZPlusFaceProperty({faceColor:e.z}),this.cubeActor.setZMinusFaceProperty({faceColor:e.z}))}},{key:"getWidget",value:function(){return this.widget}},{key:"getCubeActor",value:function(){return this.cubeActor}},{key:"destroy",value:function(){this.widget&&(this.widget.setEnabled(!1),this.widget.delete(),this.widget=null),this.cubeActor&&(this.cubeActor.delete(),this.cubeActor=null)}}])&&St(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();const xt=jt;function At(e){return At="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},At(e)}function Mt(e){return function(e){if(Array.isArray(e))return Lt(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||Ft(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Ft(e,t){if(e){if("string"==typeof e)return Lt(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Lt(e,t):void 0}}function Lt(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r0}}},{key:"applyField",value:function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},o=n.range,i=void 0===o?null:o,a=n.colormap,s=void 0===a?this.currentColormap:a,c=n.render,l=void 0===c||c;if(r&&"none"!==r&&t){var u=r.startsWith("cell:"),f=u?r.substring(5):r.startsWith("point:")?r.substring(6):r,p=u?t.getCellData():t.getPointData(),d=p.getArrayByName(f);if(!d)return console.warn('[FieldVisualization] Field "'.concat(f,'" not found')),void this.disableScalarVisualization(e,l);var h=d.getRange(),y=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,s=[],c=!0,l=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=i.call(r)).done)&&(s.push(n.value),s.length!==t);c=!0);}catch(e){l=!0,o=e}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return s}}(e,t)||Ft(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(i||(this.autoRange?h:this.manualRange),2),v=y[0],g=y[1];if(Math.abs(g-v)<1e-10&&!i)return console.warn('[FieldVisualization] Field "'.concat(f,'" has zero-width range')),void this.disableScalarVisualization(e,l);p.setActiveScalars(f),e.setScalarVisibility(!0),u?e.setScalarModeToUseCellData():e.setScalarModeToUsePointData(),e.setScalarRange(v,g),this.applyColormap(e,s,v,g),this.currentField=r,this.currentColormap=s,e.update(),l&&this.renderWindow.render(),console.log('[FieldVisualization] Applied field "'.concat(f,'" with range [').concat(v.toFixed(3),", ").concat(g.toFixed(3),"]"))}else this.disableScalarVisualization(e,l)}},{key:"applyColormap",value:function(e,t,r,n){try{var o=this.vtkColorTransferFunction.newInstance(),i=this.vtkColorMaps.getPresetByName(t);i?(o.applyColorMap(i),o.setMappingRange(r,n),o.updateRange(),e.setLookupTable(o)):console.warn('[FieldVisualization] Colormap "'.concat(t,'" not found'))}catch(e){console.error("[FieldVisualization] Error applying colormap:",e)}}},{key:"disableScalarVisualization",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];e&&e.setScalarVisibility(!1),this.currentField=null,t&&this.renderWindow.render()}},{key:"getColormapOptions",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=this.vtkColorMaps.rgbPresetNames||[],r=[];return e?(Rt.forEach(function(e){t.includes(e)&&r.push({value:e,label:e,isPopular:!0})}),r.push({value:"",label:"----------",disabled:!0}),t.filter(function(e){return!Rt.includes(e)}).sort().forEach(function(e){r.push({value:e,label:e,isPopular:!1})})):t.sort().forEach(function(e){r.push({value:e,label:e,isPopular:Rt.includes(e)})}),r}},{key:"setAutoRange",value:function(e){this.autoRange=e}},{key:"setManualRange",value:function(e,t){this.manualRange=[e,t]}},{key:"calculateSynchronizedRange",value:function(e,t){var r=1/0,n=-1/0,o=t.startsWith("cell:"),i=o?t.substring(5):t.startsWith("point:")?t.substring(6):t;return e.forEach(function(e){if(e){var t=o?e.getCellData():e.getPointData(),a=null==t?void 0:t.getArrayByName(i);if(a){var s=a.getRange();r=Math.min(r,s[0]),n=Math.max(n,s[1])}}}),r===1/0||n===-1/0?[0,1]:[r,n]}},{key:"findCommonFields",value:function(e){var t=this;if(!e||0===e.length)return{commonPointFields:[],commonCellFields:[],commonAllFields:[]};for(var r=this.extractFields(e[0]),n=r.pointFields.map(function(e){return e.name}),o=r.cellFields.map(function(e){return e.name}),i=function(){var r=t.extractFields(e[a]),i=r.pointFields.map(function(e){return e.name}),s=r.cellFields.map(function(e){return e.name});n=n.filter(function(e){return i.includes(e)}),o=o.filter(function(e){return s.includes(e)})},a=1;ae.length)&&(t=e.length);for(var r=0,n=Array(t);r1&&void 0!==arguments[1]?arguments[1]:[1,1,1],r=e.getProperty(),n=e.getMapper();r&&r.setColor.apply(r,function(e){return function(e){if(Array.isArray(e))return Gt(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return Gt(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Gt(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}(t)),n&&n.setScalarVisibility(!1)}},{key:"getTextureInfo",value:function(e){var t=e.getProperty(),r={hasTexture:!1,hasMaterial:!1,textureType:null};return t?("function"==typeof t.getBaseColorTexture&&t.getBaseColorTexture()?(r.hasTexture=!0,r.textureType="baseColor"):"function"==typeof t.getDiffuseTexture&&t.getDiffuseTexture()?(r.hasTexture=!0,r.textureType="diffuse"):"function"==typeof t.getTexture&&t.getTexture()&&(r.hasTexture=!0,r.textureType="generic"),"function"!=typeof t.getMetallic&&"function"!=typeof t.getRoughness||(r.hasMaterial=!0),r):r}},{key:"isTextureSupported",value:function(){try{return void 0!==this.vtk.IO.Geometry.vtkGLTFImporter}catch(e){return!1}}}],t&&zt(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();const Ut=Wt;function Ht(e){return Ht="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Ht(e)}function Xt(e){return function(e){if(Array.isArray(e))return Yt(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return Yt(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Yt(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Yt(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r3?(o=h===n)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&dn||n>h)&&(i[4]=r,i[5]=n,p.n=h,s=0))}if(o||r>1)return a;throw f=!0,n}return function(o,u,h){if(l>1)throw TypeError("Generator is already running");for(f&&1===u&&d(u,h),s=u,c=h;(t=s<2?e:c)||!f;){i||(s?s<3?(s>1&&(p.n=-1),d(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(o="next"),t=i[o]){if(!(t=t.call(i,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,s<2&&(s=0)}else 1===s&&(t=i.return)&&t.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),s=1);i=e}else if((t=(f=p.n<0)?c:r.call(n,p))!==a)break}catch(t){i=e,s=1,c=t}finally{l=1}}return{value:t,done:f}}}(r,o,i),!0),l}var a={};function s(){}function c(){}function l(){}t=Object.getPrototypeOf;var u=[][n]?t(t([][n]())):(Kt(t={},n,function(){return this}),t),f=l.prototype=s.prototype=Object.create(u);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,Kt(e,o,"GeneratorFunction")),e.prototype=Object.create(f),e}return c.prototype=l,Kt(f,"constructor",l),Kt(l,"constructor",c),c.displayName="GeneratorFunction",Kt(l,o,"GeneratorFunction"),Kt(f),Kt(f,o,"Generator"),Kt(f,n,function(){return this}),Kt(f,"toString",function(){return"[object Generator]"}),(Zt=function(){return{w:i,m:p}})()}function Kt(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}Kt=function(e,t,r,n){function i(t,r){Kt(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(i("next",0),i("throw",1),i("return",2))},Kt(e,t,r,n)}function qt(e,t,r,n,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,o)}function Jt(e){return function(){var t=this,r=arguments;return new Promise(function(n,o){var i=e.apply(t,r);function a(e){qt(i,n,o,a,s,"next",e)}function s(e){qt(i,n,o,a,s,"throw",e)}a(void 0)})}}function $t(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function Qt(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.container=t,this.config=Qt(Qt({},nr),r),this.vtk=null,this.renderWindow=null,this.renderer=null,this.interactor=null,this.openGLRenderWindow=null,this.cameraController=null,this.actorManager=null,this.settingsPanel=null,this.controlsBar=null,this.screenshotCapture=null,this.axisIndicator=null,this.fieldVisualization=null,this.textureManager=null,this.actors=[],this.polyDatas=[],this.currentFilename=null,this.isInitialized=!1,this.loadingOverlay=null,this.infoOverlay=null,this._messageCleanup=null},t=[{key:"initialize",value:(o=Jt(Zt().m(function e(){return Zt().w(function(e){for(;;)switch(e.n){case 0:if(!this.isInitialized){e.n=1;break}return console.warn("[BaseViewer] Already initialized"),e.a(2);case 1:if(this.vtk=window.vtk,this.vtk){e.n=2;break}throw new Error("VTK.js not loaded. Include vtk-gltf.js before initializing viewer.");case 2:this._createRenderingPipeline(),this._initializeFeatures(),this._createUI(),this._setupResizeHandler(),this._setupMessageListener(),this.isInitialized=!0,console.log("[BaseViewer] Initialized");case 3:return e.a(2)}},e,this)})),function(){return o.apply(this,arguments)})},{key:"_createRenderingPipeline",value:function(){var e;this.renderWindow=this.vtk.Rendering.Core.vtkRenderWindow.newInstance(),this.renderer=this.vtk.Rendering.Core.vtkRenderer.newInstance(),(e=this.renderer).setBackground.apply(e,Xt(this.config.backgroundColor)),this.renderWindow.addRenderer(this.renderer),this.config.twoSidedLighting&&this.renderer.setTwoSidedLighting(!0),this.openGLRenderWindow=this.vtk.Rendering.OpenGL.vtkRenderWindow.newInstance(),this.openGLRenderWindow.setContainer(this.container),this.renderWindow.addView(this.openGLRenderWindow),this.interactor=this.vtk.Rendering.Core.vtkRenderWindowInteractor.newInstance(),this.interactor.setView(this.openGLRenderWindow),this.interactor.initialize(),this.interactor.bindEvents(this.container);var t=this.vtk.Interaction.Style.vtkInteractorStyleTrackballCamera.newInstance();this.interactor.setInteractorStyle(t);var r=this.container.getBoundingClientRect(),n=r.width,o=r.height;this.openGLRenderWindow.setSize(n,o)}},{key:"_initializeFeatures",value:function(){this.cameraController=new B(this.renderer,{distanceMultiplier:this.config.cameraDistanceMultiplier,parallelProjection:this.config.parallelProjection}),this.actorManager=new Y(this.vtk,{defaultColor:this.config.defaultMeshColor,edgeColor:this.config.edgeColor,edgeWidth:this.config.edgeWidth,showEdges:this.config.showEdges}),this.config.enableScreenshot&&(this.screenshotCapture=new vt(this.renderWindow)),this.config.enableAxisIndicator&&(this.axisIndicator=new jt(this.vtk,this.interactor,{enabled:!0})),this.config.enableFields&&(this.fieldVisualization=new Vt(this.vtk,this.renderWindow)),this.config.enableTextures&&(this.textureManager=new Wt(this.vtk,this.renderWindow))}},{key:"_createUI",value:function(){var e=this;this.config.showLoadingOverlay&&(this.loadingOverlay=this._createLoadingOverlay()),this.config.showInfoOverlay&&(this.infoOverlay=this._createInfoOverlay()),this.config.enableSettings&&this.config.settingsConfig&&(this.settingsPanel=new oe(this.config.settingsConfig),this.settingsPanel.onApply(function(t){return e._onSettingsApply(t)})),this.config.enableControls&&this.config.controlsConfig&&(this.controlsBar=new fe(this.config.controlsConfig),this._setupControlsHandlers())}},{key:"_createLoadingOverlay",value:function(){var e=document.createElement("div");return e.id="loading",e.className="loading",e.innerHTML='\n
\n
Loading mesh...
\n ',this.container.parentElement.appendChild(e),e}},{key:"_createInfoOverlay",value:function(){var e=document.createElement("div");return e.id="meshInfo",e.className="mesh-info",this.container.parentElement.appendChild(e),e}},{key:"_setupResizeHandler",value:function(){var e=this,t=new ResizeObserver(function(){var t=e.container.getBoundingClientRect(),r=t.width,n=t.height;r>0&&n>0&&(e.openGLRenderWindow.setSize(r,n),e.renderWindow.render())});t.observe(this.container),this._resizeObserver=t}},{key:"_setupMessageListener",value:function(){var e=this;this._messageCleanup=S(function(t){"loadMesh"===t.type&&t.url?e.loadMesh(t.url):"screenshot"===t.type&&e.captureScreenshot()})}},{key:"_setupControlsHandlers",value:function(){var e=this;this.controlsBar&&(this.controlsBar.onAction("camera-view",function(t){e.setCameraView(t)}),this.controlsBar.onAction("screenshot",function(){e.captureScreenshot()}),this.controlsBar.onAction("settings",function(){e.settingsPanel&&e.settingsPanel.open()}),this.controlsBar.onAction("edges-toggle",function(t){e.setEdgeVisibility(t)}))}},{key:"_onSettingsApply",value:function(e){var t;this.actorManager&&this.actorManager.applySettings(this.actors,e),e.backgroundColor&&(t=this.renderer).setBackground.apply(t,Xt(e.backgroundColor)),this.render()}},{key:"loadMesh",value:(n=Jt(Zt().m(function e(t){var r,n,o=this;return Zt().w(function(e){for(;;)switch(e.p=e.n){case 0:return this.showLoading(!0),e.p=1,this.clearScene(),e.n=2,nt(t,this.vtk,{renderer:this.renderer});case 2:return r=e.v,this.actors=r.actors,this.polyDatas=r.polyData?[r.polyData]:[],this.currentFilename=C(t),r.actors.forEach(function(e){o.renderer.addActor(e)}),this._configureLoadedActors(r),this._setupCameraForMesh(),this._updateInfoOverlay(r),this.showLoading(!1),O((this.currentFilename,r.format,r.actors.length,r.hasTexture,r.hasVertexColors,r.fields)),this.render(),e.a(2,r);case 3:throw e.p=3,n=e.v,console.error("[BaseViewer] Error loading mesh:",n),this.showLoading(!1),m(n.message),n;case 4:return e.a(2)}},e,this,[[1,3]])})),function(e){return n.apply(this,arguments)})},{key:"_configureLoadedActors",value:function(e){var t=this;this.config.enableTextures&&this.textureManager&&e.hasTexture?(this.textureManager.applyTextureFixesMultiple(this.actors),this.textureManager.configureRenderer(this.renderer)):e.hasVertexColors?this.actors.forEach(function(e){var r=e.getProperty();r&&t.config.showEdges&&(r.setEdgeVisibility(!0),t.config.edgeColor&&r.setEdgeColor.apply(r,Xt(t.config.edgeColor)))}):this.actorManager.configureActors(this.actors,{color:this.config.defaultMeshColor,showEdges:this.config.showEdges,edgeColor:this.config.edgeColor})}},{key:"_setupCameraForMesh",value:function(){if(0!==this.actors.length){for(var e=this.actors[0].getBounds(),t=1;t")}}},{key:"clearScene",value:function(){var e=this;this.actors.forEach(function(t){e.renderer.removeActor(t)}),this.actors=[],this.polyDatas=[]}},{key:"setCameraView",value:function(e){if(0!==this.actors.length){var t=this.actors[0].getBounds();this.cameraController.setCameraView(e,t),this.render()}}},{key:"setEdgeVisibility",value:function(e){var t=this;this.actors.forEach(function(r){t.actorManager.setEdgeVisibility(r,e)}),this.render()}},{key:"captureScreenshot",value:(r=Jt(Zt().m(function e(){return Zt().w(function(e){for(;;)switch(e.n){case 0:if(!this.screenshotCapture){e.n=1;break}return e.a(2,this.screenshotCapture.captureAndSend());case 1:return e.a(2)}},e,this)})),function(){return r.apply(this,arguments)})},{key:"showLoading",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Loading mesh...";if(this.loadingOverlay){this.loadingOverlay.style.display=e?"flex":"none";var r=this.loadingOverlay.querySelector(".loading-text");r&&(r.textContent=t)}}},{key:"render",value:function(){this.renderWindow.render()}},{key:"resize",value:function(e,t){this.openGLRenderWindow.setSize(e,t),this.render()}},{key:"getActors",value:function(){return this.actors}},{key:"getRenderer",value:function(){return this.renderer}},{key:"destroy",value:function(){this._messageCleanup&&this._messageCleanup(),this._resizeObserver&&this._resizeObserver.disconnect(),this.axisIndicator&&this.axisIndicator.destroy(),this.clearScene(),this.interactor&&this.interactor.unbindEvents(),this.openGLRenderWindow&&this.openGLRenderWindow.delete(),this.renderWindow&&this.renderWindow.delete(),this.loadingOverlay&&this.loadingOverlay.parentElement&&this.loadingOverlay.parentElement.removeChild(this.loadingOverlay),this.infoOverlay&&this.infoOverlay.parentElement&&this.infoOverlay.parentElement.removeChild(this.infoOverlay),console.log("[BaseViewer] Destroyed")}}],t&&tr(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,r,n,o}();const ir=or;function ar(e){return ar="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ar(e)}function sr(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof s?n:s,l=Object.create(c.prototype);return cr(l,"_invoke",function(r,n,o){var i,s,c,l=0,u=o||[],f=!1,p={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,s=0,c=e,p.n=r,a}};function d(r,n){for(s=r,c=n,t=0;!f&&l&&!o&&t3?(o=h===n)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&dn||n>h)&&(i[4]=r,i[5]=n,p.n=h,s=0))}if(o||r>1)return a;throw f=!0,n}return function(o,u,h){if(l>1)throw TypeError("Generator is already running");for(f&&1===u&&d(u,h),s=u,c=h;(t=s<2?e:c)||!f;){i||(s?s<3?(s>1&&(p.n=-1),d(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(o="next"),t=i[o]){if(!(t=t.call(i,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,s<2&&(s=0)}else 1===s&&(t=i.return)&&t.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),s=1);i=e}else if((t=(f=p.n<0)?c:r.call(n,p))!==a)break}catch(t){i=e,s=1,c=t}finally{l=1}}return{value:t,done:f}}}(r,o,i),!0),l}var a={};function s(){}function c(){}function l(){}t=Object.getPrototypeOf;var u=[][n]?t(t([][n]())):(cr(t={},n,function(){return this}),t),f=l.prototype=s.prototype=Object.create(u);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,cr(e,o,"GeneratorFunction")),e.prototype=Object.create(f),e}return c.prototype=l,cr(f,"constructor",l),cr(l,"constructor",c),c.displayName="GeneratorFunction",cr(l,o,"GeneratorFunction"),cr(f),cr(f,o,"Generator"),cr(f,n,function(){return this}),cr(f,"toString",function(){return"[object Generator]"}),(sr=function(){return{w:i,m:p}})()}function cr(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}cr=function(e,t,r,n){function i(t,r){cr(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(i("next",0),i("throw",1),i("return",2))},cr(e,t,r,n)}function lr(e,t,r,n,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,o)}function ur(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function fr(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{};return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(r=function(e,t,r){return t=br(t),function(e,t){if(t&&("object"==ar(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,yr()?Reflect.construct(t,r||[],br(e).constructor):t.apply(e,r))}(this,t,[e,fr(fr(fr({},wr),n),{},{settingsConfig:{title:"Settings",fields:[{type:te.COLOR,id:"meshColor",label:"Mesh Color",defaultValue:n.defaultMeshColor||wr.defaultMeshColor},{type:te.CHECKBOX,id:"showEdges",label:"Show Edges",defaultValue:n.showEdges||wr.showEdges},{type:te.COLOR,id:"edgeColor",label:"Edge Color",defaultValue:n.edgeColor||[.2,.2,.2]},{type:te.COLOR,id:"backgroundColor",label:"Background",defaultValue:n.backgroundColor||wr.backgroundColor}]},controlsConfig:{controls:[ue.CAMERA_VIEWS,ue.SCREENSHOT,ue.SETTINGS]}})])).currentField=null,r.currentColormap="erdc_rainbow_bright",r.availableFields=[],r}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&mr(e,t)}(t,e),r=t,n=[{key:"loadMesh",value:function(){var e,r=(e=sr().m(function e(r){var n,o,i;return sr().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,vr(t,"loadMesh",this,3)([r]);case 1:return n=e.v,this.fieldVisualization&&this.polyDatas.length>0&&(o=this.fieldVisualization.extractFields(this.polyDatas[0]),this.availableFields=o.allFields,this.availableFields.length>0&&(null===(i=window.parent)||void 0===i||i.postMessage({type:"fieldsAvailable",fields:this.availableFields.map(function(e){return{name:e.fullName,displayName:e.displayName,type:e.type,range:e.range}})},"*"))),e.a(2,n)}},e,this)}),function(){var t=this,r=arguments;return new Promise(function(n,o){var i=e.apply(t,r);function a(e){lr(i,n,o,a,s,"next",e)}function s(e){lr(i,n,o,a,s,"throw",e)}a(void 0)})});return function(e){return r.apply(this,arguments)}}()},{key:"applyField",value:function(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.fieldVisualization&&0!==this.polyDatas.length){var n=null===(t=this.actors[0])||void 0===t?void 0:t.getMapper();n&&(this.fieldVisualization.applyField(n,this.polyDatas[0],e,{colormap:r.colormap||this.currentColormap,range:r.range,render:!0}),this.currentField=e,r.colormap&&(this.currentColormap=r.colormap))}else console.warn("[StandardViewer] Field visualization not available")}},{key:"setColormap",value:function(e){this.currentColormap=e,this.currentField&&this.applyField(this.currentField,{colormap:e})}},{key:"clearField",value:function(){if(this.actors.length>0){var e,t=this.actors[0].getMapper();t&&(null===(e=this.fieldVisualization)||void 0===e||e.disableScalarVisualization(t,!0))}this.currentField=null}},{key:"getColormapOptions",value:function(){var e;return(null===(e=this.fieldVisualization)||void 0===e?void 0:e.getColormapOptions())||[]}},{key:"getAvailableFields",value:function(){return this.availableFields}},{key:"_setupMessageListener",value:function(){var e=this;vr(t,"_setupMessageListener",this,3)([]),window.addEventListener("message",function(t){var r=t.data;if(r&&r.type)switch(r.type){case"setField":e.applyField(r.field,{colormap:r.colormap,range:r.range});break;case"setColormap":e.setColormap(r.colormap);break;case"clearField":e.clearField()}})}}],n&&dr(r.prototype,n),Object.defineProperty(r,"prototype",{writable:!1}),r;var r,n}(or);function Sr(e){var t=new Or(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{});return t.initialize(),t}const Cr=Or;function Pr(e){return Pr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Pr(e)}function Tr(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function kr(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{};return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(r=function(e,t,r){return t=Mr(t),function(e,t){if(t&&("object"==Pr(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,Ar()?Reflect.construct(t,r||[],Mr(e).constructor):t.apply(e,r))}(this,t,[e,kr(kr(kr({},Lr),n),{},{settingsConfig:{title:"Settings",fields:[{type:te.COLOR,id:"backgroundColor",label:"Background",defaultValue:n.backgroundColor||Lr.backgroundColor},{type:te.CHECKBOX,id:"showEdges",label:"Show Edges",defaultValue:!1}]},controlsConfig:{controls:[ue.CAMERA_VIEWS,ue.SCREENSHOT,ue.SETTINGS]}})])).textureInfo=null,r}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Fr(e,t)}(t,e),r=t,(n=[{key:"_configureLoadedActors",value:function(e){var t=this;this.textureManager&&e.actors.length>0&&(this.textureInfo=this.textureManager.applyTextureFixesMultiple(e.actors),this.textureManager.configureRenderer(this.renderer),console.log("[TexturedViewer] Texture info:",this.textureInfo),this.textureInfo.hasTexture||e.actors.forEach(function(e){t.textureManager.setActorColor(e,t.config.defaultMeshColor)}))}},{key:"_updateInfoOverlay",value:function(e){if(this.infoOverlay){var t=["File: ".concat(this.currentFilename)];e.actors&&t.push("Actors: ".concat(e.actors.length)),this.textureInfo&&(t.push("Textured: ".concat(this.textureInfo.hasTexture?"Yes":"No")),this.textureInfo.texturedActors>0&&t.push("Textured actors: ".concat(this.textureInfo.texturedActors))),this.infoOverlay.innerHTML=t.join("
")}}},{key:"getTextureInfo",value:function(){return this.textureInfo}},{key:"hasTextures",value:function(){var e;return(null===(e=this.textureInfo)||void 0===e?void 0:e.hasTexture)||!1}}])&&jr(r.prototype,n),Object.defineProperty(r,"prototype",{writable:!1}),r;var r,n}(or);function Br(e){var t=new _r(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{});return t.initialize(),t}const Rr=_r;function Vr(e){return Vr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Vr(e)}function Ir(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i,a,s=[],c=!0,l=!1;try{if(i=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=i.call(r)).done)&&(s.push(n.value),s.length!==t);c=!0);}catch(e){l=!0,o=e}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(l)throw o}}return s}}(e,t)||Gr(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Dr(e){return function(e){if(Array.isArray(e))return zr(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||Gr(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Gr(e,t){if(e){if("string"==typeof e)return zr(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?zr(e,t):void 0}}function zr(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r3?(o=h===n)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&dn||n>h)&&(i[4]=r,i[5]=n,p.n=h,s=0))}if(o||r>1)return a;throw f=!0,n}return function(o,u,h){if(l>1)throw TypeError("Generator is already running");for(f&&1===u&&d(u,h),s=u,c=h;(t=s<2?e:c)||!f;){i||(s?s<3?(s>1&&(p.n=-1),d(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(o="next"),t=i[o]){if(!(t=t.call(i,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,s<2&&(s=0)}else 1===s&&(t=i.return)&&t.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),s=1);i=e}else if((t=(f=p.n<0)?c:r.call(n,p))!==a)break}catch(t){i=e,s=1,c=t}finally{l=1}}return{value:t,done:f}}}(r,o,i),!0),l}var a={};function s(){}function c(){}function l(){}t=Object.getPrototypeOf;var u=[][n]?t(t([][n]())):(Wr(t={},n,function(){return this}),t),f=l.prototype=s.prototype=Object.create(u);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,Wr(e,o,"GeneratorFunction")),e.prototype=Object.create(f),e}return c.prototype=l,Wr(f,"constructor",l),Wr(l,"constructor",c),c.displayName="GeneratorFunction",Wr(l,o,"GeneratorFunction"),Wr(f),Wr(f,o,"Generator"),Wr(f,n,function(){return this}),Wr(f,"toString",function(){return"[object Generator]"}),(Nr=function(){return{w:i,m:p}})()}function Wr(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}Wr=function(e,t,r,n){function i(t,r){Wr(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(i("next",0),i("throw",1),i("return",2))},Wr(e,t,r,n)}function Ur(e,t,r,n,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,o)}function Hr(e){return function(){var t=this,r=arguments;return new Promise(function(n,o){var i=e.apply(t,r);function a(e){Ur(i,n,o,a,s,"next",e)}function s(e){Ur(i,n,o,a,s,"throw",e)}a(void 0)})}}function Xr(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function Yr(e){for(var t=1;t2&&void 0!==arguments[2]?arguments[2]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.containerA=t,this.containerB=r,this.config=Yr(Yr({},$r),n),this.vtk=null,this.viewportA=null,this.viewportB=null,this.actorManager=null,this.fieldVisualization=null,this.layout=this.config.layout,this.syncCameras=this.config.syncCameras,this.syncFields=this.config.syncFields,this.isInitialized=!1,this._cameraObserver=null,this._isUpdatingCamera=!1,this._messageCleanup=null},t=[{key:"initialize",value:(o=Hr(Nr().m(function e(){return Nr().w(function(e){for(;;)switch(e.n){case 0:if(!this.isInitialized){e.n=1;break}return e.a(2);case 1:if(this.vtk=window.vtk,this.vtk){e.n=2;break}throw new Error("VTK.js not loaded");case 2:this.viewportA=this._createViewport(this.containerA,"A"),this.viewportB=this._createViewport(this.containerB,"B"),this.actorManager=new Y(this.vtk,{defaultColor:this.config.defaultMeshColorA}),this.fieldVisualization=new Vt(this.vtk,this.viewportA.renderWindow),this.syncCameras&&this._setupCameraSync(),this._setupResizeHandlers(),this._setupMessageListener(),this.isInitialized=!0,console.log("[DualViewer] Initialized");case 3:return e.a(2)}},e,this)})),function(){return o.apply(this,arguments)})},{key:"_createViewport",value:function(e,t){var r=this.vtk.Rendering.Core.vtkRenderWindow.newInstance(),n=this.vtk.Rendering.Core.vtkRenderer.newInstance();n.setBackground.apply(n,Dr(this.config.backgroundColor)),r.addRenderer(n);var o=this.vtk.Rendering.OpenGL.vtkRenderWindow.newInstance();o.setContainer(e),r.addView(o);var i=this.vtk.Rendering.Core.vtkRenderWindowInteractor.newInstance();i.setView(o),i.initialize(),i.bindEvents(e);var a=this.vtk.Interaction.Style.vtkInteractorStyleTrackballCamera.newInstance();i.setInteractorStyle(a);var s=e.getBoundingClientRect(),c=s.width,l=s.height;return o.setSize(c,l),{id:t,container:e,renderWindow:r,renderer:n,openGLRenderWindow:o,interactor:i,interactorStyle:a,cameraController:new B(n,{distanceMultiplier:this.config.cameraDistanceMultiplier}),textureManager:new Wt(this.vtk,r),actors:[],polyData:null,filename:null}}},{key:"_setupCameraSync",value:function(){var e=this,t=function(t,r){if(!e._isUpdatingCamera){e._isUpdatingCamera=!0;var n=t.renderer.getActiveCamera(),o=r.renderer.getActiveCamera();o.setPosition.apply(o,Dr(n.getPosition())),o.setFocalPoint.apply(o,Dr(n.getFocalPoint())),o.setViewUp.apply(o,Dr(n.getViewUp())),o.setParallelScale(n.getParallelScale()),r.renderWindow.render(),e._isUpdatingCamera=!1}},r=this.viewportA.renderer.getActiveCamera(),n=this.viewportB.renderer.getActiveCamera();r.onModified(function(){e.syncCameras&&t(e.viewportA,e.viewportB)}),n.onModified(function(){e.syncCameras&&t(e.viewportB,e.viewportA)})}},{key:"_setupResizeHandlers",value:function(){var e=this,t=function(e){var t=e.container.getBoundingClientRect(),r=t.width,n=t.height;r>0&&n>0&&(e.openGLRenderWindow.setSize(r,n),e.renderWindow.render())};this._resizeObserverA=new ResizeObserver(function(){return t(e.viewportA)}),this._resizeObserverB=new ResizeObserver(function(){return t(e.viewportB)}),this._resizeObserverA.observe(this.viewportA.container),this._resizeObserverB.observe(this.viewportB.container)}},{key:"_setupMessageListener",value:function(){var e=this;this._messageCleanup=S(function(t){switch(t.type){case"loadMeshA":e.loadMesh("A",t.url);break;case"loadMeshB":e.loadMesh("B",t.url);break;case"loadMesh":t.viewport?e.loadMesh(t.viewport,t.url):e.loadMesh("A",t.url);break;case"setLayout":e.setLayout(t.layout);break;case"setCameraSync":e.setCameraSync(t.enabled);break;case"setField":e.applyField(t.field,t.options);break;case"screenshot":e.captureScreenshot()}})}},{key:"loadMesh",value:(n=Hr(Nr().m(function e(t,r){var n,o,i,a,s=this;return Nr().w(function(e){for(;;)switch(e.p=e.n){case 0:return n="A"===t?this.viewportA:this.viewportB,o="A"===t?this.config.defaultMeshColorA:this.config.defaultMeshColorB,e.p=1,n.actors.forEach(function(e){return n.renderer.removeActor(e)}),n.actors=[],e.n=2,nt(r,this.vtk,{renderer:n.renderer});case 2:return i=e.v,n.actors=i.actors,n.polyData=i.polyData,n.filename=C(r),i.actors.forEach(function(e){n.renderer.addActor(e)}),i.hasTexture&&this.config.enableTextures?(n.textureManager.applyTextureFixesMultiple(i.actors),n.textureManager.configureRenderer(n.renderer)):i.hasVertexColors?i.actors.forEach(function(e){var t=e.getProperty();t&&s.config.showEdges&&t.setEdgeVisibility(!0)}):this.actorManager.configureActors(i.actors,{color:o,showEdges:this.config.showEdges}),this._positionCameraForViewport(n),n.renderWindow.render(),O((n.filename,i.format,i.hasTexture,i.hasVertexColors)),e.a(2,i);case 3:throw e.p=3,a=e.v,console.error("[DualViewer] Error loading mesh ".concat(t,":"),a),m("Failed to load mesh ".concat(t,": ").concat(a.message)),a;case 4:return e.a(2)}},e,this,[[1,3]])})),function(e,t){return n.apply(this,arguments)})},{key:"_positionCameraForViewport",value:function(e){if(0!==e.actors.length){for(var t=e.actors[0].getBounds(),r=1;r1&&void 0!==arguments[1]?arguments[1]:{};if(this.config.enableFields){var r=t.range;if(this.syncFields&&!r){var n=[this.viewportA.polyData,this.viewportB.polyData].filter(Boolean);n.length>0&&(r=this.fieldVisualization.calculateSynchronizedRange(n,e))}if(this.viewportA.polyData&&this.viewportA.actors.length>0){var o=this.viewportA.actors[0].getMapper();this.fieldVisualization.applyField(o,this.viewportA.polyData,e,Yr(Yr({},t),{},{range:r,render:!1}))}if(this.viewportB.polyData&&this.viewportB.actors.length>0){var i=this.viewportB.actors[0].getMapper();new Vt(this.vtk,this.viewportB.renderWindow).applyField(i,this.viewportB.polyData,e,Yr(Yr({},t),{},{range:r,render:!1}))}this.render()}}},{key:"setLayout",value:function(e){this.layout=e,console.log("[DualViewer] Layout set to: ".concat(e))}},{key:"setCameraSync",value:function(e){this.syncCameras=e,console.log("[DualViewer] Camera sync: ".concat(e))}},{key:"setFieldSync",value:function(e){this.syncFields=e}},{key:"setCameraView",value:function(e){var t=[].concat(Dr(this.viewportA.actors),Dr(this.viewportB.actors));if(0!==t.length){for(var r=t[0].getBounds(),n=1;n2&&void 0!==arguments[2]?arguments[2]:{});return r.initialize(),r}const tn=Qr;function rn(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof s?n:s,l=Object.create(c.prototype);return nn(l,"_invoke",function(r,n,o){var i,s,c,l=0,u=o||[],f=!1,p={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function(t,r){return i=t,s=0,c=e,p.n=r,a}};function d(r,n){for(s=r,c=n,t=0;!f&&l&&!o&&t3?(o=h===n)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&dn||n>h)&&(i[4]=r,i[5]=n,p.n=h,s=0))}if(o||r>1)return a;throw f=!0,n}return function(o,u,h){if(l>1)throw TypeError("Generator is already running");for(f&&1===u&&d(u,h),s=u,c=h;(t=s<2?e:c)||!f;){i||(s?s<3?(s>1&&(p.n=-1),d(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(o="next"),t=i[o]){if(!(t=t.call(i,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,s<2&&(s=0)}else 1===s&&(t=i.return)&&t.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),s=1);i=e}else if((t=(f=p.n<0)?c:r.call(n,p))!==a)break}catch(t){i=e,s=1,c=t}finally{l=1}}return{value:t,done:f}}}(r,o,i),!0),l}var a={};function s(){}function c(){}function l(){}t=Object.getPrototypeOf;var u=[][n]?t(t([][n]())):(nn(t={},n,function(){return this}),t),f=l.prototype=s.prototype=Object.create(u);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,nn(e,o,"GeneratorFunction")),e.prototype=Object.create(f),e}return c.prototype=l,nn(f,"constructor",l),nn(l,"constructor",c),c.displayName="GeneratorFunction",nn(l,o,"GeneratorFunction"),nn(f),nn(f,o,"Generator"),nn(f,n,function(){return this}),nn(f,"toString",function(){return"[object Generator]"}),(rn=function(){return{w:i,m:p}})()}function nn(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}nn=function(e,t,r,n){function i(t,r){nn(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(i("next",0),i("throw",1),i("return",2))},nn(e,t,r,n)}function on(e,t,r,n,o,i,a){try{var s=e[i](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,o)}var an={STANDARD:"standard",TEXTURED:"textured",DUAL:"dual"},sn={create:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};switch(console.log("[GeomPack Viewer] Creating ".concat(e," viewer")),e){case an.STANDARD:case"standard":return new Cr(t,r);case an.TEXTURED:case"textured":return new Rr(t,r);case an.DUAL:case"dual":if(Array.isArray(t))return new tn(t[0],t[1],r);if(r.containerB)return new tn(t,r.containerB,r);throw new Error("DualViewer requires two containers");default:return console.warn("[GeomPack Viewer] Unknown viewer type: ".concat(e,", falling back to standard")),new Cr(t,r)}},createAndInit:function(e,t){var r,n=arguments,o=this;return(r=rn().m(function r(){var i,a;return rn().w(function(r){for(;;)switch(r.n){case 0:return i=n.length>2&&void 0!==n[2]?n[2]:{},a=o.create(e,t,i),r.n=1,a.initialize();case 1:return r.a(2,a)}},r)}),function(){var e=this,t=arguments;return new Promise(function(n,o){var i=r.apply(e,t);function a(e){on(i,n,o,a,s,"next",e)}function s(e){on(i,n,o,a,s,"throw",e)}a(void 0)})})()}};const cn={ColorUtils:i,BoundsUtils:d,MessageHandler:P,CameraController:R,ActorManager:Z,Representation:X,BaseViewer:ir,SettingsPanel:ie,SettingTypes:te,ControlsBar:pe,ControlTypes:le,StandardControls:ue,LoaderFactory:ct,FormatTypes:qe,STLLoader:me,OBJLoader:ke,VTPLoader:_e,GLTFLoader:He,FieldVisualization:It,TextureManager:Ut,ScreenshotCapture:gt,AxisIndicator:xt,StandardViewer:Cr,TexturedViewer:Rr,DualViewer:tn,DualLayoutMode:Jr,ViewerTypes:an,createStandardViewer:Sr,createTexturedViewer:Br,createDualViewer:en,ViewerFactory:sn};return t})()); \ No newline at end of file diff --git a/javascript/js/viewer/core/ActorManager.js b/javascript/js/viewer/core/ActorManager.js new file mode 100644 index 00000000..0ce7c26f --- /dev/null +++ b/javascript/js/viewer/core/ActorManager.js @@ -0,0 +1,276 @@ +/** + * ActorManager - Unified actor/property management for VTK viewers + * + * Handles actor configuration, appearance settings, edge visibility, + * and material properties. Works with both single actors and actor arrays. + */ + +import { hexToRgb } from '../utils/ColorUtils.js'; + +/** + * Default actor appearance settings + */ +const DEFAULT_SETTINGS = { + color: [1.0, 1.0, 1.0], // White + edgeColor: [0.0, 0.0, 0.0], // Black edges + ambient: 0.4, + diffuse: 0.8, + specular: 0.3, + specularPower: 20, + edgeVisibility: false, + lineWidth: 1, + pointSize: 5, + representation: 2, // 0=Points, 1=Wireframe, 2=Surface + opacity: 1.0 +}; + +/** + * Representation mode constants + */ +export const Representation = { + POINTS: 0, + WIREFRAME: 1, + SURFACE: 2 +}; + +export class ActorManager { + /** + * Create an ActorManager + * @param {Object} renderWindow - VTK render window for triggering renders + */ + constructor(renderWindow) { + this.renderWindow = renderWindow; + this.actors = []; + this.settings = { ...DEFAULT_SETTINGS }; + } + + /** + * Add an actor to be managed + * @param {Object} actor - VTK actor instance + */ + addActor(actor) { + this.actors.push(actor); + this.configureActor(actor, this.settings); + } + + /** + * Remove an actor from management + * @param {Object} actor - VTK actor instance + */ + removeActor(actor) { + const index = this.actors.indexOf(actor); + if (index > -1) { + this.actors.splice(index, 1); + } + } + + /** + * Clear all managed actors + */ + clearActors() { + this.actors = []; + } + + /** + * Set actors to manage (replaces existing) + * @param {Object[]} actors - Array of VTK actor instances + */ + setActors(actors) { + this.actors = Array.isArray(actors) ? actors : [actors]; + this.actors.forEach(actor => this.configureActor(actor, this.settings)); + } + + /** + * Configure a single actor with settings + * @param {Object} actor - VTK actor instance + * @param {Object} settings - Settings object + */ + configureActor(actor, settings = {}) { + const merged = { ...this.settings, ...settings }; + const property = actor.getProperty(); + + if (!property) { + console.warn('[ActorManager] Actor has no property object'); + return; + } + + // Color (supports hex string or RGB array) + if (merged.color) { + const rgb = typeof merged.color === 'string' + ? hexToRgb(merged.color) + : merged.color; + property.setColor(...rgb); + } + + // Edge color + if (merged.edgeColor) { + const rgb = typeof merged.edgeColor === 'string' + ? hexToRgb(merged.edgeColor) + : merged.edgeColor; + property.setEdgeColor(...rgb); + } + + // Lighting properties + if (merged.ambient !== undefined) property.setAmbient(merged.ambient); + if (merged.diffuse !== undefined) property.setDiffuse(merged.diffuse); + if (merged.specular !== undefined) property.setSpecular(merged.specular); + if (merged.specularPower !== undefined) property.setSpecularPower(merged.specularPower); + + // Edge and line properties + if (merged.edgeVisibility !== undefined) property.setEdgeVisibility(merged.edgeVisibility); + if (merged.lineWidth !== undefined) property.setLineWidth(merged.lineWidth); + + // Point properties + if (merged.pointSize !== undefined) property.setPointSize(merged.pointSize); + + // Representation mode + if (merged.representation !== undefined) property.setRepresentation(merged.representation); + + // Opacity + if (merged.opacity !== undefined) property.setOpacity(merged.opacity); + } + + /** + * Apply settings to all managed actors + * @param {Object} settings - Settings object + * @param {boolean} render - Whether to trigger a render (default: true) + */ + applySettings(settings, render = true) { + this.settings = { ...this.settings, ...settings }; + this.actors.forEach(actor => this.configureActor(actor, this.settings)); + if (render) { + this.renderWindow.render(); + } + } + + /** + * Set edge visibility on all managed actors + * @param {boolean} visible - Whether edges should be visible + */ + setEdgeVisibility(visible) { + this.applySettings({ edgeVisibility: visible }); + } + + /** + * Set color on all managed actors + * @param {string|number[]} color - Hex string or RGB array (0-1 range) + */ + setColor(color) { + this.applySettings({ color }); + } + + /** + * Set opacity on all managed actors + * @param {number} opacity - Opacity value (0-1) + */ + setOpacity(opacity) { + this.applySettings({ opacity }); + } + + /** + * Set representation mode on all managed actors + * @param {number} mode - 0=Points, 1=Wireframe, 2=Surface + */ + setRepresentation(mode) { + this.applySettings({ representation: mode }); + } + + /** + * Set line width for edges/wireframe + * @param {number} width - Line width in pixels + */ + setLineWidth(width) { + this.applySettings({ lineWidth: width }); + } + + /** + * Set point size for point cloud rendering + * @param {number} size - Point size in pixels + */ + setPointSize(size) { + this.applySettings({ pointSize: size }); + } + + /** + * Get current settings + * @returns {Object} Current settings object + */ + getSettings() { + return { ...this.settings }; + } + + /** + * Apply settings from a settings panel (handles hex colors and number parsing) + * @param {Object} panelValues - Values from settings panel inputs + */ + applyPanelSettings(panelValues) { + const settings = {}; + + if (panelValues.meshColor !== undefined) { + settings.color = panelValues.meshColor; + } + if (panelValues.pointSize !== undefined) { + settings.pointSize = parseFloat(panelValues.pointSize); + } + if (panelValues.edgeWidth !== undefined) { + settings.lineWidth = parseFloat(panelValues.edgeWidth); + } + if (panelValues.representation !== undefined) { + settings.representation = parseInt(panelValues.representation, 10); + } + if (panelValues.opacity !== undefined) { + settings.opacity = parseFloat(panelValues.opacity); + } + + this.applySettings(settings); + } + + /** + * Configure for textured mode (disables scalar visibility, sets material) + * @param {Object} actor - VTK actor instance + */ + configureForTexture(actor) { + const property = actor.getProperty(); + const mapper = actor.getMapper(); + + if (property) { + // Material settings for proper texture display + if (typeof property.setMetallic === 'function') { + property.setMetallic(0.0); + } + if (typeof property.setRoughness === 'function') { + property.setRoughness(1.0); + } + if (typeof property.setInterpolation === 'function') { + property.setInterpolation(2); // Phong shading + } + + // Remove metallic/roughness texture if present (common GLTF issue) + if (typeof property.setRMTexture === 'function') { + property.setRMTexture(null); + } + if (typeof property.setMetallicRoughnessTexture === 'function') { + property.setMetallicRoughnessTexture(null); + } + } + + if (mapper) { + mapper.setScalarVisibility(false); + mapper.modified(); + } + } + + /** + * Enable/disable scalar (field) visualization on mapper + * @param {Object} mapper - VTK mapper instance + * @param {boolean} enabled - Whether to show scalar colors + */ + setScalarVisibility(mapper, enabled) { + if (mapper) { + mapper.setScalarVisibility(enabled); + mapper.modified(); + } + } +} + +export default ActorManager; diff --git a/javascript/js/viewer/core/BaseViewer.js b/javascript/js/viewer/core/BaseViewer.js new file mode 100644 index 00000000..09c8384a --- /dev/null +++ b/javascript/js/viewer/core/BaseViewer.js @@ -0,0 +1,657 @@ +/** + * BaseViewer - Foundation class for VTK viewers + * + * Provides core lifecycle management, VTK setup, and feature composition. + * Subclasses configure features and behavior through options. + */ + +import { CameraController } from './CameraController.js'; +import { ActorManager, Representation } from './ActorManager.js'; +import { SettingsPanel } from '../ui/SettingsPanel.js'; +import { ControlsBar, StandardControls } from '../ui/ControlsBar.js'; +import { loadMesh } from '../loaders/LoaderFactory.js'; +import { ScreenshotCapture } from '../features/ScreenshotCapture.js'; +import { AxisIndicator } from '../features/AxisIndicator.js'; +import { FieldVisualization } from '../features/FieldVisualization.js'; +import { TextureManager } from '../features/TextureManager.js'; +import { sendMeshLoaded, sendError, createMessageListener, extractFilename } from '../utils/MessageHandler.js'; +import { getCenter, getMaxDimension, isValidBounds } from '../utils/BoundsUtils.js'; + +/** + * Default viewer configuration + */ +const DEFAULT_CONFIG = { + // Appearance + backgroundColor: [0.15, 0.15, 0.15], + defaultMeshColor: [0.6, 0.8, 1.0], + edgeColor: [0.2, 0.2, 0.2], + edgeWidth: 1.0, + showEdges: false, + + // Camera + cameraDistanceMultiplier: 2.5, + parallelProjection: false, + + // Lighting + twoSidedLighting: false, + + // Features (enabled/disabled) + enableFields: true, + enableTextures: false, + enableScreenshot: true, + enableAxisIndicator: false, + enableSettings: true, + enableControls: true, + + // UI + showLoadingOverlay: true, + showInfoOverlay: true +}; + +export class BaseViewer { + /** + * Create a BaseViewer + * @param {HTMLElement} container - Container element for the viewer + * @param {Object} config - Configuration options + */ + constructor(container, config = {}) { + this.container = container; + this.config = { ...DEFAULT_CONFIG, ...config }; + + // VTK objects (initialized in initialize()) + this.vtk = null; + this.renderWindow = null; + this.renderer = null; + this.interactor = null; + this.openGLRenderWindow = null; + + // Feature modules + this.cameraController = null; + this.actorManager = null; + this.settingsPanel = null; + this.controlsBar = null; + this.screenshotCapture = null; + this.axisIndicator = null; + this.fieldVisualization = null; + this.textureManager = null; + + // State + this.actors = []; + this.polyDatas = []; + this.currentFilename = null; + this.isInitialized = false; + + // UI elements + this.loadingOverlay = null; + this.infoOverlay = null; + + // Message listener cleanup + this._messageCleanup = null; + } + + /** + * Initialize the viewer + * Must be called before loading meshes + */ + async initialize() { + if (this.isInitialized) { + console.warn('[BaseViewer] Already initialized'); + return; + } + + // Get VTK from global + this.vtk = window.vtk; + if (!this.vtk) { + throw new Error('VTK.js not loaded. Include vtk-gltf.js before initializing viewer.'); + } + + // Create VTK rendering pipeline + this._createRenderingPipeline(); + + // Initialize feature modules + this._initializeFeatures(); + + // Create UI elements + this._createUI(); + + // Setup resize handling + this._setupResizeHandler(); + + // Setup message listener for loading meshes + this._setupMessageListener(); + + this.isInitialized = true; + console.log('[BaseViewer] Initialized'); + } + + /** + * Create VTK rendering pipeline + * @private + */ + _createRenderingPipeline() { + // Create render window + this.renderWindow = this.vtk.Rendering.Core.vtkRenderWindow.newInstance(); + + // Create renderer + this.renderer = this.vtk.Rendering.Core.vtkRenderer.newInstance(); + this.renderer.setBackground(...this.config.backgroundColor); + this.renderWindow.addRenderer(this.renderer); + + // Two-sided lighting + if (this.config.twoSidedLighting) { + this.renderer.setTwoSidedLighting(true); + } + + // Create OpenGL render window + this.openGLRenderWindow = this.vtk.Rendering.OpenGL.vtkRenderWindow.newInstance(); + this.openGLRenderWindow.setContainer(this.container); + this.renderWindow.addView(this.openGLRenderWindow); + + // Create interactor + this.interactor = this.vtk.Rendering.Core.vtkRenderWindowInteractor.newInstance(); + this.interactor.setView(this.openGLRenderWindow); + this.interactor.initialize(); + this.interactor.bindEvents(this.container); + + // Set interactor style + const interactorStyle = this.vtk.Interaction.Style.vtkInteractorStyleTrackballCamera.newInstance(); + this.interactor.setInteractorStyle(interactorStyle); + + // Size to container + const { width, height } = this.container.getBoundingClientRect(); + this.openGLRenderWindow.setSize(width, height); + } + + /** + * Initialize feature modules + * @private + */ + _initializeFeatures() { + // Camera controller + this.cameraController = new CameraController(this.renderer, { + distanceMultiplier: this.config.cameraDistanceMultiplier, + parallelProjection: this.config.parallelProjection + }); + + // Actor manager + this.actorManager = new ActorManager(this.vtk, { + defaultColor: this.config.defaultMeshColor, + edgeColor: this.config.edgeColor, + edgeWidth: this.config.edgeWidth, + showEdges: this.config.showEdges + }); + + // Screenshot capture + if (this.config.enableScreenshot) { + this.screenshotCapture = new ScreenshotCapture(this.renderWindow); + } + + // Axis indicator + if (this.config.enableAxisIndicator) { + this.axisIndicator = new AxisIndicator(this.vtk, this.interactor, { + enabled: true + }); + } + + // Field visualization + if (this.config.enableFields) { + this.fieldVisualization = new FieldVisualization(this.vtk, this.renderWindow); + } + + // Texture manager + if (this.config.enableTextures) { + this.textureManager = new TextureManager(this.vtk, this.renderWindow); + } + } + + /** + * Create UI elements + * @private + */ + _createUI() { + // Loading overlay + if (this.config.showLoadingOverlay) { + this.loadingOverlay = this._createLoadingOverlay(); + } + + // Info overlay + if (this.config.showInfoOverlay) { + this.infoOverlay = this._createInfoOverlay(); + } + + // Settings panel + if (this.config.enableSettings && this.config.settingsConfig) { + this.settingsPanel = new SettingsPanel(this.config.settingsConfig); + this.settingsPanel.onApply((settings) => this._onSettingsApply(settings)); + } + + // Controls bar + if (this.config.enableControls && this.config.controlsConfig) { + this.controlsBar = new ControlsBar(this.config.controlsConfig); + this._setupControlsHandlers(); + } + } + + /** + * Create loading overlay element + * @private + * @returns {HTMLElement} + */ + _createLoadingOverlay() { + const overlay = document.createElement('div'); + overlay.id = 'loading'; + overlay.className = 'loading'; + overlay.innerHTML = ` +
+
Loading mesh...
+ + `; + this.container.parentElement.appendChild(overlay); + return overlay; + } + + /** + * Update the download progress bar. + * @param {number|null} fraction - 0..1, or null for indeterminate (hides the bar) + */ + setProgress(fraction) { + if (!this.loadingOverlay) return; + const wrap = this.loadingOverlay.querySelector('.loading-progress'); + const bar = this.loadingOverlay.querySelector('.loading-progress-bar'); + const textEl = this.loadingOverlay.querySelector('.loading-text'); + if (!wrap || !bar) return; + if (fraction == null || isNaN(fraction)) { + wrap.style.display = 'none'; // indeterminate -> spinner only + return; + } + const pct = Math.max(0, Math.min(100, Math.round(fraction * 100))); + wrap.style.display = 'block'; + bar.style.width = pct + '%'; + if (textEl) textEl.textContent = `Downloading mesh… ${pct}%`; + } + + /** + * Create info overlay element + * @private + * @returns {HTMLElement} + */ + _createInfoOverlay() { + const overlay = document.createElement('div'); + overlay.id = 'meshInfo'; + overlay.className = 'mesh-info'; + this.container.parentElement.appendChild(overlay); + return overlay; + } + + /** + * Setup resize handler + * @private + */ + _setupResizeHandler() { + const resizeObserver = new ResizeObserver(() => { + const { width, height } = this.container.getBoundingClientRect(); + if (width > 0 && height > 0) { + this.openGLRenderWindow.setSize(width, height); + this.renderWindow.render(); + } + }); + resizeObserver.observe(this.container); + this._resizeObserver = resizeObserver; + } + + /** + * Setup message listener for postMessage API + * @private + */ + _setupMessageListener() { + this._messageCleanup = createMessageListener((data) => { + if (data.type === 'loadMesh' && data.url) { + this.loadMesh(data.url); + } else if (data.type === 'screenshot') { + this.captureScreenshot(); + } + }); + } + + /** + * Setup controls bar handlers + * @private + */ + _setupControlsHandlers() { + if (!this.controlsBar) return; + + // Camera view buttons + this.controlsBar.onAction('camera-view', (direction) => { + this.setCameraView(direction); + }); + + // Screenshot button + this.controlsBar.onAction('screenshot', () => { + this.captureScreenshot(); + }); + + // Settings button + this.controlsBar.onAction('settings', () => { + if (this.settingsPanel) { + this.settingsPanel.open(); + } + }); + + // Edges toggle + this.controlsBar.onAction('edges-toggle', (show) => { + this.setEdgeVisibility(show); + }); + } + + /** + * Handle settings panel apply + * @private + * @param {Object} settings - Applied settings + */ + _onSettingsApply(settings) { + // Apply to actor manager + if (this.actorManager) { + this.actorManager.applySettings(this.actors, settings); + } + + // Apply background color + if (settings.backgroundColor) { + this.renderer.setBackground(...settings.backgroundColor); + } + + this.render(); + } + + /** + * Load a mesh from URL + * @param {string} url - Mesh file URL + * @returns {Promise} Load result with polyData, actors, fields + */ + async loadMesh(url) { + this.showLoading(true, 'Downloading mesh…'); + this.setProgress(0); + + try { + // Clear existing actors + this.clearScene(); + + // Detect format and load (with download progress) + const result = await loadMesh(url, this.vtk, { + renderer: this.renderer, + onProgress: (frac) => this.setProgress(frac) + }); + + // Store state + this.actors = result.actors; + this.polyDatas = result.polyData ? [result.polyData] : []; + this.currentFilename = extractFilename(url); + + // Add actors to renderer + result.actors.forEach(actor => { + this.renderer.addActor(actor); + }); + + // Configure actors + this._configureLoadedActors(result); + + // Setup camera + this._setupCameraForMesh(); + + // Update UI + this._updateInfoOverlay(result); + this.showLoading(false); + + // Notify parent + sendMeshLoaded({ + filename: this.currentFilename, + format: result.format, + actors: result.actors.length, + hasTexture: result.hasTexture || false, + hasVertexColors: result.hasVertexColors || false, + fields: result.fields || [] + }); + + this.render(); + return result; + + } catch (error) { + console.error('[BaseViewer] Error loading mesh:', error); + this.showLoading(false); + sendError(error.message); + throw error; + } + } + + /** + * Configure actors after loading + * @private + * @param {Object} result - Load result + */ + _configureLoadedActors(result) { + // Apply texture fixes if enabled + if (this.config.enableTextures && this.textureManager && result.hasTexture) { + this.textureManager.applyTextureFixesMultiple(this.actors); + this.textureManager.configureRenderer(this.renderer); + } else if (result.hasVertexColors) { + // Mesh has vertex colors - don't override with default color + // Just configure edges if needed, colors are already set up by loader + this.actors.forEach(actor => { + const property = actor.getProperty(); + if (property) { + if (this.config.showEdges) { + property.setEdgeVisibility(true); + if (this.config.edgeColor) { + property.setEdgeColor(...this.config.edgeColor); + } + } + } + }); + } else { + // Apply standard actor configuration + this.actorManager.configureActors(this.actors, { + color: this.config.defaultMeshColor, + showEdges: this.config.showEdges, + edgeColor: this.config.edgeColor + }); + } + } + + /** + * Setup camera position for loaded mesh + * @private + */ + _setupCameraForMesh() { + if (this.actors.length === 0) return; + + // Get combined bounds + let bounds = this.actors[0].getBounds(); + for (let i = 1; i < this.actors.length; i++) { + const actorBounds = this.actors[i].getBounds(); + bounds = [ + Math.min(bounds[0], actorBounds[0]), + Math.max(bounds[1], actorBounds[1]), + Math.min(bounds[2], actorBounds[2]), + Math.max(bounds[3], actorBounds[3]), + Math.min(bounds[4], actorBounds[4]), + Math.max(bounds[5], actorBounds[5]) + ]; + } + + if (isValidBounds(bounds)) { + this.cameraController.positionInitialCamera(bounds); + } + } + + /** + * Update info overlay with mesh information + * @private + * @param {Object} result - Load result + */ + _updateInfoOverlay(result) { + if (!this.infoOverlay) return; + + const lines = [`File: ${this.currentFilename}`]; + + if (result.polyData) { + const numPoints = result.polyData.getNumberOfPoints(); + const numCells = result.polyData.getNumberOfCells(); + lines.push(`Points: ${numPoints.toLocaleString()}`); + lines.push(`Cells: ${numCells.toLocaleString()}`); + } + + if (result.hasTexture) { + lines.push('Textured: Yes'); + } + + this.infoOverlay.innerHTML = lines.join('
'); + } + + /** + * Clear the scene + */ + clearScene() { + this.actors.forEach(actor => { + this.renderer.removeActor(actor); + }); + this.actors = []; + this.polyDatas = []; + } + + /** + * Set camera view direction + * @param {string} direction - '+X', '-X', '+Y', '-Y', '+Z', '-Z' + */ + setCameraView(direction) { + if (this.actors.length === 0) return; + + const bounds = this.actors[0].getBounds(); + this.cameraController.setCameraView(direction, bounds); + this.render(); + } + + /** + * Set edge visibility + * @param {boolean} visible + */ + setEdgeVisibility(visible) { + this.actors.forEach(actor => { + this.actorManager.setEdgeVisibility(actor, visible); + }); + this.render(); + } + + /** + * Capture screenshot + * @returns {Promise} Base64 image data + */ + async captureScreenshot() { + if (this.screenshotCapture) { + return this.screenshotCapture.captureAndSend(); + } + } + + /** + * Show/hide loading overlay + * @param {boolean} show + * @param {string} text - Optional loading text + */ + showLoading(show, text = 'Loading mesh...') { + if (this.loadingOverlay) { + this.loadingOverlay.style.display = show ? 'flex' : 'none'; + const textEl = this.loadingOverlay.querySelector('.loading-text'); + if (textEl) { + textEl.textContent = text; + } + if (!show) { + // reset the progress bar for the next load + const wrap = this.loadingOverlay.querySelector('.loading-progress'); + const bar = this.loadingOverlay.querySelector('.loading-progress-bar'); + if (wrap) wrap.style.display = 'none'; + if (bar) bar.style.width = '0%'; + } + } + } + + /** + * Render the scene + */ + render() { + this.renderWindow.render(); + } + + /** + * Resize the viewer + * @param {number} width + * @param {number} height + */ + resize(width, height) { + this.openGLRenderWindow.setSize(width, height); + this.render(); + } + + /** + * Get current actors + * @returns {Object[]} + */ + getActors() { + return this.actors; + } + + /** + * Get renderer + * @returns {Object} + */ + getRenderer() { + return this.renderer; + } + + /** + * Cleanup and destroy viewer + */ + destroy() { + // Cleanup message listener + if (this._messageCleanup) { + this._messageCleanup(); + } + + // Cleanup resize observer + if (this._resizeObserver) { + this._resizeObserver.disconnect(); + } + + // Cleanup axis indicator + if (this.axisIndicator) { + this.axisIndicator.destroy(); + } + + // Clear scene + this.clearScene(); + + // Delete VTK objects + if (this.interactor) { + this.interactor.unbindEvents(); + } + if (this.openGLRenderWindow) { + this.openGLRenderWindow.delete(); + } + if (this.renderWindow) { + this.renderWindow.delete(); + } + + // Remove UI elements + if (this.loadingOverlay && this.loadingOverlay.parentElement) { + this.loadingOverlay.parentElement.removeChild(this.loadingOverlay); + } + if (this.infoOverlay && this.infoOverlay.parentElement) { + this.infoOverlay.parentElement.removeChild(this.infoOverlay); + } + + console.log('[BaseViewer] Destroyed'); + } +} + +export default BaseViewer; diff --git a/javascript/js/viewer/core/CameraController.js b/javascript/js/viewer/core/CameraController.js new file mode 100644 index 00000000..7858f421 --- /dev/null +++ b/javascript/js/viewer/core/CameraController.js @@ -0,0 +1,271 @@ +/** + * CameraController - Unified camera management for VTK viewers + * + * Handles camera positioning, view presets, and projection modes. + * Configurable distance multiplier allows different viewers to use different defaults. + */ + +import { getCenter, getMaxDimension } from '../utils/BoundsUtils.js'; + +/** + * View direction configurations + * Maps direction strings to camera position offsets and viewUp vectors + */ +const VIEW_CONFIGS = { + '+X': { offset: [1, 0, 0], viewUp: [0, 0, 1] }, + '-X': { offset: [-1, 0, 0], viewUp: [0, 0, 1] }, + '+Y': { offset: [0, 1, 0], viewUp: [0, 0, 1] }, + '-Y': { offset: [0, -1, 0], viewUp: [0, 0, 1] }, + '+Z': { offset: [0, 0, 1], viewUp: [0, 1, 0] }, + '-Z': { offset: [0, 0, -1], viewUp: [0, 1, 0] } +}; + +/** + * Default camera configuration + */ +const DEFAULT_CONFIG = { + distanceMultiplier: 2.5, // Standard viewers use 2.5, textured uses 2.0 + initialViewOffset: [1, 1, 1], // Diagonal view for initial positioning + initialViewUp: [0, 0, 1] +}; + +export class CameraController { + /** + * Create a CameraController + * @param {Object} renderer - VTK renderer instance + * @param {Object} renderWindow - VTK render window instance + * @param {Object} config - Configuration options + * @param {number} config.distanceMultiplier - Camera distance = maxDim * multiplier (default: 2.5) + */ + constructor(renderer, renderWindow, config = {}) { + this.renderer = renderer; + this.renderWindow = renderWindow; + this.config = { ...DEFAULT_CONFIG, ...config }; + this.currentBounds = null; + } + + /** + * Get the active camera from the renderer + * @returns {Object} VTK camera instance + */ + getCamera() { + return this.renderer.getActiveCamera(); + } + + /** + * Store bounds for later use (e.g., view presets) + * @param {number[]} bounds - VTK bounds [xmin, xmax, ymin, ymax, zmin, zmax] + */ + setBounds(bounds) { + this.currentBounds = bounds; + } + + /** + * Position camera for initial viewing of mesh + * @param {number[]} bounds - VTK bounds [xmin, xmax, ymin, ymax, zmin, zmax] + */ + positionInitialCamera(bounds) { + this.currentBounds = bounds; + + const camera = this.getCamera(); + const center = getCenter(bounds); + const maxDim = getMaxDimension(bounds); + const distance = maxDim * this.config.distanceMultiplier; + + const offset = this.config.initialViewOffset; + const position = [ + center[0] + offset[0] * distance, + center[1] + offset[1] * distance, + center[2] + offset[2] * distance + ]; + + camera.setPosition(...position); + camera.setFocalPoint(...center); + camera.setViewUp(...this.config.initialViewUp); + + this.renderer.resetCamera(); + this.renderWindow.render(); + } + + /** + * Set camera to a specific axis-aligned view + * @param {string} direction - One of '+X', '-X', '+Y', '-Y', '+Z', '-Z' + * @param {number[]} bounds - Optional bounds, uses stored bounds if not provided + */ + setCameraView(direction, bounds = null) { + const activeBounds = bounds || this.currentBounds; + if (!activeBounds) { + console.warn('[CameraController] No bounds available for setCameraView'); + return; + } + + const viewConfig = VIEW_CONFIGS[direction]; + if (!viewConfig) { + console.warn(`[CameraController] Unknown view direction: ${direction}`); + return; + } + + const camera = this.getCamera(); + const center = getCenter(activeBounds); + const maxDim = getMaxDimension(activeBounds); + const distance = maxDim * this.config.distanceMultiplier; + + const position = [ + center[0] + viewConfig.offset[0] * distance, + center[1] + viewConfig.offset[1] * distance, + center[2] + viewConfig.offset[2] * distance + ]; + + camera.setPosition(...position); + camera.setFocalPoint(...center); + camera.setViewUp(...viewConfig.viewUp); + + this.renderer.resetCamera(); + this.renderWindow.render(); + } + + /** + * Reset camera to fit the current bounds + */ + resetCamera() { + if (this.currentBounds) { + this.renderer.resetCamera(this.currentBounds); + } else { + this.renderer.resetCamera(); + } + this.renderWindow.render(); + } + + /** + * Reset camera clipping range (useful after mesh updates) + */ + resetClippingRange() { + this.renderer.resetCameraClippingRange(); + this.renderWindow.render(); + } + + /** + * Set parallel (orthographic) vs perspective projection + * @param {boolean} enabled - True for parallel, false for perspective + */ + setParallelProjection(enabled) { + const camera = this.getCamera(); + camera.setParallelProjection(enabled); + this.renderWindow.render(); + } + + /** + * Get current parallel projection state + * @returns {boolean} True if parallel projection is enabled + */ + getParallelProjection() { + return this.getCamera().getParallelProjection(); + } + + /** + * Synchronize this camera with another camera + * Useful for side-by-side viewers + * @param {Object} sourceCamera - Camera to copy state from + */ + synchronizeFrom(sourceCamera) { + const camera = this.getCamera(); + camera.setPosition(...sourceCamera.getPosition()); + camera.setFocalPoint(...sourceCamera.getFocalPoint()); + camera.setViewUp(...sourceCamera.getViewUp()); + camera.setParallelProjection(sourceCamera.getParallelProjection()); + camera.setClippingRange(...sourceCamera.getClippingRange()); + camera.setParallelScale(sourceCamera.getParallelScale()); + camera.setViewAngle(sourceCamera.getViewAngle()); + } + + /** + * Get camera state for serialization + * @returns {Object} Camera state object + */ + getState() { + const camera = this.getCamera(); + return { + position: camera.getPosition(), + focalPoint: camera.getFocalPoint(), + viewUp: camera.getViewUp(), + parallelProjection: camera.getParallelProjection(), + clippingRange: camera.getClippingRange(), + parallelScale: camera.getParallelScale(), + viewAngle: camera.getViewAngle() + }; + } + + /** + * Restore camera state from serialized object + * @param {Object} state - Camera state object from getState() + */ + setState(state) { + const camera = this.getCamera(); + if (state.position) camera.setPosition(...state.position); + if (state.focalPoint) camera.setFocalPoint(...state.focalPoint); + if (state.viewUp) camera.setViewUp(...state.viewUp); + if (state.parallelProjection !== undefined) camera.setParallelProjection(state.parallelProjection); + if (state.clippingRange) camera.setClippingRange(...state.clippingRange); + if (state.parallelScale !== undefined) camera.setParallelScale(state.parallelScale); + if (state.viewAngle !== undefined) camera.setViewAngle(state.viewAngle); + this.renderWindow.render(); + } + + /** + * Focus camera on a specific 3D point + * Moves the camera to look at the point while maintaining relative view direction + * @param {number[]} point - [x, y, z] coordinates to focus on + * @param {number} viewRadius - Optional radius around point to view (defaults to 1/10 of mesh size) + */ + focusOnPoint(point, viewRadius = null) { + const camera = this.getCamera(); + + // Get current camera direction (from focal point to camera position) + const currentFocalPoint = camera.getFocalPoint(); + const currentPosition = camera.getPosition(); + const direction = [ + currentPosition[0] - currentFocalPoint[0], + currentPosition[1] - currentFocalPoint[1], + currentPosition[2] - currentFocalPoint[2] + ]; + + // Normalize direction + const length = Math.sqrt(direction[0]**2 + direction[1]**2 + direction[2]**2); + if (length > 0) { + direction[0] /= length; + direction[1] /= length; + direction[2] /= length; + } else { + // Default to looking from +Z if no current direction + direction[0] = 0; + direction[1] = 0; + direction[2] = 1; + } + + // Calculate view distance + let distance; + if (viewRadius !== null) { + distance = viewRadius * this.config.distanceMultiplier; + } else if (this.currentBounds) { + const maxDim = getMaxDimension(this.currentBounds); + distance = maxDim * 0.3; // Closer view for focused point + } else { + distance = 10; // Fallback + } + + // Position camera along the direction from the point + const newPosition = [ + point[0] + direction[0] * distance, + point[1] + direction[1] * distance, + point[2] + direction[2] * distance + ]; + + camera.setFocalPoint(...point); + camera.setPosition(...newPosition); + + this.renderer.resetCameraClippingRange(); + this.renderWindow.render(); + } +} + +export default CameraController; diff --git a/javascript/js/viewer/features/AxisIndicator.js b/javascript/js/viewer/features/AxisIndicator.js new file mode 100644 index 00000000..095f23fc --- /dev/null +++ b/javascript/js/viewer/features/AxisIndicator.js @@ -0,0 +1,242 @@ +/** + * AxisIndicator - Orientation widget for VTK viewers + * + * Creates and manages an annotated cube axis indicator that shows + * the current camera orientation. + */ + +import { rgbToString } from '../utils/ColorUtils.js'; + +/** + * Default axis colors + */ +const DEFAULT_COLORS = { + x: '#ff5555', // Red for X axis + y: '#55ff55', // Green for Y axis + z: '#5555ff' // Blue for Z axis +}; + +/** + * Default widget configuration + */ +const DEFAULT_CONFIG = { + enabled: false, + corner: 'BOTTOM_LEFT', // BOTTOM_LEFT, BOTTOM_RIGHT, TOP_LEFT, TOP_RIGHT + viewportSize: 0.15, + minPixelSize: 100, + maxPixelSize: 300, + faceColor: rgbToString(0.5, 0.5, 0.5) +}; + +export class AxisIndicator { + /** + * Create an AxisIndicator + * @param {Object} vtk - VTK.js global object + * @param {Object} interactor - VTK interactor (from renderWindow.getInteractor()) + * @param {Object} config - Configuration options + */ + constructor(vtk, interactor, config = {}) { + this.vtk = vtk; + this.interactor = interactor; + this.config = { ...DEFAULT_CONFIG, ...config }; + + // VTK classes + this.vtkOrientationMarkerWidget = vtk.Interaction.Widgets.vtkOrientationMarkerWidget; + this.vtkAnnotatedCubeActor = vtk.Rendering.Core.vtkAnnotatedCubeActor; + + // Widget state + this.widget = null; + this.cubeActor = null; + this.enabled = this.config.enabled; + + this._createWidget(); + } + + /** + * Create the orientation widget + * @private + */ + _createWidget() { + // Create annotated cube actor + this.cubeActor = this.vtkAnnotatedCubeActor.newInstance(); + + // Set default style + this.cubeActor.setDefaultStyle({ + text: '+X', + fontStyle: 'bold', + fontFamily: 'Arial', + fontColor: 'white', + fontSizeScale: (res) => res / 2, + faceColor: this.config.faceColor, + faceRotation: 0, + edgeThickness: 0.1, + edgeColor: 'white', + resolution: 400, + }); + + // Customize each face with axis colors + this.cubeActor.setXPlusFaceProperty({ text: '+X', faceColor: DEFAULT_COLORS.x }); + this.cubeActor.setXMinusFaceProperty({ text: '-X', faceColor: DEFAULT_COLORS.x }); + this.cubeActor.setYPlusFaceProperty({ text: '+Y', faceColor: DEFAULT_COLORS.y }); + this.cubeActor.setYMinusFaceProperty({ text: '-Y', faceColor: DEFAULT_COLORS.y }); + this.cubeActor.setZPlusFaceProperty({ text: '+Z', faceColor: DEFAULT_COLORS.z }); + this.cubeActor.setZMinusFaceProperty({ text: '-Z', faceColor: DEFAULT_COLORS.z }); + + // Create orientation marker widget + this.widget = this.vtkOrientationMarkerWidget.newInstance({ + actor: this.cubeActor, + interactor: this.interactor, + }); + + // Configure widget position and size + this._applyCornerConfig(); + this.widget.setViewportSize(this.config.viewportSize); + this.widget.setMinPixelSize(this.config.minPixelSize); + this.widget.setMaxPixelSize(this.config.maxPixelSize); + + // Set initial enabled state + this.widget.setEnabled(this.enabled); + } + + /** + * Apply corner configuration + * @private + */ + _applyCornerConfig() { + const Corners = this.vtkOrientationMarkerWidget.Corners; + const cornerMap = { + 'BOTTOM_LEFT': Corners.BOTTOM_LEFT, + 'BOTTOM_RIGHT': Corners.BOTTOM_RIGHT, + 'TOP_LEFT': Corners.TOP_LEFT, + 'TOP_RIGHT': Corners.TOP_RIGHT + }; + + const corner = cornerMap[this.config.corner] || Corners.BOTTOM_LEFT; + this.widget.setViewportCorner(corner); + } + + /** + * Enable the axis indicator + */ + enable() { + this.enabled = true; + if (this.widget) { + this.widget.setEnabled(true); + } + } + + /** + * Disable the axis indicator + */ + disable() { + this.enabled = false; + if (this.widget) { + this.widget.setEnabled(false); + } + } + + /** + * Toggle the axis indicator + * @returns {boolean} New enabled state + */ + toggle() { + if (this.enabled) { + this.disable(); + } else { + this.enable(); + } + return this.enabled; + } + + /** + * Set enabled state + * @param {boolean} enabled - Whether to enable the indicator + */ + setEnabled(enabled) { + if (enabled) { + this.enable(); + } else { + this.disable(); + } + } + + /** + * Check if enabled + * @returns {boolean} + */ + isEnabled() { + return this.enabled; + } + + /** + * Set the corner position + * @param {string} corner - 'BOTTOM_LEFT', 'BOTTOM_RIGHT', 'TOP_LEFT', 'TOP_RIGHT' + */ + setCorner(corner) { + this.config.corner = corner; + this._applyCornerConfig(); + } + + /** + * Set viewport size (0-1 range) + * @param {number} size - Viewport size as fraction + */ + setViewportSize(size) { + this.config.viewportSize = size; + if (this.widget) { + this.widget.setViewportSize(size); + } + } + + /** + * Set axis colors + * @param {Object} colors - Color object with x, y, z properties (hex strings) + */ + setAxisColors(colors) { + if (colors.x) { + this.cubeActor.setXPlusFaceProperty({ faceColor: colors.x }); + this.cubeActor.setXMinusFaceProperty({ faceColor: colors.x }); + } + if (colors.y) { + this.cubeActor.setYPlusFaceProperty({ faceColor: colors.y }); + this.cubeActor.setYMinusFaceProperty({ faceColor: colors.y }); + } + if (colors.z) { + this.cubeActor.setZPlusFaceProperty({ faceColor: colors.z }); + this.cubeActor.setZMinusFaceProperty({ faceColor: colors.z }); + } + } + + /** + * Get the underlying VTK widget + * @returns {Object} VTK orientation marker widget + */ + getWidget() { + return this.widget; + } + + /** + * Get the cube actor + * @returns {Object} VTK annotated cube actor + */ + getCubeActor() { + return this.cubeActor; + } + + /** + * Cleanup resources + */ + destroy() { + if (this.widget) { + this.widget.setEnabled(false); + this.widget.delete(); + this.widget = null; + } + if (this.cubeActor) { + this.cubeActor.delete(); + this.cubeActor = null; + } + } +} + +export default AxisIndicator; diff --git a/javascript/js/viewer/features/FieldVisualization.js b/javascript/js/viewer/features/FieldVisualization.js new file mode 100644 index 00000000..05159123 --- /dev/null +++ b/javascript/js/viewer/features/FieldVisualization.js @@ -0,0 +1,352 @@ +/** + * FieldVisualization - Scalar field coloring for VTK viewers + * + * Handles scalar field visualization including: + * - Field detection (point/cell data) + * - Colormap application + * - Range calculation (auto/manual, single/synchronized) + */ + +/** + * Popular colormaps to show at top of selector + */ +const POPULAR_COLORMAPS = [ + 'erdc_rainbow_bright', + 'Cool to Warm', + 'Viridis (matplotlib)', + 'Plasma (matplotlib)', + 'Inferno (matplotlib)', + 'Magma (matplotlib)', + 'jet', + 'rainbow' +]; + +export class FieldVisualization { + /** + * Create a FieldVisualization instance + * @param {Object} vtk - VTK.js global object + * @param {Object} renderWindow - VTK render window for triggering renders + */ + constructor(vtk, renderWindow) { + this.vtk = vtk; + this.renderWindow = renderWindow; + + // VTK classes + this.vtkColorTransferFunction = vtk.Rendering.Core.vtkColorTransferFunction; + this.vtkColorMaps = vtk.Rendering.Core.vtkColorTransferFunction.vtkColorMaps; + + // State + this.currentField = null; + this.currentColormap = 'erdc_rainbow_bright'; + this.autoRange = true; + this.manualRange = [0, 1]; + } + + /** + * Extract field information from polydata + * @param {Object} polyData - VTK polydata object + * @returns {Object} Field information with pointFields and cellFields arrays + */ + extractFields(polyData) { + if (!polyData) { + return { pointFields: [], cellFields: [], allFields: [] }; + } + + // Fields to hide from dropdown (VTK internal arrays that aren't useful to visualize) + const HIDDEN_FIELDS = ['Attribute', 'vtkOriginalPointIds', 'vtkOriginalCellIds']; + + const pointData = polyData.getPointData(); + const cellData = polyData.getCellData(); + + const pointFields = []; + const cellFields = []; + + // Extract point (vertex) data arrays + for (let i = 0; i < pointData.getNumberOfArrays(); i++) { + const array = pointData.getArray(i); + const name = array.getName(); + // Skip hidden/internal fields + if (HIDDEN_FIELDS.includes(name)) continue; + const range = array.getRange(); + pointFields.push({ + name, + displayName: `${name} (vertex)`, + type: 'point', + fullName: `point:${name}`, + numComponents: array.getNumberOfComponents(), + range: [range[0], range[1]] + }); + } + + // Extract cell (face) data arrays + for (let i = 0; i < cellData.getNumberOfArrays(); i++) { + const array = cellData.getArray(i); + const name = array.getName(); + // Skip hidden/internal fields + if (HIDDEN_FIELDS.includes(name)) continue; + const range = array.getRange(); + cellFields.push({ + name, + displayName: `${name} (face)`, + type: 'cell', + fullName: `cell:${name}`, + numComponents: array.getNumberOfComponents(), + range: [range[0], range[1]] + }); + } + + const allFields = [...pointFields, ...cellFields]; + + return { + pointFields, + cellFields, + allFields, + hasFields: allFields.length > 0 + }; + } + + /** + * Apply a scalar field to a mapper + * @param {Object} mapper - VTK mapper + * @param {Object} polyData - VTK polydata + * @param {string} fieldName - Field name (e.g., "point:temperature" or "cell:pressure") + * @param {Object} options - Options + * @param {number[]} options.range - Manual range [min, max] (overrides auto) + * @param {string} options.colormap - Colormap name + * @param {boolean} options.render - Whether to trigger render (default: true) + */ + applyField(mapper, polyData, fieldName, options = {}) { + const { + range = null, + colormap = this.currentColormap, + render = true + } = options; + + if (!fieldName || fieldName === 'none' || !polyData) { + this.disableScalarVisualization(mapper, render); + return; + } + + // Parse field name + const isCellData = fieldName.startsWith('cell:'); + const actualFieldName = isCellData + ? fieldName.substring(5) + : fieldName.startsWith('point:') + ? fieldName.substring(6) + : fieldName; + + // Get data array + const data = isCellData ? polyData.getCellData() : polyData.getPointData(); + const scalarArray = data.getArrayByName(actualFieldName); + + if (!scalarArray) { + console.warn(`[FieldVisualization] Field "${actualFieldName}" not found`); + this.disableScalarVisualization(mapper, render); + return; + } + + // Get range + const dataRange = scalarArray.getRange(); + const [minVal, maxVal] = range || (this.autoRange ? dataRange : this.manualRange); + + // Check for degenerate range + const epsilon = 1e-10; + if (Math.abs(maxVal - minVal) < epsilon && !range) { + console.warn(`[FieldVisualization] Field "${actualFieldName}" has zero-width range`); + this.disableScalarVisualization(mapper, render); + return; + } + + // Set active scalars + data.setActiveScalars(actualFieldName); + + // Configure mapper + mapper.setScalarVisibility(true); + if (isCellData) { + mapper.setScalarModeToUseCellData(); + } else { + mapper.setScalarModeToUsePointData(); + } + mapper.setScalarRange(minVal, maxVal); + + // Apply colormap + this.applyColormap(mapper, colormap, minVal, maxVal); + + // Update state + this.currentField = fieldName; + this.currentColormap = colormap; + + // Update mapper to apply changes + mapper.update(); + + if (render) { + this.renderWindow.render(); + } + + console.log(`[FieldVisualization] Applied field "${actualFieldName}" with range [${minVal.toFixed(3)}, ${maxVal.toFixed(3)}]`); + } + + /** + * Apply a colormap to a mapper + * @param {Object} mapper - VTK mapper + * @param {string} colormapName - Colormap preset name + * @param {number} minVal - Range minimum + * @param {number} maxVal - Range maximum + */ + applyColormap(mapper, colormapName, minVal, maxVal) { + try { + const lookupTable = this.vtkColorTransferFunction.newInstance(); + const preset = this.vtkColorMaps.getPresetByName(colormapName); + + if (preset) { + lookupTable.applyColorMap(preset); + lookupTable.setMappingRange(minVal, maxVal); + lookupTable.updateRange(); + mapper.setLookupTable(lookupTable); + } else { + console.warn(`[FieldVisualization] Colormap "${colormapName}" not found`); + } + } catch (error) { + console.error('[FieldVisualization] Error applying colormap:', error); + } + } + + /** + * Disable scalar visualization on a mapper + * @param {Object} mapper - VTK mapper + * @param {boolean} render - Whether to trigger render + */ + disableScalarVisualization(mapper, render = true) { + if (mapper) { + mapper.setScalarVisibility(false); + } + this.currentField = null; + if (render) { + this.renderWindow.render(); + } + } + + /** + * Get available colormap presets + * @param {boolean} popularFirst - Put popular colormaps at top (default: true) + * @returns {Array} Array of {value, label, isPopular} objects + */ + getColormapOptions(popularFirst = true) { + const allPresets = this.vtkColorMaps.rgbPresetNames || []; + const options = []; + + if (popularFirst) { + // Add popular colormaps first + POPULAR_COLORMAPS.forEach(name => { + if (allPresets.includes(name)) { + options.push({ value: name, label: name, isPopular: true }); + } + }); + + // Add separator + options.push({ value: '', label: '----------', disabled: true }); + + // Add remaining colormaps + allPresets + .filter(name => !POPULAR_COLORMAPS.includes(name)) + .sort() + .forEach(name => { + options.push({ value: name, label: name, isPopular: false }); + }); + } else { + allPresets.sort().forEach(name => { + options.push({ value: name, label: name, isPopular: POPULAR_COLORMAPS.includes(name) }); + }); + } + + return options; + } + + /** + * Set auto range mode + * @param {boolean} auto - Whether to use auto range + */ + setAutoRange(auto) { + this.autoRange = auto; + } + + /** + * Set manual range + * @param {number} min - Range minimum + * @param {number} max - Range maximum + */ + setManualRange(min, max) { + this.manualRange = [min, max]; + } + + /** + * Calculate synchronized range for multiple polydatas + * @param {Object[]} polydatas - Array of VTK polydata objects + * @param {string} fieldName - Field name + * @returns {number[]} Combined range [min, max] + */ + calculateSynchronizedRange(polydatas, fieldName) { + let globalMin = Infinity; + let globalMax = -Infinity; + + const isCellData = fieldName.startsWith('cell:'); + const actualFieldName = isCellData + ? fieldName.substring(5) + : fieldName.startsWith('point:') + ? fieldName.substring(6) + : fieldName; + + polydatas.forEach(polyData => { + if (!polyData) return; + + const data = isCellData ? polyData.getCellData() : polyData.getPointData(); + const scalarArray = data?.getArrayByName(actualFieldName); + + if (scalarArray) { + const range = scalarArray.getRange(); + globalMin = Math.min(globalMin, range[0]); + globalMax = Math.max(globalMax, range[1]); + } + }); + + if (globalMin === Infinity || globalMax === -Infinity) { + return [0, 1]; // Default range + } + + return [globalMin, globalMax]; + } + + /** + * Find common fields between multiple polydatas + * @param {Object[]} polydatas - Array of VTK polydata objects + * @returns {Object} Object with commonPointFields, commonCellFields, commonAllFields + */ + findCommonFields(polydatas) { + if (!polydatas || polydatas.length === 0) { + return { commonPointFields: [], commonCellFields: [], commonAllFields: [] }; + } + + // Get fields from first polydata + const firstFields = this.extractFields(polydatas[0]); + let commonPointFields = firstFields.pointFields.map(f => f.name); + let commonCellFields = firstFields.cellFields.map(f => f.name); + + // Intersect with remaining polydatas + for (let i = 1; i < polydatas.length; i++) { + const fields = this.extractFields(polydatas[i]); + const pointNames = fields.pointFields.map(f => f.name); + const cellNames = fields.cellFields.map(f => f.name); + + commonPointFields = commonPointFields.filter(n => pointNames.includes(n)); + commonCellFields = commonCellFields.filter(n => cellNames.includes(n)); + } + + return { + commonPointFields, + commonCellFields, + commonAllFields: [...commonPointFields, ...commonCellFields] + }; + } +} + +export default FieldVisualization; diff --git a/javascript/js/viewer/features/ScreenshotCapture.js b/javascript/js/viewer/features/ScreenshotCapture.js new file mode 100644 index 00000000..27b90a35 --- /dev/null +++ b/javascript/js/viewer/features/ScreenshotCapture.js @@ -0,0 +1,97 @@ +/** + * ScreenshotCapture - Screenshot functionality for VTK viewers + * + * Handles capturing screenshots from VTK render windows and + * sending them via postMessage or triggering downloads. + */ + +import { sendScreenshot } from '../utils/MessageHandler.js'; + +export class ScreenshotCapture { + /** + * Create a ScreenshotCapture instance + * @param {Object} renderWindow - VTK render window + */ + constructor(renderWindow) { + this.renderWindow = renderWindow; + } + + /** + * Capture a screenshot as a base64 PNG data URL + * @returns {Promise} Base64 PNG data URL + */ + async capture() { + const images = await this.renderWindow.captureImages(); + return images[0]; // Returns base64 PNG data URL + } + + /** + * Capture and send screenshot to parent window via postMessage + * @returns {Promise} + */ + async captureAndSend() { + try { + const image = await this.capture(); + sendScreenshot(image); + console.log('[ScreenshotCapture] Screenshot captured and sent to parent'); + } catch (error) { + console.error('[ScreenshotCapture] Error capturing screenshot:', error); + throw error; + } + } + + /** + * Capture and download screenshot as a file + * @param {string} filename - Download filename (default: "screenshot.png") + * @returns {Promise} + */ + async captureAndDownload(filename = 'screenshot.png') { + try { + const image = await this.capture(); + + // Create download link + const link = document.createElement('a'); + link.href = image; + link.download = filename; + link.style.display = 'none'; + + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + + console.log('[ScreenshotCapture] Screenshot downloaded:', filename); + } catch (error) { + console.error('[ScreenshotCapture] Error downloading screenshot:', error); + throw error; + } + } + + /** + * Capture screenshot and return as Blob + * @returns {Promise} PNG Blob + */ + async captureAsBlob() { + const image = await this.capture(); + + // Convert base64 to blob + const response = await fetch(image); + return response.blob(); + } + + /** + * Generate a timestamp-based filename + * @param {string} prefix - Filename prefix (default: "screenshot") + * @param {string} extension - File extension (default: "png") + * @returns {string} Filename with timestamp + */ + static generateFilename(prefix = 'screenshot', extension = 'png') { + const now = new Date(); + const timestamp = now.toISOString() + .replace(/[:.]/g, '-') + .replace('T', '_') + .slice(0, 19); + return `${prefix}_${timestamp}.${extension}`; + } +} + +export default ScreenshotCapture; diff --git a/javascript/js/viewer/features/TextureManager.js b/javascript/js/viewer/features/TextureManager.js new file mode 100644 index 00000000..dccd7d94 --- /dev/null +++ b/javascript/js/viewer/features/TextureManager.js @@ -0,0 +1,213 @@ +/** + * TextureManager - Texture handling for GLTF/GLB meshes + * + * Manages texture extraction, material fixes, and rendering configuration + * for properly displaying textured meshes in VTK.js. + */ + +/** + * Texture information structure + * @typedef {Object} TextureInfo + * @property {boolean} hasTexture - Whether a texture was found + * @property {boolean} hasMaterial - Whether PBR material properties exist + * @property {string} textureType - Type of texture found (baseColor, diffuse, etc.) + */ + +export class TextureManager { + /** + * Create a TextureManager + * @param {Object} vtk - VTK.js global object + * @param {Object} renderWindow - VTK render window + */ + constructor(vtk, renderWindow) { + this.vtk = vtk; + this.renderWindow = renderWindow; + } + + /** + * Apply texture fixes to an actor + * This fixes common issues with GLTF texture rendering in VTK.js + * @param {Object} actor - VTK actor + * @returns {TextureInfo} Texture information + */ + applyTextureFixes(actor) { + const property = actor.getProperty(); + const mapper = actor.getMapper(); + const info = { + hasTexture: false, + hasMaterial: false, + textureType: null + }; + + if (!property) { + return info; + } + + // CRITICAL FIX: Remove metallicRoughnessTexture if present + // VTK.js GLTFImporter may use this instead of baseColorTexture + if (typeof property.setRMTexture === 'function') { + property.setRMTexture(null); + } + if (typeof property.setMetallicRoughnessTexture === 'function') { + property.setMetallicRoughnessTexture(null); + } + + // Try multiple methods to get the base color texture + let texture = null; + + if (typeof property.getBaseColorTexture === 'function') { + texture = property.getBaseColorTexture(); + if (texture) info.textureType = 'baseColor'; + } + if (!texture && typeof property.getDiffuseTexture === 'function') { + texture = property.getDiffuseTexture(); + if (texture) info.textureType = 'diffuse'; + } + if (!texture && typeof property.getTexture === 'function') { + texture = property.getTexture(); + if (texture) info.textureType = 'generic'; + } + + if (texture) { + info.hasTexture = true; + actor.addTexture(texture); + } + + // Check for PBR material properties + if (typeof property.getMetallic === 'function' || + typeof property.getRoughness === 'function') { + info.hasMaterial = true; + } + + // Set material to non-metallic for proper texture display + if (typeof property.setMetallic === 'function') { + property.setMetallic(0.0); + } + if (typeof property.setRoughness === 'function') { + property.setRoughness(1.0); + } + if (typeof property.setInterpolation === 'function') { + property.setInterpolation(2); // Phong shading + } + + // Configure mapper for texture rendering + if (mapper) { + mapper.setScalarVisibility(false); + mapper.modified(); + } + + return info; + } + + /** + * Apply texture fixes to multiple actors + * @param {Object[]} actors - Array of VTK actors + * @returns {TextureInfo} Combined texture information + */ + applyTextureFixesMultiple(actors) { + const combinedInfo = { + hasTexture: false, + hasMaterial: false, + texturedActors: 0 + }; + + actors.forEach(actor => { + const info = this.applyTextureFixes(actor); + if (info.hasTexture) { + combinedInfo.hasTexture = true; + combinedInfo.texturedActors++; + } + if (info.hasMaterial) { + combinedInfo.hasMaterial = true; + } + }); + + return combinedInfo; + } + + /** + * Configure renderer for texture display + * @param {Object} renderer - VTK renderer + */ + configureRenderer(renderer) { + // Enable two-sided lighting for better texture visibility + if (typeof renderer.setTwoSidedLighting === 'function') { + renderer.setTwoSidedLighting(true); + } + + // Disable shadows (can interfere with texture display) + if (typeof renderer.setUseShadows === 'function') { + renderer.setUseShadows(false); + } + } + + /** + * Set actor appearance for non-textured display (solid color) + * @param {Object} actor - VTK actor + * @param {number[]} color - RGB color array [0-1 range] + */ + setActorColor(actor, color = [1.0, 1.0, 1.0]) { + const property = actor.getProperty(); + const mapper = actor.getMapper(); + + if (property) { + property.setColor(...color); + } + + if (mapper) { + mapper.setScalarVisibility(false); + } + } + + /** + * Extract texture information from actor without modifying it + * @param {Object} actor - VTK actor + * @returns {TextureInfo} Texture information + */ + getTextureInfo(actor) { + const property = actor.getProperty(); + const info = { + hasTexture: false, + hasMaterial: false, + textureType: null + }; + + if (!property) { + return info; + } + + // Check for textures + if (typeof property.getBaseColorTexture === 'function' && property.getBaseColorTexture()) { + info.hasTexture = true; + info.textureType = 'baseColor'; + } else if (typeof property.getDiffuseTexture === 'function' && property.getDiffuseTexture()) { + info.hasTexture = true; + info.textureType = 'diffuse'; + } else if (typeof property.getTexture === 'function' && property.getTexture()) { + info.hasTexture = true; + info.textureType = 'generic'; + } + + // Check for material + if (typeof property.getMetallic === 'function' || + typeof property.getRoughness === 'function') { + info.hasMaterial = true; + } + + return info; + } + + /** + * Check if GLTF texture support is available + * @returns {boolean} + */ + isTextureSupported() { + try { + return this.vtk.IO.Geometry.vtkGLTFImporter !== undefined; + } catch { + return false; + } + } +} + +export default TextureManager; diff --git a/javascript/js/viewer/index.js b/javascript/js/viewer/index.js new file mode 100644 index 00000000..aa68bad1 --- /dev/null +++ b/javascript/js/viewer/index.js @@ -0,0 +1,199 @@ +/** + * GeomPack VTK Viewer - Main Entry Point + * + * This module exports the ViewerFactory and all viewer components + * for creating unified VTK viewers. + */ + +// Utils +import ColorUtils from './utils/ColorUtils.js'; +import BoundsUtils from './utils/BoundsUtils.js'; +import MessageHandler from './utils/MessageHandler.js'; + +// Core +import CameraController from './core/CameraController.js'; +import ActorManager, { Representation } from './core/ActorManager.js'; +import BaseViewer from './core/BaseViewer.js'; + +// UI +import SettingsPanel, { SettingTypes } from './ui/SettingsPanel.js'; +import ControlsBar, { ControlTypes, StandardControls } from './ui/ControlsBar.js'; + +// Loaders +import LoaderFactory, { FormatTypes } from './loaders/LoaderFactory.js'; +import STLLoader from './loaders/STLLoader.js'; +import OBJLoader from './loaders/OBJLoader.js'; +import VTPLoader from './loaders/VTPLoader.js'; +import GLTFLoader from './loaders/GLTFLoader.js'; + +// Features +import FieldVisualization from './features/FieldVisualization.js'; +import TextureManager from './features/TextureManager.js'; +import ScreenshotCapture from './features/ScreenshotCapture.js'; +import AxisIndicator from './features/AxisIndicator.js'; + +// Viewers +import StandardViewer, { createStandardViewer } from './viewers/StandardViewer.js'; +import TexturedViewer, { createTexturedViewer } from './viewers/TexturedViewer.js'; +import DualViewer, { createDualViewer, DualLayoutMode } from './viewers/DualViewer.js'; + +// Re-export utilities +export { ColorUtils, BoundsUtils, MessageHandler }; + +// Re-export core +export { CameraController, ActorManager, Representation, BaseViewer }; + +// Re-export UI +export { SettingsPanel, SettingTypes, ControlsBar, ControlTypes, StandardControls }; + +// Re-export loaders +export { LoaderFactory, FormatTypes, STLLoader, OBJLoader, VTPLoader, GLTFLoader }; + +// Re-export features +export { FieldVisualization, TextureManager, ScreenshotCapture, AxisIndicator }; + +// Re-export viewers +export { StandardViewer, TexturedViewer, DualViewer, DualLayoutMode }; +export { createStandardViewer, createTexturedViewer, createDualViewer }; + +// Export individual utility functions for convenience +export { rgbToString, hexToRgb, rgbToHex } from './utils/ColorUtils.js'; +export { getCenter, getMaxDimension, getDimensions, combineBounds, isValidBounds } from './utils/BoundsUtils.js'; +export { + MessageTypes, + sendToParent, + sendError, + sendScreenshot, + sendMeshLoaded, + createMessageListener, + extractFilename +} from './utils/MessageHandler.js'; + +// Export loader factory functions +export { + loadMesh, + loadMeshes, + detectFormat, + requiresRenderer, + supportsTextures, + supportsFields, + getLoaderConfig +} from './loaders/LoaderFactory.js'; + +/** + * Viewer types for ViewerFactory + */ +export const ViewerTypes = { + STANDARD: 'standard', + TEXTURED: 'textured', + DUAL: 'dual' +}; + +/** + * ViewerFactory - Creates viewer instances + * + * Usage: + * const viewer = ViewerFactory.create('standard', containerEl); + * await viewer.initialize(); + * await viewer.loadMesh('/path/to/mesh.stl'); + */ +export const ViewerFactory = { + /** + * Create a viewer instance + * @param {string} type - Viewer type ('standard', 'textured', 'dual') + * @param {HTMLElement|HTMLElement[]} container - Container element(s) + * @param {Object} options - Viewer options + * @returns {BaseViewer|DualViewer} Viewer instance + */ + create(type, container, options = {}) { + console.log(`[GeomPack Viewer] Creating ${type} viewer`); + + switch (type) { + case ViewerTypes.STANDARD: + case 'standard': + return new StandardViewer(container, options); + + case ViewerTypes.TEXTURED: + case 'textured': + return new TexturedViewer(container, options); + + case ViewerTypes.DUAL: + case 'dual': + // Dual viewer expects two containers + if (Array.isArray(container)) { + return new DualViewer(container[0], container[1], options); + } else if (options.containerB) { + return new DualViewer(container, options.containerB, options); + } else { + throw new Error('DualViewer requires two containers'); + } + + default: + console.warn(`[GeomPack Viewer] Unknown viewer type: ${type}, falling back to standard`); + return new StandardViewer(container, options); + } + }, + + /** + * Create and initialize a viewer + * @param {string} type - Viewer type + * @param {HTMLElement|HTMLElement[]} container - Container element(s) + * @param {Object} options - Viewer options + * @returns {Promise} Initialized viewer + */ + async createAndInit(type, container, options = {}) { + const viewer = this.create(type, container, options); + await viewer.initialize(); + return viewer; + } +}; + +// Default export +export default { + // Utils + ColorUtils, + BoundsUtils, + MessageHandler, + + // Core + CameraController, + ActorManager, + Representation, + BaseViewer, + + // UI + SettingsPanel, + SettingTypes, + ControlsBar, + ControlTypes, + StandardControls, + + // Loaders + LoaderFactory, + FormatTypes, + STLLoader, + OBJLoader, + VTPLoader, + GLTFLoader, + + // Features + FieldVisualization, + TextureManager, + ScreenshotCapture, + AxisIndicator, + + // Viewers + StandardViewer, + TexturedViewer, + DualViewer, + DualLayoutMode, + ViewerTypes, + + // Factory functions + createStandardViewer, + createTexturedViewer, + createDualViewer, + + // Factory + ViewerFactory +}; diff --git a/javascript/js/viewer/loaders/GLTFLoader.js b/javascript/js/viewer/loaders/GLTFLoader.js new file mode 100644 index 00000000..b589f853 --- /dev/null +++ b/javascript/js/viewer/loaders/GLTFLoader.js @@ -0,0 +1,299 @@ +/** + * GLTFLoader - GLTF/GLB mesh file loader with texture support + * + * Loads GLTF/GLB files using VTK.js vtkGLTFImporter. + * Includes critical texture fixes for proper rendering: + * - Removes metallicRoughnessTexture (causes rendering issues) + * - Sets material to non-metallic for proper texture display + * - Enables two-sided lighting + * + * This loader properly handles textured meshes, unlike simplified implementations. + */ + +/** + * Check if GLTFImporter is available + * @param {Object} vtk - VTK.js global object + * @returns {boolean} + */ +export function isGLTFSupported(vtk) { + try { + return vtk.IO.Geometry.vtkGLTFImporter !== undefined; + } catch { + return false; + } +} + +/** + * Load a GLTF/GLB file with full texture support + * @param {string} filepath - URL to the GLTF/GLB file + * @param {Object} vtk - VTK.js global object + * @param {Object} renderer - VTK renderer (required for GLTF import) + * @param {Object} options - Loading options + * @param {boolean} options.applyTextureFixes - Apply material fixes for proper texture display (default: true) + * @param {boolean} options.twoSidedLighting - Enable two-sided lighting (default: true) + * @returns {Object} Result object with actors and metadata + */ +export async function loadGLTF(filepath, vtk, renderer, options = {}) { + const { + applyTextureFixes = true, + twoSidedLighting = true + } = options; + + const vtkGLTFImporter = vtk.IO.Geometry.vtkGLTFImporter; + + if (!vtkGLTFImporter) { + throw new Error('GLTFImporter not available in this VTK.js version'); + } + + // Enable two-sided lighting for better texture visibility + if (twoSidedLighting && renderer.setTwoSidedLighting) { + renderer.setTwoSidedLighting(true); + } + + const importer = vtkGLTFImporter.newInstance(); + + // CRITICAL: Set renderer FIRST - importActors() needs this + importer.setRenderer(renderer); + + // Set the URL + importer.setUrl(filepath); + + // Wait for GLTF parsing to complete using onReady callback + await new Promise((resolve, reject) => { + importer.onReady(() => { + resolve(); + }); + + // Start loading (this triggers parsing) + importer.loadData().catch(reject); + }); + + // Import actors (creates VTK actors and adds them to renderer) + importer.importActors(); + + // Get actors from the importer (returns Map) + const actorsMap = importer.getActors(); + const actors = Array.from(actorsMap.values()); + + // Track texture and vertex color information + let hasTexture = false; + let hasMaterial = false; + let hasVertexColors = false; + + // Process actors and apply texture fixes + if (applyTextureFixes) { + actors.forEach((actor, index) => { + const mapper = actor.getMapper(); + const property = actor.getProperty(); + const input = mapper?.getInputData(); + + if (input && input.getNumberOfPoints() > 0) { + // Check for vertex colors (may be stored as scalars or as named array COLOR_0) + const pointData = input.getPointData(); + let scalars = pointData?.getScalars(); + + // If no default scalars, check for COLOR_0 array (GLTF standard) + if (!scalars && pointData) { + const numArrays = pointData.getNumberOfArrays(); + for (let i = 0; i < numArrays; i++) { + const arr = pointData.getArray(i); + const name = arr?.getName() || ''; + if (name.toUpperCase().includes('COLOR') && arr.getNumberOfComponents() >= 3) { + scalars = arr; + // Set as active scalars so VTK renders them + pointData.setScalars(arr); + break; + } + } + } + + if (scalars && scalars.getNumberOfComponents() >= 3) { + hasVertexColors = true; + console.log('[GLTFLoader] Found vertex colors:', scalars.getName(), 'components:', scalars.getNumberOfComponents()); + } + + if (property) { + // CRITICAL FIX: Remove metallicRoughnessTexture if present + // VTK.js GLTFImporter may use this instead of baseColorTexture + if (typeof property.setRMTexture === 'function') { + property.setRMTexture(null); + } + if (typeof property.setMetallicRoughnessTexture === 'function') { + property.setMetallicRoughnessTexture(null); + } + + // Try multiple methods to get the base color texture + let texture = null; + if (typeof property.getBaseColorTexture === 'function') { + texture = property.getBaseColorTexture(); + } + if (!texture && typeof property.getDiffuseTexture === 'function') { + texture = property.getDiffuseTexture(); + } + if (!texture && typeof property.getTexture === 'function') { + texture = property.getTexture(); + } + + if (texture) { + hasTexture = true; + actor.addTexture(texture); + } + + // Check for material + if (property.getMetallic !== undefined || property.getRoughness !== undefined) { + hasMaterial = true; + } + + // Set material to non-metallic for proper texture display + if (typeof property.setMetallic === 'function') { + property.setMetallic(0.0); + } + if (typeof property.setRoughness === 'function') { + property.setRoughness(1.0); + } + if (typeof property.setInterpolation === 'function') { + property.setInterpolation(2); // Phong shading + } + } + + // Configure mapper for rendering + if (mapper) { + console.log('[GLTFLoader] Configuring mapper - hasVertexColors:', hasVertexColors, 'hasTexture:', hasTexture); + if (hasVertexColors && !hasTexture) { + // Enable scalar visibility to show vertex colors + console.log('[GLTFLoader] Enabling vertex color rendering'); + mapper.setScalarVisibility(true); + mapper.setScalarModeToUsePointData(); + mapper.setColorModeToDirectScalars(); + + // Set actor color to white so vertex colors show through + if (property) { + console.log('[GLTFLoader] Setting actor color to white'); + property.setColor(1.0, 1.0, 1.0); + // Also set PBR base color factor for GLTF materials + if (typeof property.setBaseColorFactor === 'function') { + console.log('[GLTFLoader] Setting PBR baseColorFactor to white'); + property.setBaseColorFactor([1.0, 1.0, 1.0, 1.0]); + } + // Set diffuse and ambient explicitly + if (typeof property.setDiffuseColor === 'function') { + property.setDiffuseColor(1.0, 1.0, 1.0); + } + if (typeof property.setAmbientColor === 'function') { + property.setAmbientColor(1.0, 1.0, 1.0); + } + if (typeof property.setAmbient === 'function') { + property.setAmbient(0.2); + } + if (typeof property.setDiffuse === 'function') { + property.setDiffuse(0.8); + } + } + } else { + // Disable scalars for texture rendering + mapper.setScalarVisibility(false); + } + mapper.modified(); + } + } + }); + } + + // Calculate combined bounds from all actors + let bounds = null; + if (actors.length > 0) { + bounds = [Infinity, -Infinity, Infinity, -Infinity, Infinity, -Infinity]; + actors.forEach(actor => { + const actorBounds = actor.getBounds(); + bounds[0] = Math.min(bounds[0], actorBounds[0]); + bounds[1] = Math.max(bounds[1], actorBounds[1]); + bounds[2] = Math.min(bounds[2], actorBounds[2]); + bounds[3] = Math.max(bounds[3], actorBounds[3]); + bounds[4] = Math.min(bounds[4], actorBounds[4]); + bounds[5] = Math.max(bounds[5], actorBounds[5]); + }); + } + + // Calculate total points/polys + let totalPoints = 0; + let totalPolys = 0; + actors.forEach(actor => { + const mapper = actor.getMapper(); + const input = mapper?.getInputData(); + if (input) { + totalPoints += input.getNumberOfPoints(); + totalPolys += input.getNumberOfPolys(); + } + }); + + return { + actors, + importer, + bounds, + hasTexture, + hasVertexColors, + metadata: { + format: 'GLTF', + numActors: actors.length, + numPoints: totalPoints, + numPolys: totalPolys, + bounds, + hasTexture, + hasVertexColors, + hasMaterial + } + }; +} + +/** + * Simplified GLTF load for non-textured display (e.g., field visualization) + * Uses parseAsArrayBuffer instead of URL loading for simpler cases + * @param {ArrayBuffer} arrayBuffer - File data as ArrayBuffer + * @param {Object} vtk - VTK.js global object + * @returns {Object} Result object with polyData and metadata + */ +export async function loadGLTFSimple(arrayBuffer, vtk) { + const vtkGLTFImporter = vtk.IO.Geometry.vtkGLTFImporter; + + if (!vtkGLTFImporter) { + throw new Error('GLTFImporter not available'); + } + + const importer = vtkGLTFImporter.newInstance(); + importer.parseAsArrayBuffer(arrayBuffer); + await importer.update(); + + const polyData = importer.getOutputData(); + if (!polyData) { + throw new Error('Failed to extract polydata from GLTF'); + } + + return { + polyData, + importer, + metadata: { + format: 'GLTF', + numPoints: polyData.getNumberOfPoints(), + numPolys: polyData.getNumberOfPolys(), + bounds: polyData.getBounds() + } + }; +} + +/** + * Check if a filepath is a GLTF/GLB file + * @param {string} filepath - File path or URL + * @returns {boolean} + */ +export function canLoadGLTF(filepath) { + const lower = filepath.toLowerCase(); + return lower.includes('.glb') || lower.includes('.gltf'); +} + +export default { + load: loadGLTF, + loadSimple: loadGLTFSimple, + canLoad: canLoadGLTF, + isSupported: isGLTFSupported, + format: 'GLTF' +}; diff --git a/javascript/js/viewer/loaders/LoaderFactory.js b/javascript/js/viewer/loaders/LoaderFactory.js new file mode 100644 index 00000000..4c82d6aa --- /dev/null +++ b/javascript/js/viewer/loaders/LoaderFactory.js @@ -0,0 +1,228 @@ +/** + * LoaderFactory - Auto-detect and load mesh files + * + * Provides a unified interface for loading different mesh formats. + * Automatically detects file type and uses the appropriate loader. + */ + +import { loadSTL, canLoadSTL } from './STLLoader.js'; +import { loadOBJ, canLoadOBJ } from './OBJLoader.js'; +import { loadVTP, canLoadVTP } from './VTPLoader.js'; +import { loadGLTF, loadGLTFSimple, canLoadGLTF, isGLTFSupported } from './GLTFLoader.js'; + +/** + * Supported format types + */ +export const FormatTypes = { + STL: 'STL', + OBJ: 'OBJ', + VTP: 'VTP', + GLTF: 'GLTF', + GLB: 'GLB' +}; + +/** + * Detect file format from filepath + * @param {string} filepath - File path or URL + * @returns {string|null} Format type or null if unknown + */ +export function detectFormat(filepath) { + const lower = filepath.toLowerCase(); + + if (lower.includes('.stl')) return FormatTypes.STL; + if (lower.includes('.obj')) return FormatTypes.OBJ; + if (lower.includes('.vtp')) return FormatTypes.VTP; + if (lower.includes('.glb')) return FormatTypes.GLB; + if (lower.includes('.gltf')) return FormatTypes.GLTF; + + return null; +} + +/** + * Check if a format requires special handling (e.g., GLTF needs renderer) + * @param {string} format - Format type + * @returns {boolean} + */ +export function requiresRenderer(format) { + return format === FormatTypes.GLTF || format === FormatTypes.GLB; +} + +/** + * Check if a format supports textures + * @param {string} format - Format type + * @returns {boolean} + */ +export function supportsTextures(format) { + return format === FormatTypes.GLTF || format === FormatTypes.GLB; +} + +/** + * Check if a format supports scalar fields + * @param {string} format - Format type + * @returns {boolean} + */ +export function supportsFields(format) { + return format === FormatTypes.VTP; +} + +/** + * Fetch file data as ArrayBuffer + * @param {string} filepath - URL to fetch + * @returns {Promise} + */ +async function fetchFile(filepath, onProgress = null) { + const response = await fetch(filepath); + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${response.statusText}`); + } + const total = Number(response.headers.get('Content-Length')) || 0; + // Fall back to a plain (indeterminate) read if we can't stream or size it. + if (!response.body || !total || typeof onProgress !== 'function') { + if (typeof onProgress === 'function') onProgress(null); + return response.arrayBuffer(); + } + const reader = response.body.getReader(); + const chunks = []; + let loaded = 0; + onProgress(0, 0, total); + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + chunks.push(value); + loaded += value.length; + onProgress(Math.min(1, loaded / total), loaded, total); + } + const out = new Uint8Array(loaded); + let offset = 0; + for (const c of chunks) { out.set(c, offset); offset += c.length; } + return out.buffer; +} + +/** + * Load a mesh file with automatic format detection + * @param {string} filepath - URL to the mesh file + * @param {Object} vtk - VTK.js global object + * @param {Object} options - Loading options + * @param {Object} options.renderer - VTK renderer (required for GLTF with textures) + * @param {boolean} options.withTextures - Load GLTF with full texture support (default: true) + * @param {boolean} options.twoSidedLighting - Enable two-sided lighting for GLTF (default: true) + * @returns {Promise} Result object with polyData/actors and metadata + */ +export async function loadMesh(filepath, vtk, options = {}) { + const { + renderer = null, + withTextures = true, + twoSidedLighting = true, + onProgress = null + } = options; + + const format = detectFormat(filepath); + + if (!format) { + throw new Error(`Unsupported file format: ${filepath}`); + } + + console.log(`[LoaderFactory] Loading ${format} file:`, filepath); + + // GLTF/GLB with texture support requires renderer and URL-based loading + // (VTK fetches internally, so we can't byte-track it -> indeterminate). + if ((format === FormatTypes.GLTF || format === FormatTypes.GLB) && withTextures && renderer) { + if (typeof onProgress === 'function') onProgress(null); + return loadGLTF(filepath, vtk, renderer, { + applyTextureFixes: true, + twoSidedLighting + }); + } + + // For all other cases, fetch the file first (with download progress) + const arrayBuffer = await fetchFile(filepath, onProgress); + + switch (format) { + case FormatTypes.STL: + return loadSTL(arrayBuffer, vtk); + + case FormatTypes.OBJ: + return loadOBJ(arrayBuffer, vtk); + + case FormatTypes.VTP: + return loadVTP(arrayBuffer, vtk); + + case FormatTypes.GLTF: + case FormatTypes.GLB: + // Simple GLTF load without texture support + return loadGLTFSimple(arrayBuffer, vtk); + + default: + throw new Error(`No loader available for format: ${format}`); + } +} + +/** + * Load multiple mesh files + * @param {string[]} filepaths - Array of URLs to mesh files + * @param {Object} vtk - VTK.js global object + * @param {Object} options - Loading options (same as loadMesh) + * @returns {Promise} Array of result objects + */ +export async function loadMeshes(filepaths, vtk, options = {}) { + return Promise.all(filepaths.map(fp => loadMesh(fp, vtk, options))); +} + +/** + * Create a loader configuration for a specific format + * Useful for manual loader selection + * @param {string} format - Format type + * @returns {Object} Loader configuration + */ +export function getLoaderConfig(format) { + switch (format) { + case FormatTypes.STL: + return { + load: loadSTL, + canLoad: canLoadSTL, + requiresRenderer: false, + supportsTextures: false, + supportsFields: false + }; + case FormatTypes.OBJ: + return { + load: loadOBJ, + canLoad: canLoadOBJ, + requiresRenderer: false, + supportsTextures: false, + supportsFields: false + }; + case FormatTypes.VTP: + return { + load: loadVTP, + canLoad: canLoadVTP, + requiresRenderer: false, + supportsTextures: false, + supportsFields: true + }; + case FormatTypes.GLTF: + case FormatTypes.GLB: + return { + load: loadGLTF, + loadSimple: loadGLTFSimple, + canLoad: canLoadGLTF, + isSupported: isGLTFSupported, + requiresRenderer: true, + supportsTextures: true, + supportsFields: false + }; + default: + return null; + } +} + +export default { + loadMesh, + loadMeshes, + detectFormat, + requiresRenderer, + supportsTextures, + supportsFields, + getLoaderConfig, + FormatTypes +}; diff --git a/javascript/js/viewer/loaders/OBJLoader.js b/javascript/js/viewer/loaders/OBJLoader.js new file mode 100644 index 00000000..3f388d20 --- /dev/null +++ b/javascript/js/viewer/loaders/OBJLoader.js @@ -0,0 +1,63 @@ +/** + * OBJLoader - OBJ mesh file loader + * + * Loads Wavefront OBJ files using VTK.js vtkOBJReader. + * Includes normals computation for proper shading. + */ + +/** + * Load an OBJ file and return polydata + * @param {ArrayBuffer} arrayBuffer - File data as ArrayBuffer + * @param {Object} vtk - VTK.js global object + * @returns {Object} Result object with polyData and metadata + */ +export async function loadOBJ(arrayBuffer, vtk) { + const vtkOBJReader = vtk.IO.Misc.vtkOBJReader; + const vtkPolyDataNormals = vtk.Filters.Core.vtkPolyDataNormals; + + const reader = vtkOBJReader.newInstance(); + + // OBJ files are text-based + const text = new TextDecoder().decode(arrayBuffer); + reader.parseAsText(text); + + const rawPolyData = reader.getOutputData(); + if (!rawPolyData) { + throw new Error('Failed to parse OBJ data'); + } + + // Apply normals filter for proper shading + const normalsFilter = vtkPolyDataNormals.newInstance(); + normalsFilter.setInputConnection(reader.getOutputPort()); + normalsFilter.update(); + + const polyData = normalsFilter.getOutputData(); + + return { + polyData, + reader, + normalsFilter, + outputPort: normalsFilter.getOutputPort(), + metadata: { + format: 'OBJ', + numPoints: polyData.getNumberOfPoints(), + numPolys: polyData.getNumberOfPolys(), + bounds: polyData.getBounds() + } + }; +} + +/** + * Check if a filepath is an OBJ file + * @param {string} filepath - File path or URL + * @returns {boolean} + */ +export function canLoadOBJ(filepath) { + return filepath.toLowerCase().includes('.obj'); +} + +export default { + load: loadOBJ, + canLoad: canLoadOBJ, + format: 'OBJ' +}; diff --git a/javascript/js/viewer/loaders/STLLoader.js b/javascript/js/viewer/loaders/STLLoader.js new file mode 100644 index 00000000..801341dc --- /dev/null +++ b/javascript/js/viewer/loaders/STLLoader.js @@ -0,0 +1,60 @@ +/** + * STLLoader - STL mesh file loader + * + * Loads binary or ASCII STL files using VTK.js vtkSTLReader. + * Includes normals computation for proper shading. + */ + +/** + * Load an STL file and return polydata + * @param {ArrayBuffer} arrayBuffer - File data as ArrayBuffer + * @param {Object} vtk - VTK.js global object + * @returns {Object} Result object with polyData and metadata + */ +export async function loadSTL(arrayBuffer, vtk) { + const vtkSTLReader = vtk.IO.Geometry.vtkSTLReader; + const vtkPolyDataNormals = vtk.Filters.Core.vtkPolyDataNormals; + + const reader = vtkSTLReader.newInstance(); + reader.parseAsArrayBuffer(arrayBuffer); + + const rawPolyData = reader.getOutputData(); + if (!rawPolyData) { + throw new Error('Failed to parse STL data'); + } + + // Apply normals filter for proper shading + const normalsFilter = vtkPolyDataNormals.newInstance(); + normalsFilter.setInputConnection(reader.getOutputPort()); + normalsFilter.update(); + + const polyData = normalsFilter.getOutputData(); + + return { + polyData, + reader, + normalsFilter, + outputPort: normalsFilter.getOutputPort(), + metadata: { + format: 'STL', + numPoints: polyData.getNumberOfPoints(), + numPolys: polyData.getNumberOfPolys(), + bounds: polyData.getBounds() + } + }; +} + +/** + * Check if a filepath is an STL file + * @param {string} filepath - File path or URL + * @returns {boolean} + */ +export function canLoadSTL(filepath) { + return filepath.toLowerCase().includes('.stl'); +} + +export default { + load: loadSTL, + canLoad: canLoadSTL, + format: 'STL' +}; diff --git a/javascript/js/viewer/loaders/VTPLoader.js b/javascript/js/viewer/loaders/VTPLoader.js new file mode 100644 index 00000000..5f20eaaa --- /dev/null +++ b/javascript/js/viewer/loaders/VTPLoader.js @@ -0,0 +1,116 @@ +/** + * VTPLoader - VTK XML PolyData file loader + * + * Loads VTP files using VTK.js vtkXMLPolyDataReader. + * VTP files can contain scalar fields (vertex/face attributes). + * Includes normals computation for proper shading. + */ + +/** + * Extract field information from polydata + * @param {Object} polyData - VTK polydata object + * @returns {Object} Field information + */ +function extractFieldInfo(polyData) { + const pointData = polyData.getPointData(); + const cellData = polyData.getCellData(); + + const pointFields = []; + const cellFields = []; + + // Extract point (vertex) data arrays + for (let i = 0; i < pointData.getNumberOfArrays(); i++) { + const array = pointData.getArray(i); + const name = array.getName(); + const range = array.getRange(); + pointFields.push({ + name, + type: 'point', + numComponents: array.getNumberOfComponents(), + range: [range[0], range[1]] + }); + } + + // Extract cell (face) data arrays + for (let i = 0; i < cellData.getNumberOfArrays(); i++) { + const array = cellData.getArray(i); + const name = array.getName(); + const range = array.getRange(); + cellFields.push({ + name, + type: 'cell', + numComponents: array.getNumberOfComponents(), + range: [range[0], range[1]] + }); + } + + return { + pointFields, + cellFields, + hasFields: pointFields.length > 0 || cellFields.length > 0 + }; +} + +/** + * Load a VTP file and return polydata + * @param {ArrayBuffer} arrayBuffer - File data as ArrayBuffer + * @param {Object} vtk - VTK.js global object + * @returns {Object} Result object with polyData, fields, and metadata + */ +export async function loadVTP(arrayBuffer, vtk) { + const vtkXMLPolyDataReader = vtk.IO.XML.vtkXMLPolyDataReader; + const vtkPolyDataNormals = vtk.Filters.Core.vtkPolyDataNormals; + + const reader = vtkXMLPolyDataReader.newInstance(); + reader.parseAsArrayBuffer(arrayBuffer); + + const rawPolyData = reader.getOutputData(); + if (!rawPolyData) { + throw new Error('Failed to parse VTP data'); + } + + // Extract field info BEFORE normals filter (preserves original data) + const fieldInfo = extractFieldInfo(rawPolyData); + + // Apply normals filter for proper shading + const normalsFilter = vtkPolyDataNormals.newInstance(); + normalsFilter.setInputConnection(reader.getOutputPort()); + normalsFilter.update(); + + const polyData = normalsFilter.getOutputData(); + + // Extract field info again from filtered data (should be same) + const filteredFieldInfo = extractFieldInfo(polyData); + + return { + polyData, + reader, + normalsFilter, + outputPort: normalsFilter.getOutputPort(), + fields: filteredFieldInfo, + metadata: { + format: 'VTP', + numPoints: polyData.getNumberOfPoints(), + numPolys: polyData.getNumberOfPolys(), + bounds: polyData.getBounds(), + pointFields: filteredFieldInfo.pointFields.map(f => f.name), + cellFields: filteredFieldInfo.cellFields.map(f => f.name), + hasFields: filteredFieldInfo.hasFields + } + }; +} + +/** + * Check if a filepath is a VTP file + * @param {string} filepath - File path or URL + * @returns {boolean} + */ +export function canLoadVTP(filepath) { + return filepath.toLowerCase().includes('.vtp'); +} + +export default { + load: loadVTP, + canLoad: canLoadVTP, + format: 'VTP' +}; diff --git a/javascript/js/viewer/ui/ControlsBar.js b/javascript/js/viewer/ui/ControlsBar.js new file mode 100644 index 00000000..731f9b3e --- /dev/null +++ b/javascript/js/viewer/ui/ControlsBar.js @@ -0,0 +1,398 @@ +/** + * ControlsBar - Configurable controls bar for VTK viewers + * + * Generates and manages the bottom controls bar with camera buttons, + * toggles, selectors, and action buttons. + */ + +/** + * Control types + */ +export const ControlTypes = { + BUTTON: 'button', + CHECKBOX: 'checkbox', + SELECT: 'select', + DIVIDER: 'divider', + LABEL: 'label' +}; + +/** + * Standard control configurations + */ +export const StandardControls = { + settingsButton: { + id: 'settingsButton', + type: ControlTypes.BUTTON, + label: '[Settings]', + title: 'Appearance Settings' + }, + divider: { + type: ControlTypes.DIVIDER + }, + edgesToggle: { + id: 'showEdges', + type: ControlTypes.CHECKBOX, + label: 'Edges' + }, + cameraButtons: { + type: 'camera_group', + buttons: ['+X', '-X', '+Y', '-Y', '+Z', '-Z'] + }, + screenshotButton: { + id: 'screenshot', + type: ControlTypes.BUTTON, + label: 'Screenshot' + }, + saveMeshButton: { + id: 'saveMesh', + type: ControlTypes.BUTTON, + label: 'Save Mesh', + className: 'save-button' + }, + saveGLBButton: { + id: 'saveGLB', + type: ControlTypes.BUTTON, + label: 'Save GLB', + className: 'save-button' + }, + resetCameraButton: { + id: 'resetCamera', + type: ControlTypes.BUTTON, + label: 'Reset Camera' + }, + fieldSelector: { + id: 'fieldSelector', + type: ControlTypes.SELECT, + label: 'Field', + wrapperClass: 'field-label', + hidden: true + }, + colormapSelector: { + id: 'colormapSelector', + type: ControlTypes.SELECT, + label: 'Colormap', + wrapperClass: 'colormap-label', + hidden: true + } +}; + +export class ControlsBar { + /** + * Create a ControlsBar + * @param {Object} options - Configuration options + * @param {HTMLElement} options.container - Container element for the controls bar + * @param {Object} options.handlers - Event handlers keyed by control ID + * @param {Array} options.controls - Array of control configurations + */ + constructor(options = {}) { + this.container = options.container; + this.handlers = options.handlers || {}; + this.controls = options.controls || this._getDefaultControls(); + this.elements = {}; + } + + /** + * Get default controls for standard viewer + * @private + */ + _getDefaultControls() { + return [ + StandardControls.settingsButton, + StandardControls.divider, + StandardControls.edgesToggle, + StandardControls.divider, + StandardControls.cameraButtons, + StandardControls.divider, + StandardControls.fieldSelector, + StandardControls.colormapSelector, + StandardControls.screenshotButton, + StandardControls.saveMeshButton + ]; + } + + /** + * Generate HTML for the controls bar + * @returns {string} HTML string + */ + generateHTML() { + let html = ''; + + this.controls.forEach(control => { + if (!control) return; + + switch (control.type) { + case ControlTypes.BUTTON: + html += this._generateButton(control); + break; + case ControlTypes.CHECKBOX: + html += this._generateCheckbox(control); + break; + case ControlTypes.SELECT: + html += this._generateSelect(control); + break; + case ControlTypes.DIVIDER: + html += ''; + break; + case ControlTypes.LABEL: + html += `${control.text || ''}`; + break; + case 'camera_group': + html += this._generateCameraGroup(control); + break; + default: + if (typeof control.html === 'string') { + html += control.html; + } + } + }); + + return html; + } + + /** + * Generate button HTML + * @private + */ + _generateButton(control) { + const className = control.className || ''; + const style = control.id === 'settingsButton' ? 'width:32px;height:32px;padding:0;font-size:16px;' : ''; + const styleAttr = style ? `style="${style}"` : ''; + const classAttr = className ? `class="${className}"` : ''; + + return ``; + } + + /** + * Generate checkbox HTML + * @private + */ + _generateCheckbox(control) { + const checked = control.checked ? 'checked' : ''; + return ` + + `; + } + + /** + * Generate select HTML + * @private + */ + _generateSelect(control) { + const wrapperClass = control.wrapperClass || ''; + const hiddenStyle = control.hidden ? 'style="display:none;"' : ''; + const options = (control.options || []).map(opt => + `` + ).join(''); + + return ` + + `; + } + + /** + * Generate camera view buttons group + * @private + */ + _generateCameraGroup(control) { + const buttons = control.buttons || ['+X', '-X', '+Y', '-Y', '+Z', '-Z']; + return buttons.map(dir => { + const id = `view${dir.replace('+', 'Pos').replace('-', 'Neg')}`; + return ``; + }).join(''); + } + + /** + * Render the controls bar into the container + */ + render() { + if (!this.container) { + console.warn('[ControlsBar] No container specified'); + return; + } + + this.container.innerHTML = this.generateHTML(); + this._cacheElements(); + this._setupEventListeners(); + } + + /** + * Cache references to control elements + * @private + */ + _cacheElements() { + this.controls.forEach(control => { + if (control && control.id) { + this.elements[control.id] = document.getElementById(control.id); + } + }); + + // Also cache camera buttons + ['viewPosX', 'viewNegX', 'viewPosY', 'viewNegY', 'viewPosZ', 'viewNegZ'].forEach(id => { + const el = document.getElementById(id); + if (el) this.elements[id] = el; + }); + } + + /** + * Setup event listeners based on handlers + * @private + */ + _setupEventListeners() { + // Standard handlers + Object.keys(this.handlers).forEach(id => { + const element = this.elements[id]; + const handler = this.handlers[id]; + + if (element && handler) { + if (element.type === 'checkbox') { + element.addEventListener('change', (e) => handler(e.target.checked, e)); + } else if (element.tagName === 'SELECT') { + element.addEventListener('change', (e) => handler(e.target.value, e)); + } else { + element.addEventListener('click', handler); + } + } + }); + + // Camera buttons (special handling) + if (this.handlers.cameraView) { + const cameraDirections = ['+X', '-X', '+Y', '-Y', '+Z', '-Z']; + cameraDirections.forEach(dir => { + const id = `view${dir.replace('+', 'Pos').replace('-', 'Neg')}`; + const element = this.elements[id]; + if (element) { + element.addEventListener('click', () => this.handlers.cameraView(dir)); + } + }); + } + } + + /** + * Get an element by ID + * @param {string} id - Element ID + * @returns {HTMLElement|null} + */ + getElement(id) { + return this.elements[id] || document.getElementById(id); + } + + /** + * Show a control element + * @param {string} id - Element ID + */ + show(id) { + const wrapper = document.getElementById(`${id}Label`) || this.elements[id]; + if (wrapper) { + wrapper.style.display = 'flex'; + } + } + + /** + * Hide a control element + * @param {string} id - Element ID + */ + hide(id) { + const wrapper = document.getElementById(`${id}Label`) || this.elements[id]; + if (wrapper) { + wrapper.style.display = 'none'; + } + } + + /** + * Enable a control element + * @param {string} id - Element ID + */ + enable(id) { + const element = this.elements[id]; + if (element) { + element.disabled = false; + } + } + + /** + * Disable a control element + * @param {string} id - Element ID + */ + disable(id) { + const element = this.elements[id]; + if (element) { + element.disabled = true; + } + } + + /** + * Set button text + * @param {string} id - Button ID + * @param {string} text - New text + */ + setButtonText(id, text) { + const element = this.elements[id]; + if (element) { + element.textContent = text; + } + } + + /** + * Set button style (e.g., for save button states) + * @param {string} id - Button ID + * @param {Object} style - Style properties + */ + setButtonStyle(id, style) { + const element = this.elements[id]; + if (element) { + Object.assign(element.style, style); + } + } + + /** + * Populate a select element with options + * @param {string} id - Select element ID + * @param {Array} options - Array of {value, label, selected?} objects + * @param {boolean} clearFirst - Whether to clear existing options first + */ + populateSelect(id, options, clearFirst = true) { + const element = this.elements[id] || document.getElementById(id); + if (!element || element.tagName !== 'SELECT') return; + + if (clearFirst) { + element.innerHTML = ''; + } + + options.forEach(opt => { + const option = document.createElement('option'); + option.value = opt.value; + option.textContent = opt.label; + if (opt.selected) option.selected = true; + if (opt.disabled) option.disabled = true; + element.appendChild(option); + }); + } + + /** + * Add a handler for a control + * @param {string} id - Control ID + * @param {Function} handler - Event handler function + */ + addHandler(id, handler) { + this.handlers[id] = handler; + + // If already rendered, attach immediately + const element = this.elements[id]; + if (element) { + if (element.type === 'checkbox') { + element.addEventListener('change', (e) => handler(e.target.checked, e)); + } else if (element.tagName === 'SELECT') { + element.addEventListener('change', (e) => handler(e.target.value, e)); + } else { + element.addEventListener('click', handler); + } + } + } +} + +export default ControlsBar; diff --git a/javascript/js/viewer/ui/SettingsPanel.js b/javascript/js/viewer/ui/SettingsPanel.js new file mode 100644 index 00000000..af39ae18 --- /dev/null +++ b/javascript/js/viewer/ui/SettingsPanel.js @@ -0,0 +1,383 @@ +/** + * SettingsPanel - Configurable settings modal for VTK viewers + * + * Generates and manages a settings panel with configurable fields. + * Different viewers can specify which settings to show. + */ + +/** + * Available setting types + */ +export const SettingTypes = { + NUMBER: 'number', + COLOR: 'color', + SELECT: 'select', + CHECKBOX: 'checkbox' +}; + +/** + * Default settings configuration + */ +const DEFAULT_SETTINGS_CONFIG = [ + { + id: 'pointSize', + label: 'Point Size', + type: SettingTypes.NUMBER, + min: 1, + max: 20, + step: 1, + default: 5 + }, + { + id: 'meshColor', + label: 'Mesh Color', + type: SettingTypes.COLOR, + default: '#ffffff' + }, + { + id: 'edgeWidth', + label: 'Edge Width', + type: SettingTypes.NUMBER, + min: 1, + max: 10, + step: 1, + default: 1 + }, + { + id: 'representation', + label: 'Render Mode', + type: SettingTypes.SELECT, + options: [ + { value: '2', label: 'Surface' }, + { value: '1', label: 'Wireframe' }, + { value: '0', label: 'Points' } + ], + default: '2' + }, + { + id: 'parallelProjection', + label: 'Parallel Projection', + type: SettingTypes.CHECKBOX, + default: false + }, + { + id: 'showAxisIndicator', + label: 'Show Axis Indicator', + type: SettingTypes.CHECKBOX, + default: false + } +]; + +/** + * Colormap range settings (optional, for field visualization) + */ +const COLORMAP_SETTINGS_CONFIG = [ + { + id: 'autoColorRange', + label: 'Auto Range', + type: SettingTypes.CHECKBOX, + default: true, + section: 'Colormap Range' + }, + { + id: 'colormapMin', + label: 'Min', + type: SettingTypes.NUMBER, + step: 'any', + placeholder: 'Auto', + default: '', + section: 'Colormap Range' + }, + { + id: 'colormapMax', + label: 'Max', + type: SettingTypes.NUMBER, + step: 'any', + placeholder: 'Auto', + default: '', + section: 'Colormap Range' + } +]; + +export class SettingsPanel { + /** + * Create a SettingsPanel + * @param {Object} options - Configuration options + * @param {HTMLElement} options.container - Container element for the panel + * @param {Function} options.onApply - Callback when settings are applied + * @param {string[]} options.enabledSettings - Array of setting IDs to show (null = all) + * @param {boolean} options.includeColormapSettings - Whether to include colormap range settings + */ + constructor(options = {}) { + this.container = options.container || document.body; + this.onApply = options.onApply || (() => {}); + this.enabledSettings = options.enabledSettings || null; + this.includeColormapSettings = options.includeColormapSettings || false; + + this.panelElement = null; + this.overlayElement = null; + this.currentValues = {}; + + // Build settings config + this.settingsConfig = this._buildSettingsConfig(); + + // Initialize default values + this.settingsConfig.forEach(setting => { + this.currentValues[setting.id] = setting.default; + }); + } + + /** + * Build the settings configuration based on enabled settings + * @private + */ + _buildSettingsConfig() { + let config = [...DEFAULT_SETTINGS_CONFIG]; + + if (this.includeColormapSettings) { + config = config.concat(COLORMAP_SETTINGS_CONFIG); + } + + if (this.enabledSettings) { + config = config.filter(s => this.enabledSettings.includes(s.id)); + } + + return config; + } + + /** + * Generate the HTML for the settings panel + * @returns {string} HTML string + */ + generateHTML() { + let currentSection = null; + let html = ` +
+
+

Appearance Settings

+ `; + + this.settingsConfig.forEach(setting => { + // Add section header if needed + if (setting.section && setting.section !== currentSection) { + currentSection = setting.section; + html += ` +
+ +
+ `; + } + + html += this._generateSettingRow(setting); + }); + + html += ` +
+ + +
+
+ `; + + return html; + } + + /** + * Generate HTML for a single setting row + * @private + */ + _generateSettingRow(setting) { + let inputHtml = ''; + + switch (setting.type) { + case SettingTypes.NUMBER: + inputHtml = ` + + `; + break; + + case SettingTypes.COLOR: + inputHtml = ``; + break; + + case SettingTypes.SELECT: + inputHtml = `'; + break; + + case SettingTypes.CHECKBOX: + const checked = setting.default ? 'checked' : ''; + return ` +
+ +
+ `; + } + + return ` +
+ + ${inputHtml} +
+ `; + } + + /** + * Render the panel into the container + */ + render() { + // Create wrapper if needed + const wrapper = document.createElement('div'); + wrapper.innerHTML = this.generateHTML(); + + // Find or create panel elements in container + this.overlayElement = wrapper.querySelector('#settingsOverlay'); + this.panelElement = wrapper.querySelector('#settingsPanel'); + + // Append to container + this.container.appendChild(this.overlayElement); + this.container.appendChild(this.panelElement); + + // Setup event listeners + this._setupEventListeners(); + } + + /** + * Attach to existing panel elements in the DOM + * @param {HTMLElement} panel - The settings panel element + * @param {HTMLElement} overlay - The overlay element + */ + attachToExisting(panel, overlay) { + this.panelElement = panel; + this.overlayElement = overlay; + this._setupEventListeners(); + } + + /** + * Setup event listeners + * @private + */ + _setupEventListeners() { + // Apply button + const applyBtn = this.panelElement.querySelector('#applySettings'); + if (applyBtn) { + applyBtn.addEventListener('click', () => this._handleApply()); + } + + // Cancel button + const cancelBtn = this.panelElement.querySelector('#cancelSettings'); + if (cancelBtn) { + cancelBtn.addEventListener('click', () => this.close()); + } + + // Overlay click + if (this.overlayElement) { + this.overlayElement.addEventListener('click', () => this.close()); + } + } + + /** + * Handle apply button click + * @private + */ + _handleApply() { + const values = this.getValues(); + this.currentValues = { ...values }; + this.onApply(values); + this.close(); + } + + /** + * Open the settings panel + */ + open() { + // Update inputs with current values + this.setValues(this.currentValues); + + if (this.panelElement) { + this.panelElement.classList.add('visible'); + } + if (this.overlayElement) { + this.overlayElement.classList.add('visible'); + } + } + + /** + * Close the settings panel + */ + close() { + if (this.panelElement) { + this.panelElement.classList.remove('visible'); + } + if (this.overlayElement) { + this.overlayElement.classList.remove('visible'); + } + } + + /** + * Get current values from all inputs + * @returns {Object} Object with setting id -> value pairs + */ + getValues() { + const values = {}; + + this.settingsConfig.forEach(setting => { + const element = document.getElementById(setting.id); + if (!element) return; + + if (setting.type === SettingTypes.CHECKBOX) { + values[setting.id] = element.checked; + } else { + values[setting.id] = element.value; + } + }); + + return values; + } + + /** + * Set values on all inputs + * @param {Object} values - Object with setting id -> value pairs + */ + setValues(values) { + this.settingsConfig.forEach(setting => { + const element = document.getElementById(setting.id); + if (!element || values[setting.id] === undefined) return; + + if (setting.type === SettingTypes.CHECKBOX) { + element.checked = values[setting.id]; + } else { + element.value = values[setting.id]; + } + }); + } + + /** + * Update stored current values + * @param {Object} values - Partial values to update + */ + updateCurrentValues(values) { + this.currentValues = { ...this.currentValues, ...values }; + } + + /** + * Get current stored values + * @returns {Object} Current values + */ + getCurrentValues() { + return { ...this.currentValues }; + } +} + +export default SettingsPanel; diff --git a/javascript/js/viewer/ui/styles.css b/javascript/js/viewer/ui/styles.css new file mode 100644 index 00000000..4440c292 --- /dev/null +++ b/javascript/js/viewer/ui/styles.css @@ -0,0 +1,366 @@ +/** + * Shared styles for all VTK viewers + * Single source of truth - changes here affect all viewers + */ + +/* ========== Base Layout ========== */ +body { + margin: 0; + overflow: hidden; + background: #2a2a2a; + font-family: monospace; + display: flex; + flex-direction: column; + height: 100vh; +} + +#viewerContainer { + flex: 1; + position: relative; + min-height: 0; +} + +#container { + width: 100%; + height: 100%; + position: relative; +} + +/* ========== Loading Overlay ========== */ +#loading { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + color: white; + font-size: 14px; + text-align: center; + z-index: 1000; + pointer-events: none; +} + +/* ========== Controls Bar ========== */ +#controls { + background: #1a1a1a; + border-top: 1px solid #444; + padding: 8px 12px; + display: flex; + gap: 12px; + align-items: center; + flex-wrap: wrap; + font-size: 12px; + color: #ccc; +} + +#controls label { + display: flex; + align-items: center; + gap: 4px; +} + +#controls select, +#controls button { + background: #333; + color: #ccc; + border: 1px solid #555; + padding: 4px 8px; + border-radius: 3px; + font-size: 12px; + font-family: monospace; +} + +#controls button { + cursor: pointer; +} + +#controls button:hover { + background: #444; +} + +#controls button:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +#controls input[type="checkbox"] { + cursor: pointer; +} + +/* Divider between control groups */ +.controls-divider { + width: 1px; + height: 20px; + background: #444; + margin: 0 8px; +} + +/* ========== Settings Panel ========== */ +#settingsPanel { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + background: #1a1a1a; + border: 1px solid #555; + border-radius: 6px; + padding: 16px; + z-index: 2000; + display: none; + min-width: 280px; + max-height: 80%; + overflow-y: auto; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5); +} + +#settingsPanel.visible { + display: block; +} + +#settingsPanel h3 { + margin: 0 0 12px 0; + color: #ccc; + font-size: 14px; + font-weight: normal; + border-bottom: 1px solid #333; + padding-bottom: 8px; +} + +#settingsPanel .setting-row { + display: flex; + align-items: center; + gap: 12px; + margin-bottom: 12px; +} + +#settingsPanel .setting-row label { + flex: 0 0 100px; + color: #ccc; + font-size: 12px; +} + +#settingsPanel .setting-row input[type="color"] { + flex: 1; + height: 32px; + border: 1px solid #555; + background: #333; + cursor: pointer; +} + +#settingsPanel .setting-row input[type="number"] { + flex: 1; + background: #333; + color: #ccc; + border: 1px solid #555; + padding: 6px 8px; + border-radius: 3px; + font-size: 12px; + font-family: monospace; +} + +#settingsPanel .setting-row select { + flex: 1; + background: #333; + color: #ccc; + border: 1px solid #555; + padding: 6px 8px; + border-radius: 3px; + font-size: 12px; + font-family: monospace; +} + +#settingsPanel .setting-row input[type="checkbox"] { + cursor: pointer; +} + +#settingsPanel .setting-section { + margin-top: 12px; + padding-top: 12px; + border-top: 1px solid #444; +} + +#settingsPanel .setting-section-label { + font-weight: bold; + color: #aaa; + margin-bottom: 8px; +} + +#settingsPanel .button-row { + display: flex; + gap: 8px; + margin-top: 16px; + padding-top: 12px; + border-top: 1px solid #333; +} + +#settingsPanel .button-row button { + flex: 1; + padding: 6px 12px; + font-size: 12px; + background: #333; + color: #ccc; + border: 1px solid #555; + border-radius: 3px; + cursor: pointer; +} + +#settingsPanel .button-row button:hover { + background: #444; +} + +/* Settings overlay (dark backdrop) */ +#settingsOverlay { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + background: rgba(0, 0, 0, 0.5); + z-index: 1999; + display: none; +} + +#settingsOverlay.visible { + display: block; +} + +/* Settings button (gear icon) */ +#settingsButton { + background: #333; + width: 32px; + height: 32px; + padding: 0; + display: flex; + align-items: center; + justify-content: center; + font-size: 16px; +} + +/* ========== Info Panel (for textured viewer) ========== */ +#infoPanel { + position: absolute; + top: 10px; + left: 10px; + background: rgba(26, 26, 26, 0.9); + border: 1px solid #444; + border-radius: 4px; + padding: 8px 12px; + font-size: 11px; + color: #ccc; + z-index: 100; + display: none; +} + +#infoPanel.visible { + display: block; +} + +#infoPanel .info-row { + display: flex; + gap: 8px; + margin-bottom: 4px; +} + +#infoPanel .info-row:last-child { + margin-bottom: 0; +} + +#infoPanel .info-label { + color: #888; +} + +#infoPanel .info-value { + color: #4a9eff; +} + +#infoPanel .info-value.warning { + color: #ffaa00; +} + +#infoPanel .info-value.error { + color: #ff6b6b; +} + +#infoPanel .info-value.success { + color: #6bff6b; +} + +/* ========== Dual Viewer Specific ========== */ +.viewer-dual #viewerContainer { + display: flex; +} + +.viewer-dual .viewport-container { + flex: 1; + position: relative; + min-width: 0; +} + +.viewer-dual .viewport-label { + position: absolute; + top: 8px; + left: 8px; + background: rgba(0, 0, 0, 0.6); + color: #ccc; + padding: 4px 8px; + border-radius: 3px; + font-size: 11px; + z-index: 100; +} + +.viewer-dual #sideBySideContainer { + display: none; + width: 100%; + height: 100%; + gap: 2px; +} + +.viewer-dual #sideBySideContainer.active { + display: flex; +} + +.viewer-dual #overlayContainer { + display: none; + width: 100%; + height: 100%; +} + +.viewer-dual #overlayContainer.active { + display: block; +} + +/* Field controls for dual viewer */ +.field-controls { + display: none; +} + +.field-controls.active { + display: flex; + align-items: center; + gap: 8px; +} + +/* ========== Save Button Variants ========== */ +#saveMesh, +#saveGLB { + background: #2a5a2a; +} + +#saveMesh:hover, +#saveGLB:hover { + background: #3a6a3a; +} + +/* ========== Utility Classes ========== */ +.hidden { + display: none !important; +} + +.flex { + display: flex; +} + +.flex-center { + display: flex; + align-items: center; + justify-content: center; +} diff --git a/javascript/js/viewer/utils/BoundsUtils.js b/javascript/js/viewer/utils/BoundsUtils.js new file mode 100644 index 00000000..0236ea1f --- /dev/null +++ b/javascript/js/viewer/utils/BoundsUtils.js @@ -0,0 +1,94 @@ +/** + * Bounds calculation utilities for VTK viewers + */ + +/** + * Get the center point of bounds + * @param {number[]} bounds - VTK bounds array [xmin, xmax, ymin, ymax, zmin, zmax] + * @returns {number[]} Center point [x, y, z] + */ +export function getCenter(bounds) { + return [ + (bounds[0] + bounds[1]) / 2, + (bounds[2] + bounds[3]) / 2, + (bounds[4] + bounds[5]) / 2 + ]; +} + +/** + * Get the maximum dimension of bounds + * @param {number[]} bounds - VTK bounds array [xmin, xmax, ymin, ymax, zmin, zmax] + * @returns {number} Maximum dimension + */ +export function getMaxDimension(bounds) { + return Math.max( + bounds[1] - bounds[0], + bounds[3] - bounds[2], + bounds[5] - bounds[4] + ); +} + +/** + * Get all three dimensions of bounds + * @param {number[]} bounds - VTK bounds array [xmin, xmax, ymin, ymax, zmin, zmax] + * @returns {number[]} Dimensions [width, height, depth] + */ +export function getDimensions(bounds) { + return [ + bounds[1] - bounds[0], + bounds[3] - bounds[2], + bounds[5] - bounds[4] + ]; +} + +/** + * Combine multiple bounds into a single bounding box + * @param {number[][]} boundsArray - Array of VTK bounds + * @returns {number[]} Combined bounds [xmin, xmax, ymin, ymax, zmin, zmax] + */ +export function combineBounds(boundsArray) { + if (!boundsArray || boundsArray.length === 0) { + return [0, 0, 0, 0, 0, 0]; + } + + const combined = [...boundsArray[0]]; + + for (let i = 1; i < boundsArray.length; i++) { + const b = boundsArray[i]; + combined[0] = Math.min(combined[0], b[0]); // xmin + combined[1] = Math.max(combined[1], b[1]); // xmax + combined[2] = Math.min(combined[2], b[2]); // ymin + combined[3] = Math.max(combined[3], b[3]); // ymax + combined[4] = Math.min(combined[4], b[4]); // zmin + combined[5] = Math.max(combined[5], b[5]); // zmax + } + + return combined; +} + +/** + * Check if bounds are valid (non-empty) + * @param {number[]} bounds - VTK bounds array + * @returns {boolean} True if bounds are valid + */ +export function isValidBounds(bounds) { + if (!bounds || bounds.length !== 6) return false; + + // Check for NaN or Infinity + for (const val of bounds) { + if (!Number.isFinite(val)) return false; + } + + // Check that max >= min for all dimensions + return bounds[1] >= bounds[0] && + bounds[3] >= bounds[2] && + bounds[5] >= bounds[4]; +} + +export default { + getCenter, + getMaxDimension, + getDimensions, + combineBounds, + isValidBounds +}; diff --git a/javascript/js/viewer/utils/ColorUtils.js b/javascript/js/viewer/utils/ColorUtils.js new file mode 100644 index 00000000..1e2debdc --- /dev/null +++ b/javascript/js/viewer/utils/ColorUtils.js @@ -0,0 +1,59 @@ +/** + * Color utility functions for VTK viewers + */ + +/** + * Convert RGB values (0-1 range) to CSS rgb() string + * @param {number} r - Red component (0-1) + * @param {number} g - Green component (0-1) + * @param {number} b - Blue component (0-1) + * @returns {string} CSS rgb string like "rgb(255, 128, 0)" + */ +export function rgbToString(r, g, b) { + const r255 = Math.round(r * 255); + const g255 = Math.round(g * 255); + const b255 = Math.round(b * 255); + return `rgb(${r255}, ${g255}, ${b255})`; +} + +/** + * Convert hex color string to RGB array (0-1 range) + * @param {string} hex - Hex color like "#ffffff" or "#fff" + * @returns {number[]} RGB array [r, g, b] with values 0-1 + */ +export function hexToRgb(hex) { + // Remove # if present + hex = hex.replace(/^#/, ''); + + // Handle shorthand hex (#fff -> #ffffff) + if (hex.length === 3) { + hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; + } + + const r = parseInt(hex.substr(0, 2), 16) / 255; + const g = parseInt(hex.substr(2, 2), 16) / 255; + const b = parseInt(hex.substr(4, 2), 16) / 255; + + return [r, g, b]; +} + +/** + * Convert RGB array (0-1 range) to hex color string + * @param {number} r - Red component (0-1) + * @param {number} g - Green component (0-1) + * @param {number} b - Blue component (0-1) + * @returns {string} Hex color like "#ffffff" + */ +export function rgbToHex(r, g, b) { + const toHex = (c) => { + const hex = Math.round(c * 255).toString(16); + return hex.length === 1 ? '0' + hex : hex; + }; + return '#' + toHex(r) + toHex(g) + toHex(b); +} + +export default { + rgbToString, + hexToRgb, + rgbToHex +}; diff --git a/javascript/js/viewer/utils/MessageHandler.js b/javascript/js/viewer/utils/MessageHandler.js new file mode 100644 index 00000000..4e2de8cb --- /dev/null +++ b/javascript/js/viewer/utils/MessageHandler.js @@ -0,0 +1,100 @@ +/** + * PostMessage communication utilities for VTK viewers + */ + +/** + * Message types used by the viewer system + */ +export const MessageTypes = { + // Incoming messages (from parent) + LOAD_MESH: 'LOAD_MESH', + LOAD_DUAL_MESH: 'LOAD_DUAL_MESH', + + // Outgoing messages (to parent) + MESH_LOADED: 'MESH_LOADED', + MESH_ERROR: 'MESH_ERROR', + SCREENSHOT: 'SCREENSHOT' +}; + +/** + * Send a message to the parent window + * @param {string} type - Message type + * @param {Object} data - Additional data to send + */ +export function sendToParent(type, data = {}) { + if (window.parent && window.parent !== window) { + window.parent.postMessage({ + type, + ...data + }, '*'); + } +} + +/** + * Send an error message to the parent window + * @param {string|Error} error - Error message or Error object + */ +export function sendError(error) { + const message = error instanceof Error ? error.message : error; + sendToParent(MessageTypes.MESH_ERROR, { error: message }); +} + +/** + * Send a screenshot to the parent window + * @param {string} imageDataUrl - Base64 PNG data URL + */ +export function sendScreenshot(imageDataUrl) { + sendToParent(MessageTypes.SCREENSHOT, { + image: imageDataUrl, + timestamp: Date.now() + }); +} + +/** + * Send mesh loaded confirmation to parent + */ +export function sendMeshLoaded() { + sendToParent(MessageTypes.MESH_LOADED, { error: null }); +} + +/** + * Create a message listener for the viewer + * @param {Object} handlers - Object mapping message types to handler functions + * @returns {Function} Cleanup function to remove the listener + */ +export function createMessageListener(handlers) { + const listener = (event) => { + const { type } = event.data || {}; + + if (type && handlers[type]) { + handlers[type](event.data); + } + }; + + window.addEventListener('message', listener); + + // Return cleanup function + return () => { + window.removeEventListener('message', listener); + }; +} + +/** + * Extract filename from a filepath URL + * @param {string} filepath - URL or path to extract filename from + * @returns {string} Extracted filename + */ +export function extractFilename(filepath) { + const urlParams = new URLSearchParams(filepath.split('?')[1] || ''); + return urlParams.get('filename') || filepath.split('/').pop().split('?')[0]; +} + +export default { + MessageTypes, + sendToParent, + sendError, + sendScreenshot, + sendMeshLoaded, + createMessageListener, + extractFilename +}; diff --git a/javascript/js/viewer/viewers/DualViewer.js b/javascript/js/viewer/viewers/DualViewer.js new file mode 100644 index 00000000..8eee2d94 --- /dev/null +++ b/javascript/js/viewer/viewers/DualViewer.js @@ -0,0 +1,551 @@ +/** + * DualViewer - VTK viewer for dual mesh comparison + * + * Supports side-by-side and overlay layouts with: + * - Camera synchronization between viewports + * - Synchronized scalar field ranges + * - Multiple layout modes (side-by-side, overlay, split) + * - Independent and linked settings + */ + +import { CameraController } from '../core/CameraController.js'; +import { ActorManager } from '../core/ActorManager.js'; +import { loadMesh, supportsTextures } from '../loaders/LoaderFactory.js'; +import { FieldVisualization } from '../features/FieldVisualization.js'; +import { TextureManager } from '../features/TextureManager.js'; +import { ScreenshotCapture } from '../features/ScreenshotCapture.js'; +import { sendMeshLoaded, sendError, createMessageListener, extractFilename } from '../utils/MessageHandler.js'; +import { combineBounds, isValidBounds } from '../utils/BoundsUtils.js'; + +/** + * Layout modes for dual viewer + */ +export const LayoutMode = { + SIDE_BY_SIDE: 'side-by-side', + OVERLAY: 'overlay', + VERTICAL: 'vertical' +}; + +/** + * Dual viewer configuration + */ +const DUAL_CONFIG = { + // Camera + cameraDistanceMultiplier: 2.5, + + // Layout + layout: LayoutMode.SIDE_BY_SIDE, + + // Sync options + syncCameras: true, + syncFields: true, + + // Appearance + backgroundColor: [0.15, 0.15, 0.15], + defaultMeshColorA: [0.6, 0.8, 1.0], + defaultMeshColorB: [0.6, 0.8, 1.0], + showEdges: false, + + // Features + enableFields: true, + enableTextures: true +}; + +export class DualViewer { + /** + * Create a DualViewer + * @param {HTMLElement} containerA - Container for first viewport + * @param {HTMLElement} containerB - Container for second viewport + * @param {Object} config - Configuration options + */ + constructor(containerA, containerB, config = {}) { + this.containerA = containerA; + this.containerB = containerB; + this.config = { ...DUAL_CONFIG, ...config }; + + // VTK objects + this.vtk = null; + + // Viewports (each has its own renderer, render window, etc.) + this.viewportA = null; + this.viewportB = null; + + // Feature modules (shared) + this.actorManager = null; + this.fieldVisualization = null; + + // State + this.layout = this.config.layout; + this.syncCameras = this.config.syncCameras; + this.syncFields = this.config.syncFields; + this.isInitialized = false; + + // Camera sync state + this._cameraObserver = null; + this._isUpdatingCamera = false; + + // Message listener cleanup + this._messageCleanup = null; + } + + /** + * Initialize the dual viewer + */ + async initialize() { + if (this.isInitialized) return; + + this.vtk = window.vtk; + if (!this.vtk) { + throw new Error('VTK.js not loaded'); + } + + // Create both viewports + this.viewportA = this._createViewport(this.containerA, 'A'); + this.viewportB = this._createViewport(this.containerB, 'B'); + + // Initialize shared modules + this.actorManager = new ActorManager(this.vtk, { + defaultColor: this.config.defaultMeshColorA + }); + this.fieldVisualization = new FieldVisualization(this.vtk, this.viewportA.renderWindow); + + // Setup camera sync if enabled + if (this.syncCameras) { + this._setupCameraSync(); + } + + // Setup resize handlers + this._setupResizeHandlers(); + + // Setup message listener + this._setupMessageListener(); + + this.isInitialized = true; + console.log('[DualViewer] Initialized'); + } + + /** + * Create a viewport + * @private + * @param {HTMLElement} container + * @param {string} id + * @returns {Object} + */ + _createViewport(container, id) { + const renderWindow = this.vtk.Rendering.Core.vtkRenderWindow.newInstance(); + const renderer = this.vtk.Rendering.Core.vtkRenderer.newInstance(); + renderer.setBackground(...this.config.backgroundColor); + renderWindow.addRenderer(renderer); + + const openGLRenderWindow = this.vtk.Rendering.OpenGL.vtkRenderWindow.newInstance(); + openGLRenderWindow.setContainer(container); + renderWindow.addView(openGLRenderWindow); + + const interactor = this.vtk.Rendering.Core.vtkRenderWindowInteractor.newInstance(); + interactor.setView(openGLRenderWindow); + interactor.initialize(); + interactor.bindEvents(container); + + const interactorStyle = this.vtk.Interaction.Style.vtkInteractorStyleTrackballCamera.newInstance(); + interactor.setInteractorStyle(interactorStyle); + + const { width, height } = container.getBoundingClientRect(); + openGLRenderWindow.setSize(width, height); + + const cameraController = new CameraController(renderer, { + distanceMultiplier: this.config.cameraDistanceMultiplier + }); + + // Create texture manager for this viewport + const textureManager = new TextureManager(this.vtk, renderWindow); + + return { + id, + container, + renderWindow, + renderer, + openGLRenderWindow, + interactor, + interactorStyle, + cameraController, + textureManager, + actors: [], + polyData: null, + filename: null + }; + } + + /** + * Setup camera synchronization between viewports + * @private + */ + _setupCameraSync() { + const syncCamera = (sourceViewport, targetViewport) => { + if (this._isUpdatingCamera) return; + this._isUpdatingCamera = true; + + const sourceCamera = sourceViewport.renderer.getActiveCamera(); + const targetCamera = targetViewport.renderer.getActiveCamera(); + + targetCamera.setPosition(...sourceCamera.getPosition()); + targetCamera.setFocalPoint(...sourceCamera.getFocalPoint()); + targetCamera.setViewUp(...sourceCamera.getViewUp()); + targetCamera.setParallelScale(sourceCamera.getParallelScale()); + + targetViewport.renderWindow.render(); + this._isUpdatingCamera = false; + }; + + // Subscribe to camera modified events + const cameraA = this.viewportA.renderer.getActiveCamera(); + const cameraB = this.viewportB.renderer.getActiveCamera(); + + cameraA.onModified(() => { + if (this.syncCameras) { + syncCamera(this.viewportA, this.viewportB); + } + }); + + cameraB.onModified(() => { + if (this.syncCameras) { + syncCamera(this.viewportB, this.viewportA); + } + }); + } + + /** + * Setup resize handlers for both viewports + * @private + */ + _setupResizeHandlers() { + const handleResize = (viewport) => { + const { width, height } = viewport.container.getBoundingClientRect(); + if (width > 0 && height > 0) { + viewport.openGLRenderWindow.setSize(width, height); + viewport.renderWindow.render(); + } + }; + + this._resizeObserverA = new ResizeObserver(() => handleResize(this.viewportA)); + this._resizeObserverB = new ResizeObserver(() => handleResize(this.viewportB)); + + this._resizeObserverA.observe(this.viewportA.container); + this._resizeObserverB.observe(this.viewportB.container); + } + + /** + * Setup message listener + * @private + */ + _setupMessageListener() { + this._messageCleanup = createMessageListener((data) => { + switch (data.type) { + case 'loadMeshA': + this.loadMesh('A', data.url); + break; + case 'loadMeshB': + this.loadMesh('B', data.url); + break; + case 'loadMesh': + // Load to both or specified viewport + if (data.viewport) { + this.loadMesh(data.viewport, data.url); + } else { + this.loadMesh('A', data.url); + } + break; + case 'setLayout': + this.setLayout(data.layout); + break; + case 'setCameraSync': + this.setCameraSync(data.enabled); + break; + case 'setField': + this.applyField(data.field, data.options); + break; + case 'screenshot': + this.captureScreenshot(); + break; + } + }); + } + + /** + * Load mesh into a viewport + * @param {string} viewport - 'A' or 'B' + * @param {string} url - Mesh URL + * @returns {Promise} + */ + async loadMesh(viewport, url) { + const vp = viewport === 'A' ? this.viewportA : this.viewportB; + const defaultColor = viewport === 'A' + ? this.config.defaultMeshColorA + : this.config.defaultMeshColorB; + + try { + // Clear existing actors + vp.actors.forEach(actor => vp.renderer.removeActor(actor)); + vp.actors = []; + + // Load mesh + const result = await loadMesh(url, this.vtk, { + renderer: vp.renderer + }); + + vp.actors = result.actors; + vp.polyData = result.polyData; + vp.filename = extractFilename(url); + + // Add actors to renderer + result.actors.forEach(actor => { + vp.renderer.addActor(actor); + }); + + // Configure actors based on format + if (result.hasTexture && this.config.enableTextures) { + // Apply texture fixes for GLTF/GLB + vp.textureManager.applyTextureFixesMultiple(result.actors); + vp.textureManager.configureRenderer(vp.renderer); + } else if (result.hasVertexColors) { + // Mesh has vertex colors - don't override with default color + // Just configure edges if needed, colors are already set up by loader + result.actors.forEach(actor => { + const property = actor.getProperty(); + if (property && this.config.showEdges) { + property.setEdgeVisibility(true); + } + }); + } else { + // Standard actor configuration - apply default color + this.actorManager.configureActors(result.actors, { + color: defaultColor, + showEdges: this.config.showEdges + }); + } + + // Position camera + this._positionCameraForViewport(vp); + + // Render + vp.renderWindow.render(); + + // Notify parent + sendMeshLoaded({ + viewport, + filename: vp.filename, + format: result.format, + hasTexture: result.hasTexture || false, + hasVertexColors: result.hasVertexColors || false + }); + + return result; + + } catch (error) { + console.error(`[DualViewer] Error loading mesh ${viewport}:`, error); + sendError(`Failed to load mesh ${viewport}: ${error.message}`); + throw error; + } + } + + /** + * Position camera for a viewport + * @private + */ + _positionCameraForViewport(viewport) { + if (viewport.actors.length === 0) return; + + let bounds = viewport.actors[0].getBounds(); + for (let i = 1; i < viewport.actors.length; i++) { + bounds = combineBounds(bounds, viewport.actors[i].getBounds()); + } + + if (isValidBounds(bounds)) { + viewport.cameraController.positionInitialCamera(bounds); + } + } + + /** + * Apply field visualization to both viewports + * @param {string} fieldName - Field name + * @param {Object} options - Options including colormap, range + */ + applyField(fieldName, options = {}) { + if (!this.config.enableFields) return; + + // Calculate synchronized range if enabled + let range = options.range; + if (this.syncFields && !range) { + const polydatas = [ + this.viewportA.polyData, + this.viewportB.polyData + ].filter(Boolean); + + if (polydatas.length > 0) { + range = this.fieldVisualization.calculateSynchronizedRange(polydatas, fieldName); + } + } + + // Apply to viewport A + if (this.viewportA.polyData && this.viewportA.actors.length > 0) { + const mapperA = this.viewportA.actors[0].getMapper(); + this.fieldVisualization.applyField(mapperA, this.viewportA.polyData, fieldName, { + ...options, + range, + render: false + }); + } + + // Apply to viewport B + if (this.viewportB.polyData && this.viewportB.actors.length > 0) { + const mapperB = this.viewportB.actors[0].getMapper(); + // Need a separate FieldVisualization for viewport B's render window + const fieldVizB = new FieldVisualization(this.vtk, this.viewportB.renderWindow); + fieldVizB.applyField(mapperB, this.viewportB.polyData, fieldName, { + ...options, + range, + render: false + }); + } + + // Render both + this.render(); + } + + /** + * Set layout mode + * @param {string} layout - LayoutMode value + */ + setLayout(layout) { + this.layout = layout; + // Layout changes are handled by CSS classes on the containers + // This method just updates the state; the parent should update CSS + console.log(`[DualViewer] Layout set to: ${layout}`); + } + + /** + * Set camera sync enabled + * @param {boolean} enabled + */ + setCameraSync(enabled) { + this.syncCameras = enabled; + console.log(`[DualViewer] Camera sync: ${enabled}`); + } + + /** + * Set field range sync enabled + * @param {boolean} enabled + */ + setFieldSync(enabled) { + this.syncFields = enabled; + } + + /** + * Set camera view for both viewports + * @param {string} direction - '+X', '-X', etc. + */ + setCameraView(direction) { + // Get combined bounds from both viewports + const allActors = [...this.viewportA.actors, ...this.viewportB.actors]; + if (allActors.length === 0) return; + + let bounds = allActors[0].getBounds(); + for (let i = 1; i < allActors.length; i++) { + bounds = combineBounds(bounds, allActors[i].getBounds()); + } + + // Apply to viewport A (will sync to B if enabled) + this.viewportA.cameraController.setCameraView(direction, bounds); + + // If sync is disabled, also update B + if (!this.syncCameras) { + this.viewportB.cameraController.setCameraView(direction, bounds); + } + + this.render(); + } + + /** + * Capture screenshot of both viewports + * @returns {Promise} + */ + async captureScreenshot() { + const screenshotA = new ScreenshotCapture(this.viewportA.renderWindow); + const screenshotB = new ScreenshotCapture(this.viewportB.renderWindow); + + const [imageA, imageB] = await Promise.all([ + screenshotA.capture(), + screenshotB.capture() + ]); + + // Send combined screenshot info + window.parent?.postMessage({ + type: 'screenshot', + data: { + viewportA: imageA, + viewportB: imageB + } + }, '*'); + + return { viewportA: imageA, viewportB: imageB }; + } + + /** + * Render both viewports + */ + render() { + this.viewportA.renderWindow.render(); + this.viewportB.renderWindow.render(); + } + + /** + * Get viewport + * @param {string} id - 'A' or 'B' + * @returns {Object} + */ + getViewport(id) { + return id === 'A' ? this.viewportA : this.viewportB; + } + + /** + * Cleanup and destroy + */ + destroy() { + if (this._messageCleanup) { + this._messageCleanup(); + } + + if (this._resizeObserverA) { + this._resizeObserverA.disconnect(); + } + if (this._resizeObserverB) { + this._resizeObserverB.disconnect(); + } + + // Destroy viewports + [this.viewportA, this.viewportB].forEach(vp => { + if (!vp) return; + vp.actors.forEach(actor => vp.renderer.removeActor(actor)); + vp.interactor.unbindEvents(); + vp.openGLRenderWindow.delete(); + vp.renderWindow.delete(); + }); + + console.log('[DualViewer] Destroyed'); + } +} + +/** + * Create a DualViewer instance + * @param {HTMLElement} containerA + * @param {HTMLElement} containerB + * @param {Object} config + * @returns {DualViewer} + */ +export function createDualViewer(containerA, containerB, config = {}) { + const viewer = new DualViewer(containerA, containerB, config); + viewer.initialize(); + return viewer; +} + +export { LayoutMode as DualLayoutMode }; +export default DualViewer; diff --git a/javascript/js/viewer/viewers/StandardViewer.js b/javascript/js/viewer/viewers/StandardViewer.js new file mode 100644 index 00000000..b8df80a2 --- /dev/null +++ b/javascript/js/viewer/viewers/StandardViewer.js @@ -0,0 +1,241 @@ +/** + * StandardViewer - VTK viewer for standard mesh preview + * + * Supports STL, OBJ, VTP formats with: + * - Scalar field visualization + * - Colormap selection + * - Settings panel (color, edges, lighting) + * - Screenshot capture + */ + +import { BaseViewer } from '../core/BaseViewer.js'; +import { SettingTypes } from '../ui/SettingsPanel.js'; +import { ControlTypes, StandardControls } from '../ui/ControlsBar.js'; + +/** + * Standard viewer configuration + */ +const STANDARD_CONFIG = { + // Camera + cameraDistanceMultiplier: 2.5, + + // Features + enableFields: true, + enableTextures: false, + enableScreenshot: true, + enableAxisIndicator: false, + enableSettings: true, + enableControls: true, + + // Appearance + backgroundColor: [0.15, 0.15, 0.15], + defaultMeshColor: [0.6, 0.8, 1.0], + showEdges: false +}; + +export class StandardViewer extends BaseViewer { + /** + * Create a StandardViewer + * @param {HTMLElement} container - Container element + * @param {Object} config - Additional configuration + */ + constructor(container, config = {}) { + // Merge with standard config + const mergedConfig = { + ...STANDARD_CONFIG, + ...config, + // Settings panel configuration + settingsConfig: { + title: 'Settings', + fields: [ + { + type: SettingTypes.COLOR, + id: 'meshColor', + label: 'Mesh Color', + defaultValue: config.defaultMeshColor || STANDARD_CONFIG.defaultMeshColor + }, + { + type: SettingTypes.CHECKBOX, + id: 'showEdges', + label: 'Show Edges', + defaultValue: config.showEdges || STANDARD_CONFIG.showEdges + }, + { + type: SettingTypes.COLOR, + id: 'edgeColor', + label: 'Edge Color', + defaultValue: config.edgeColor || [0.2, 0.2, 0.2] + }, + { + type: SettingTypes.COLOR, + id: 'backgroundColor', + label: 'Background', + defaultValue: config.backgroundColor || STANDARD_CONFIG.backgroundColor + } + ] + }, + // Controls bar configuration + controlsConfig: { + controls: [ + StandardControls.CAMERA_VIEWS, + StandardControls.SCREENSHOT, + StandardControls.SETTINGS + ] + } + }; + + super(container, mergedConfig); + + // Field visualization state + this.currentField = null; + this.currentColormap = 'erdc_rainbow_bright'; + this.availableFields = []; + } + + /** + * Load mesh and extract field information + * @param {string} url - Mesh file URL + * @returns {Promise} + */ + async loadMesh(url) { + const result = await super.loadMesh(url); + + // Extract field information for VTP files + if (this.fieldVisualization && this.polyDatas.length > 0) { + const fieldInfo = this.fieldVisualization.extractFields(this.polyDatas[0]); + this.availableFields = fieldInfo.allFields; + + // Notify parent about available fields + if (this.availableFields.length > 0) { + window.parent?.postMessage({ + type: 'fieldsAvailable', + fields: this.availableFields.map(f => ({ + name: f.fullName, + displayName: f.displayName, + type: f.type, + range: f.range + })) + }, '*'); + } + } + + return result; + } + + /** + * Apply scalar field visualization + * @param {string} fieldName - Field name (e.g., 'point:temperature') + * @param {Object} options - Visualization options + */ + applyField(fieldName, options = {}) { + if (!this.fieldVisualization || this.polyDatas.length === 0) { + console.warn('[StandardViewer] Field visualization not available'); + return; + } + + const mapper = this.actors[0]?.getMapper(); + if (!mapper) return; + + this.fieldVisualization.applyField( + mapper, + this.polyDatas[0], + fieldName, + { + colormap: options.colormap || this.currentColormap, + range: options.range, + render: true + } + ); + + this.currentField = fieldName; + if (options.colormap) { + this.currentColormap = options.colormap; + } + } + + /** + * Set colormap + * @param {string} colormap - Colormap name + */ + setColormap(colormap) { + this.currentColormap = colormap; + if (this.currentField) { + this.applyField(this.currentField, { colormap }); + } + } + + /** + * Clear field visualization (show solid color) + */ + clearField() { + if (this.actors.length > 0) { + const mapper = this.actors[0].getMapper(); + if (mapper) { + this.fieldVisualization?.disableScalarVisualization(mapper, true); + } + } + this.currentField = null; + } + + /** + * Get available colormap options + * @returns {Array} + */ + getColormapOptions() { + return this.fieldVisualization?.getColormapOptions() || []; + } + + /** + * Get available fields + * @returns {Array} + */ + getAvailableFields() { + return this.availableFields; + } + + /** + * Setup message listener with field support + * @private + * @override + */ + _setupMessageListener() { + super._setupMessageListener(); + + // Add field-specific message handling + window.addEventListener('message', (event) => { + const data = event.data; + if (!data || !data.type) return; + + switch (data.type) { + case 'setField': + this.applyField(data.field, { + colormap: data.colormap, + range: data.range + }); + break; + + case 'setColormap': + this.setColormap(data.colormap); + break; + + case 'clearField': + this.clearField(); + break; + } + }); + } +} + +/** + * Create a StandardViewer instance + * @param {HTMLElement} container + * @param {Object} config + * @returns {StandardViewer} + */ +export function createStandardViewer(container, config = {}) { + const viewer = new StandardViewer(container, config); + viewer.initialize(); + return viewer; +} + +export default StandardViewer; diff --git a/javascript/js/viewer/viewers/TexturedViewer.js b/javascript/js/viewer/viewers/TexturedViewer.js new file mode 100644 index 00000000..84441cc0 --- /dev/null +++ b/javascript/js/viewer/viewers/TexturedViewer.js @@ -0,0 +1,161 @@ +/** + * TexturedViewer - VTK viewer for textured GLTF/GLB meshes + * + * Specialized for displaying textured 3D models with proper: + * - Material handling (metallic=0, roughness=1) + * - Texture extraction and application + * - Two-sided lighting + * - Closer camera distance for better texture viewing + */ + +import { BaseViewer } from '../core/BaseViewer.js'; +import { SettingTypes } from '../ui/SettingsPanel.js'; +import { StandardControls } from '../ui/ControlsBar.js'; + +/** + * Textured viewer configuration + */ +const TEXTURED_CONFIG = { + // Camera - closer for texture detail + cameraDistanceMultiplier: 2.0, + + // Lighting + twoSidedLighting: true, + + // Features + enableFields: false, + enableTextures: true, + enableScreenshot: true, + enableAxisIndicator: false, + enableSettings: true, + enableControls: true, + + // Appearance + backgroundColor: [0.15, 0.15, 0.15], + defaultMeshColor: [1.0, 1.0, 1.0], + showEdges: false +}; + +export class TexturedViewer extends BaseViewer { + /** + * Create a TexturedViewer + * @param {HTMLElement} container - Container element + * @param {Object} config - Additional configuration + */ + constructor(container, config = {}) { + // Merge with textured config + const mergedConfig = { + ...TEXTURED_CONFIG, + ...config, + // Settings panel configuration + settingsConfig: { + title: 'Settings', + fields: [ + { + type: SettingTypes.COLOR, + id: 'backgroundColor', + label: 'Background', + defaultValue: config.backgroundColor || TEXTURED_CONFIG.backgroundColor + }, + { + type: SettingTypes.CHECKBOX, + id: 'showEdges', + label: 'Show Edges', + defaultValue: false + } + ] + }, + // Controls bar configuration + controlsConfig: { + controls: [ + StandardControls.CAMERA_VIEWS, + StandardControls.SCREENSHOT, + StandardControls.SETTINGS + ] + } + }; + + super(container, mergedConfig); + + // Texture state + this.textureInfo = null; + } + + /** + * Configure loaded actors for textured display + * @private + * @override + */ + _configureLoadedActors(result) { + if (this.textureManager && result.actors.length > 0) { + // Apply texture fixes to all actors + this.textureInfo = this.textureManager.applyTextureFixesMultiple(result.actors); + + // Configure renderer for texture display + this.textureManager.configureRenderer(this.renderer); + + console.log('[TexturedViewer] Texture info:', this.textureInfo); + + // If no textures found, apply default white color + if (!this.textureInfo.hasTexture) { + result.actors.forEach(actor => { + this.textureManager.setActorColor(actor, this.config.defaultMeshColor); + }); + } + } + } + + /** + * Update info overlay with texture information + * @private + * @override + */ + _updateInfoOverlay(result) { + if (!this.infoOverlay) return; + + const lines = [`File: ${this.currentFilename}`]; + + if (result.actors) { + lines.push(`Actors: ${result.actors.length}`); + } + + if (this.textureInfo) { + lines.push(`Textured: ${this.textureInfo.hasTexture ? 'Yes' : 'No'}`); + if (this.textureInfo.texturedActors > 0) { + lines.push(`Textured actors: ${this.textureInfo.texturedActors}`); + } + } + + this.infoOverlay.innerHTML = lines.join('
'); + } + + /** + * Get texture information + * @returns {Object|null} + */ + getTextureInfo() { + return this.textureInfo; + } + + /** + * Check if current mesh has textures + * @returns {boolean} + */ + hasTextures() { + return this.textureInfo?.hasTexture || false; + } +} + +/** + * Create a TexturedViewer instance + * @param {HTMLElement} container + * @param {Object} config + * @returns {TexturedViewer} + */ +export function createTexturedViewer(container, config = {}) { + const viewer = new TexturedViewer(container, config); + viewer.initialize(); + return viewer; +} + +export default TexturedViewer; diff --git a/javascript/js/vtk-gltf.js b/javascript/js/vtk-gltf.js new file mode 100644 index 00000000..354f3a18 --- /dev/null +++ b/javascript/js/vtk-gltf.js @@ -0,0 +1,2 @@ +/*! For license information please see vtk-gltf.js.LICENSE.txt */ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.vtk=t():e.vtk=t()}(globalThis,()=>(()=>{var e={581(e,t,r){"use strict";r.d(t,{default:()=>J_});var n={};r.r(n),r.d(n,{add:()=>Q,adjoint:()=>y,clone:()=>c,copy:()=>d,create:()=>u,determinant:()=>v,equals:()=>ne,exactEquals:()=>re,frob:()=>J,fromQuat:()=>U,fromQuat2:()=>M,fromRotation:()=>D,fromRotationTranslation:()=>N,fromRotationTranslationScale:()=>L,fromRotationTranslationScaleOrigin:()=>k,fromScaling:()=>E,fromTranslation:()=>A,fromValues:()=>p,fromXRotation:()=>P,fromYRotation:()=>I,fromZRotation:()=>O,frustum:()=>V,getRotation:()=>B,getScaling:()=>F,getTranslation:()=>R,identity:()=>h,invert:()=>g,lookAt:()=>$,mul:()=>oe,multiply:()=>b,multiplyScalar:()=>ee,multiplyScalarAndAdd:()=>te,ortho:()=>K,orthoNO:()=>H,orthoZO:()=>X,perspective:()=>z,perspectiveFromFieldOfView:()=>W,perspectiveNO:()=>G,perspectiveZO:()=>j,rotate:()=>S,rotateX:()=>C,rotateY:()=>T,rotateZ:()=>w,scale:()=>_,set:()=>f,str:()=>Y,sub:()=>ie,subtract:()=>Z,targetTo:()=>q,translate:()=>x,transpose:()=>m});var o={};r.r(o),r.d(o,{add:()=>Ie,adjoint:()=>me,clone:()=>le,copy:()=>ue,create:()=>ae,determinant:()=>ge,equals:()=>Fe,exactEquals:()=>Re,frob:()=>Pe,fromMat2d:()=>Te,fromMat4:()=>se,fromQuat:()=>we,fromRotation:()=>Se,fromScaling:()=>Ce,fromTranslation:()=>_e,fromValues:()=>ce,identity:()=>pe,invert:()=>he,mul:()=>Be,multiply:()=>ye,multiplyScalar:()=>Ne,multiplyScalarAndAdd:()=>Me,normalFromMat4:()=>Ae,projection:()=>Ee,rotate:()=>be,scale:()=>xe,set:()=>de,str:()=>De,sub:()=>Le,subtract:()=>Oe,translate:()=>ve,transpose:()=>fe});var i=1e-6,a="undefined"!=typeof Float32Array?Float32Array:Array;Math.random;var s=Math.PI/180;function l(e){return e*s}function u(){var e=new a(16);return a!=Float32Array&&(e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0),e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function c(e){var t=new a(16);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function d(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function p(e,t,r,n,o,i,s,l,u,c,d,p,f,h,m,g){var y=new a(16);return y[0]=e,y[1]=t,y[2]=r,y[3]=n,y[4]=o,y[5]=i,y[6]=s,y[7]=l,y[8]=u,y[9]=c,y[10]=d,y[11]=p,y[12]=f,y[13]=h,y[14]=m,y[15]=g,y}function f(e,t,r,n,o,i,a,s,l,u,c,d,p,f,h,m,g){return e[0]=t,e[1]=r,e[2]=n,e[3]=o,e[4]=i,e[5]=a,e[6]=s,e[7]=l,e[8]=u,e[9]=c,e[10]=d,e[11]=p,e[12]=f,e[13]=h,e[14]=m,e[15]=g,e}function h(e){return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function m(e,t){if(e===t){var r=t[1],n=t[2],o=t[3],i=t[6],a=t[7],s=t[11];e[1]=t[4],e[2]=t[8],e[3]=t[12],e[4]=r,e[6]=t[9],e[7]=t[13],e[8]=n,e[9]=i,e[11]=t[14],e[12]=o,e[13]=a,e[14]=s}else e[0]=t[0],e[1]=t[4],e[2]=t[8],e[3]=t[12],e[4]=t[1],e[5]=t[5],e[6]=t[9],e[7]=t[13],e[8]=t[2],e[9]=t[6],e[10]=t[10],e[11]=t[14],e[12]=t[3],e[13]=t[7],e[14]=t[11],e[15]=t[15];return e}function g(e,t){var r=t[0],n=t[1],o=t[2],i=t[3],a=t[4],s=t[5],l=t[6],u=t[7],c=t[8],d=t[9],p=t[10],f=t[11],h=t[12],m=t[13],g=t[14],y=t[15],v=r*s-n*a,b=r*l-o*a,x=r*u-i*a,_=n*l-o*s,S=n*u-i*s,C=o*u-i*l,T=c*m-d*h,w=c*g-p*h,A=c*y-f*h,E=d*g-p*m,D=d*y-f*m,P=p*y-f*g,I=v*P-b*D+x*E+_*A-S*w+C*T;return I?(I=1/I,e[0]=(s*P-l*D+u*E)*I,e[1]=(o*D-n*P-i*E)*I,e[2]=(m*C-g*S+y*_)*I,e[3]=(p*S-d*C-f*_)*I,e[4]=(l*A-a*P-u*w)*I,e[5]=(r*P-o*A+i*w)*I,e[6]=(g*x-h*C-y*b)*I,e[7]=(c*C-p*x+f*b)*I,e[8]=(a*D-s*A+u*T)*I,e[9]=(n*A-r*D-i*T)*I,e[10]=(h*S-m*x+y*v)*I,e[11]=(d*x-c*S-f*v)*I,e[12]=(s*w-a*E-l*T)*I,e[13]=(r*E-n*w+o*T)*I,e[14]=(m*b-h*_-g*v)*I,e[15]=(c*_-d*b+p*v)*I,e):null}function y(e,t){var r=t[0],n=t[1],o=t[2],i=t[3],a=t[4],s=t[5],l=t[6],u=t[7],c=t[8],d=t[9],p=t[10],f=t[11],h=t[12],m=t[13],g=t[14],y=t[15];return e[0]=s*(p*y-f*g)-d*(l*y-u*g)+m*(l*f-u*p),e[1]=-(n*(p*y-f*g)-d*(o*y-i*g)+m*(o*f-i*p)),e[2]=n*(l*y-u*g)-s*(o*y-i*g)+m*(o*u-i*l),e[3]=-(n*(l*f-u*p)-s*(o*f-i*p)+d*(o*u-i*l)),e[4]=-(a*(p*y-f*g)-c*(l*y-u*g)+h*(l*f-u*p)),e[5]=r*(p*y-f*g)-c*(o*y-i*g)+h*(o*f-i*p),e[6]=-(r*(l*y-u*g)-a*(o*y-i*g)+h*(o*u-i*l)),e[7]=r*(l*f-u*p)-a*(o*f-i*p)+c*(o*u-i*l),e[8]=a*(d*y-f*m)-c*(s*y-u*m)+h*(s*f-u*d),e[9]=-(r*(d*y-f*m)-c*(n*y-i*m)+h*(n*f-i*d)),e[10]=r*(s*y-u*m)-a*(n*y-i*m)+h*(n*u-i*s),e[11]=-(r*(s*f-u*d)-a*(n*f-i*d)+c*(n*u-i*s)),e[12]=-(a*(d*g-p*m)-c*(s*g-l*m)+h*(s*p-l*d)),e[13]=r*(d*g-p*m)-c*(n*g-o*m)+h*(n*p-o*d),e[14]=-(r*(s*g-l*m)-a*(n*g-o*m)+h*(n*l-o*s)),e[15]=r*(s*p-l*d)-a*(n*p-o*d)+c*(n*l-o*s),e}function v(e){var t=e[0],r=e[1],n=e[2],o=e[3],i=e[4],a=e[5],s=e[6],l=e[7],u=e[8],c=e[9],d=e[10],p=e[11],f=e[12],h=e[13],m=e[14],g=e[15];return(t*a-r*i)*(d*g-p*m)-(t*s-n*i)*(c*g-p*h)+(t*l-o*i)*(c*m-d*h)+(r*s-n*a)*(u*g-p*f)-(r*l-o*a)*(u*m-d*f)+(n*l-o*s)*(u*h-c*f)}function b(e,t,r){var n=t[0],o=t[1],i=t[2],a=t[3],s=t[4],l=t[5],u=t[6],c=t[7],d=t[8],p=t[9],f=t[10],h=t[11],m=t[12],g=t[13],y=t[14],v=t[15],b=r[0],x=r[1],_=r[2],S=r[3];return e[0]=b*n+x*s+_*d+S*m,e[1]=b*o+x*l+_*p+S*g,e[2]=b*i+x*u+_*f+S*y,e[3]=b*a+x*c+_*h+S*v,b=r[4],x=r[5],_=r[6],S=r[7],e[4]=b*n+x*s+_*d+S*m,e[5]=b*o+x*l+_*p+S*g,e[6]=b*i+x*u+_*f+S*y,e[7]=b*a+x*c+_*h+S*v,b=r[8],x=r[9],_=r[10],S=r[11],e[8]=b*n+x*s+_*d+S*m,e[9]=b*o+x*l+_*p+S*g,e[10]=b*i+x*u+_*f+S*y,e[11]=b*a+x*c+_*h+S*v,b=r[12],x=r[13],_=r[14],S=r[15],e[12]=b*n+x*s+_*d+S*m,e[13]=b*o+x*l+_*p+S*g,e[14]=b*i+x*u+_*f+S*y,e[15]=b*a+x*c+_*h+S*v,e}function x(e,t,r){var n,o,i,a,s,l,u,c,d,p,f,h,m=r[0],g=r[1],y=r[2];return t===e?(e[12]=t[0]*m+t[4]*g+t[8]*y+t[12],e[13]=t[1]*m+t[5]*g+t[9]*y+t[13],e[14]=t[2]*m+t[6]*g+t[10]*y+t[14],e[15]=t[3]*m+t[7]*g+t[11]*y+t[15]):(n=t[0],o=t[1],i=t[2],a=t[3],s=t[4],l=t[5],u=t[6],c=t[7],d=t[8],p=t[9],f=t[10],h=t[11],e[0]=n,e[1]=o,e[2]=i,e[3]=a,e[4]=s,e[5]=l,e[6]=u,e[7]=c,e[8]=d,e[9]=p,e[10]=f,e[11]=h,e[12]=n*m+s*g+d*y+t[12],e[13]=o*m+l*g+p*y+t[13],e[14]=i*m+u*g+f*y+t[14],e[15]=a*m+c*g+h*y+t[15]),e}function _(e,t,r){var n=r[0],o=r[1],i=r[2];return e[0]=t[0]*n,e[1]=t[1]*n,e[2]=t[2]*n,e[3]=t[3]*n,e[4]=t[4]*o,e[5]=t[5]*o,e[6]=t[6]*o,e[7]=t[7]*o,e[8]=t[8]*i,e[9]=t[9]*i,e[10]=t[10]*i,e[11]=t[11]*i,e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function S(e,t,r,n){var o,a,s,l,u,c,d,p,f,h,m,g,y,v,b,x,_,S,C,T,w,A,E,D,P=n[0],I=n[1],O=n[2],N=Math.hypot(P,I,O);return N0?(r[0]=2*(l*s+d*n+u*i-c*o)/p,r[1]=2*(u*s+d*o+c*n-l*i)/p,r[2]=2*(c*s+d*i+l*o-u*n)/p):(r[0]=2*(l*s+d*n+u*i-c*o),r[1]=2*(u*s+d*o+c*n-l*i),r[2]=2*(c*s+d*i+l*o-u*n)),N(e,t,r),e}function R(e,t){return e[0]=t[12],e[1]=t[13],e[2]=t[14],e}function F(e,t){var r=t[0],n=t[1],o=t[2],i=t[4],a=t[5],s=t[6],l=t[8],u=t[9],c=t[10];return e[0]=Math.hypot(r,n,o),e[1]=Math.hypot(i,a,s),e[2]=Math.hypot(l,u,c),e}function B(e,t){var r=new a(3);F(r,t);var n=1/r[0],o=1/r[1],i=1/r[2],s=t[0]*n,l=t[1]*o,u=t[2]*i,c=t[4]*n,d=t[5]*o,p=t[6]*i,f=t[8]*n,h=t[9]*o,m=t[10]*i,g=s+d+m,y=0;return g>0?(y=2*Math.sqrt(g+1),e[3]=.25*y,e[0]=(p-h)/y,e[1]=(f-u)/y,e[2]=(l-c)/y):s>d&&s>m?(y=2*Math.sqrt(1+s-d-m),e[3]=(p-h)/y,e[0]=.25*y,e[1]=(l+c)/y,e[2]=(f+u)/y):d>m?(y=2*Math.sqrt(1+d-s-m),e[3]=(f-u)/y,e[0]=(l+c)/y,e[1]=.25*y,e[2]=(p+h)/y):(y=2*Math.sqrt(1+m-s-d),e[3]=(l-c)/y,e[0]=(f+u)/y,e[1]=(p+h)/y,e[2]=.25*y),e}function L(e,t,r,n){var o=t[0],i=t[1],a=t[2],s=t[3],l=o+o,u=i+i,c=a+a,d=o*l,p=o*u,f=o*c,h=i*u,m=i*c,g=a*c,y=s*l,v=s*u,b=s*c,x=n[0],_=n[1],S=n[2];return e[0]=(1-(h+g))*x,e[1]=(p+b)*x,e[2]=(f-v)*x,e[3]=0,e[4]=(p-b)*_,e[5]=(1-(d+g))*_,e[6]=(m+y)*_,e[7]=0,e[8]=(f+v)*S,e[9]=(m-y)*S,e[10]=(1-(d+h))*S,e[11]=0,e[12]=r[0],e[13]=r[1],e[14]=r[2],e[15]=1,e}function k(e,t,r,n,o){var i=t[0],a=t[1],s=t[2],l=t[3],u=i+i,c=a+a,d=s+s,p=i*u,f=i*c,h=i*d,m=a*c,g=a*d,y=s*d,v=l*u,b=l*c,x=l*d,_=n[0],S=n[1],C=n[2],T=o[0],w=o[1],A=o[2],E=(1-(m+y))*_,D=(f+x)*_,P=(h-b)*_,I=(f-x)*S,O=(1-(p+y))*S,N=(g+v)*S,M=(h+b)*C,R=(g-v)*C,F=(1-(p+m))*C;return e[0]=E,e[1]=D,e[2]=P,e[3]=0,e[4]=I,e[5]=O,e[6]=N,e[7]=0,e[8]=M,e[9]=R,e[10]=F,e[11]=0,e[12]=r[0]+T-(E*T+I*w+M*A),e[13]=r[1]+w-(D*T+O*w+R*A),e[14]=r[2]+A-(P*T+N*w+F*A),e[15]=1,e}function U(e,t){var r=t[0],n=t[1],o=t[2],i=t[3],a=r+r,s=n+n,l=o+o,u=r*a,c=n*a,d=n*s,p=o*a,f=o*s,h=o*l,m=i*a,g=i*s,y=i*l;return e[0]=1-d-h,e[1]=c+y,e[2]=p-g,e[3]=0,e[4]=c-y,e[5]=1-u-h,e[6]=f+m,e[7]=0,e[8]=p+g,e[9]=f-m,e[10]=1-u-d,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function V(e,t,r,n,o,i,a){var s=1/(r-t),l=1/(o-n),u=1/(i-a);return e[0]=2*i*s,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=2*i*l,e[6]=0,e[7]=0,e[8]=(r+t)*s,e[9]=(o+n)*l,e[10]=(a+i)*u,e[11]=-1,e[12]=0,e[13]=0,e[14]=a*i*2*u,e[15]=0,e}function G(e,t,r,n,o){var i,a=1/Math.tan(t/2);return e[0]=a/r,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=a,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[11]=-1,e[12]=0,e[13]=0,e[15]=0,null!=o&&o!==1/0?(i=1/(n-o),e[10]=(o+n)*i,e[14]=2*o*n*i):(e[10]=-1,e[14]=-2*n),e}Math.hypot||(Math.hypot=function(){for(var e=0,t=arguments.length;t--;)e+=arguments[t]*arguments[t];return Math.sqrt(e)});var z=G;function j(e,t,r,n,o){var i,a=1/Math.tan(t/2);return e[0]=a/r,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=a,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[11]=-1,e[12]=0,e[13]=0,e[15]=0,null!=o&&o!==1/0?(i=1/(n-o),e[10]=o*i,e[14]=o*n*i):(e[10]=-1,e[14]=-n),e}function W(e,t,r,n){var o=Math.tan(t.upDegrees*Math.PI/180),i=Math.tan(t.downDegrees*Math.PI/180),a=Math.tan(t.leftDegrees*Math.PI/180),s=Math.tan(t.rightDegrees*Math.PI/180),l=2/(a+s),u=2/(o+i);return e[0]=l,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=u,e[6]=0,e[7]=0,e[8]=-(a-s)*l*.5,e[9]=(o-i)*u*.5,e[10]=n/(r-n),e[11]=-1,e[12]=0,e[13]=0,e[14]=n*r/(r-n),e[15]=0,e}function H(e,t,r,n,o,i,a){var s=1/(t-r),l=1/(n-o),u=1/(i-a);return e[0]=-2*s,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=-2*l,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=2*u,e[11]=0,e[12]=(t+r)*s,e[13]=(o+n)*l,e[14]=(a+i)*u,e[15]=1,e}var K=H;function X(e,t,r,n,o,i,a){var s=1/(t-r),l=1/(n-o),u=1/(i-a);return e[0]=-2*s,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=-2*l,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=u,e[11]=0,e[12]=(t+r)*s,e[13]=(o+n)*l,e[14]=i*u,e[15]=1,e}function $(e,t,r,n){var o,a,s,l,u,c,d,p,f,m,g=t[0],y=t[1],v=t[2],b=n[0],x=n[1],_=n[2],S=r[0],C=r[1],T=r[2];return Math.abs(g-S)0&&(c*=f=1/Math.sqrt(f),d*=f,p*=f);var h=l*p-u*d,m=u*c-s*p,g=s*d-l*c;return(f=h*h+m*m+g*g)>0&&(h*=f=1/Math.sqrt(f),m*=f,g*=f),e[0]=h,e[1]=m,e[2]=g,e[3]=0,e[4]=d*g-p*m,e[5]=p*h-c*g,e[6]=c*m-d*h,e[7]=0,e[8]=c,e[9]=d,e[10]=p,e[11]=0,e[12]=o,e[13]=i,e[14]=a,e[15]=1,e}function Y(e){return"mat4("+e[0]+", "+e[1]+", "+e[2]+", "+e[3]+", "+e[4]+", "+e[5]+", "+e[6]+", "+e[7]+", "+e[8]+", "+e[9]+", "+e[10]+", "+e[11]+", "+e[12]+", "+e[13]+", "+e[14]+", "+e[15]+")"}function J(e){return Math.hypot(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}function Q(e,t,r){return e[0]=t[0]+r[0],e[1]=t[1]+r[1],e[2]=t[2]+r[2],e[3]=t[3]+r[3],e[4]=t[4]+r[4],e[5]=t[5]+r[5],e[6]=t[6]+r[6],e[7]=t[7]+r[7],e[8]=t[8]+r[8],e[9]=t[9]+r[9],e[10]=t[10]+r[10],e[11]=t[11]+r[11],e[12]=t[12]+r[12],e[13]=t[13]+r[13],e[14]=t[14]+r[14],e[15]=t[15]+r[15],e}function Z(e,t,r){return e[0]=t[0]-r[0],e[1]=t[1]-r[1],e[2]=t[2]-r[2],e[3]=t[3]-r[3],e[4]=t[4]-r[4],e[5]=t[5]-r[5],e[6]=t[6]-r[6],e[7]=t[7]-r[7],e[8]=t[8]-r[8],e[9]=t[9]-r[9],e[10]=t[10]-r[10],e[11]=t[11]-r[11],e[12]=t[12]-r[12],e[13]=t[13]-r[13],e[14]=t[14]-r[14],e[15]=t[15]-r[15],e}function ee(e,t,r){return e[0]=t[0]*r,e[1]=t[1]*r,e[2]=t[2]*r,e[3]=t[3]*r,e[4]=t[4]*r,e[5]=t[5]*r,e[6]=t[6]*r,e[7]=t[7]*r,e[8]=t[8]*r,e[9]=t[9]*r,e[10]=t[10]*r,e[11]=t[11]*r,e[12]=t[12]*r,e[13]=t[13]*r,e[14]=t[14]*r,e[15]=t[15]*r,e}function te(e,t,r,n){return e[0]=t[0]+r[0]*n,e[1]=t[1]+r[1]*n,e[2]=t[2]+r[2]*n,e[3]=t[3]+r[3]*n,e[4]=t[4]+r[4]*n,e[5]=t[5]+r[5]*n,e[6]=t[6]+r[6]*n,e[7]=t[7]+r[7]*n,e[8]=t[8]+r[8]*n,e[9]=t[9]+r[9]*n,e[10]=t[10]+r[10]*n,e[11]=t[11]+r[11]*n,e[12]=t[12]+r[12]*n,e[13]=t[13]+r[13]*n,e[14]=t[14]+r[14]*n,e[15]=t[15]+r[15]*n,e}function re(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15]}function ne(e,t){var r=e[0],n=e[1],o=e[2],a=e[3],s=e[4],l=e[5],u=e[6],c=e[7],d=e[8],p=e[9],f=e[10],h=e[11],m=e[12],g=e[13],y=e[14],v=e[15],b=t[0],x=t[1],_=t[2],S=t[3],C=t[4],T=t[5],w=t[6],A=t[7],E=t[8],D=t[9],P=t[10],I=t[11],O=t[12],N=t[13],M=t[14],R=t[15];return Math.abs(r-b)<=i*Math.max(1,Math.abs(r),Math.abs(b))&&Math.abs(n-x)<=i*Math.max(1,Math.abs(n),Math.abs(x))&&Math.abs(o-_)<=i*Math.max(1,Math.abs(o),Math.abs(_))&&Math.abs(a-S)<=i*Math.max(1,Math.abs(a),Math.abs(S))&&Math.abs(s-C)<=i*Math.max(1,Math.abs(s),Math.abs(C))&&Math.abs(l-T)<=i*Math.max(1,Math.abs(l),Math.abs(T))&&Math.abs(u-w)<=i*Math.max(1,Math.abs(u),Math.abs(w))&&Math.abs(c-A)<=i*Math.max(1,Math.abs(c),Math.abs(A))&&Math.abs(d-E)<=i*Math.max(1,Math.abs(d),Math.abs(E))&&Math.abs(p-D)<=i*Math.max(1,Math.abs(p),Math.abs(D))&&Math.abs(f-P)<=i*Math.max(1,Math.abs(f),Math.abs(P))&&Math.abs(h-I)<=i*Math.max(1,Math.abs(h),Math.abs(I))&&Math.abs(m-O)<=i*Math.max(1,Math.abs(m),Math.abs(O))&&Math.abs(g-N)<=i*Math.max(1,Math.abs(g),Math.abs(N))&&Math.abs(y-M)<=i*Math.max(1,Math.abs(y),Math.abs(M))&&Math.abs(v-R)<=i*Math.max(1,Math.abs(v),Math.abs(R))}var oe=b,ie=Z;function ae(){var e=new a(9);return a!=Float32Array&&(e[1]=0,e[2]=0,e[3]=0,e[5]=0,e[6]=0,e[7]=0),e[0]=1,e[4]=1,e[8]=1,e}function se(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[4],e[4]=t[5],e[5]=t[6],e[6]=t[8],e[7]=t[9],e[8]=t[10],e}function le(e){var t=new a(9);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t}function ue(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e}function ce(e,t,r,n,o,i,s,l,u){var c=new a(9);return c[0]=e,c[1]=t,c[2]=r,c[3]=n,c[4]=o,c[5]=i,c[6]=s,c[7]=l,c[8]=u,c}function de(e,t,r,n,o,i,a,s,l,u){return e[0]=t,e[1]=r,e[2]=n,e[3]=o,e[4]=i,e[5]=a,e[6]=s,e[7]=l,e[8]=u,e}function pe(e){return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e}function fe(e,t){if(e===t){var r=t[1],n=t[2],o=t[5];e[1]=t[3],e[2]=t[6],e[3]=r,e[5]=t[7],e[6]=n,e[7]=o}else e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8];return e}function he(e,t){var r=t[0],n=t[1],o=t[2],i=t[3],a=t[4],s=t[5],l=t[6],u=t[7],c=t[8],d=c*a-s*u,p=-c*i+s*l,f=u*i-a*l,h=r*d+n*p+o*f;return h?(h=1/h,e[0]=d*h,e[1]=(-c*n+o*u)*h,e[2]=(s*n-o*a)*h,e[3]=p*h,e[4]=(c*r-o*l)*h,e[5]=(-s*r+o*i)*h,e[6]=f*h,e[7]=(-u*r+n*l)*h,e[8]=(a*r-n*i)*h,e):null}function me(e,t){var r=t[0],n=t[1],o=t[2],i=t[3],a=t[4],s=t[5],l=t[6],u=t[7],c=t[8];return e[0]=a*c-s*u,e[1]=o*u-n*c,e[2]=n*s-o*a,e[3]=s*l-i*c,e[4]=r*c-o*l,e[5]=o*i-r*s,e[6]=i*u-a*l,e[7]=n*l-r*u,e[8]=r*a-n*i,e}function ge(e){var t=e[0],r=e[1],n=e[2],o=e[3],i=e[4],a=e[5],s=e[6],l=e[7],u=e[8];return t*(u*i-a*l)+r*(-u*o+a*s)+n*(l*o-i*s)}function ye(e,t,r){var n=t[0],o=t[1],i=t[2],a=t[3],s=t[4],l=t[5],u=t[6],c=t[7],d=t[8],p=r[0],f=r[1],h=r[2],m=r[3],g=r[4],y=r[5],v=r[6],b=r[7],x=r[8];return e[0]=p*n+f*a+h*u,e[1]=p*o+f*s+h*c,e[2]=p*i+f*l+h*d,e[3]=m*n+g*a+y*u,e[4]=m*o+g*s+y*c,e[5]=m*i+g*l+y*d,e[6]=v*n+b*a+x*u,e[7]=v*o+b*s+x*c,e[8]=v*i+b*l+x*d,e}function ve(e,t,r){var n=t[0],o=t[1],i=t[2],a=t[3],s=t[4],l=t[5],u=t[6],c=t[7],d=t[8],p=r[0],f=r[1];return e[0]=n,e[1]=o,e[2]=i,e[3]=a,e[4]=s,e[5]=l,e[6]=p*n+f*a+u,e[7]=p*o+f*s+c,e[8]=p*i+f*l+d,e}function be(e,t,r){var n=t[0],o=t[1],i=t[2],a=t[3],s=t[4],l=t[5],u=t[6],c=t[7],d=t[8],p=Math.sin(r),f=Math.cos(r);return e[0]=f*n+p*a,e[1]=f*o+p*s,e[2]=f*i+p*l,e[3]=f*a-p*n,e[4]=f*s-p*o,e[5]=f*l-p*i,e[6]=u,e[7]=c,e[8]=d,e}function xe(e,t,r){var n=r[0],o=r[1];return e[0]=n*t[0],e[1]=n*t[1],e[2]=n*t[2],e[3]=o*t[3],e[4]=o*t[4],e[5]=o*t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e}function _e(e,t){return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=t[0],e[7]=t[1],e[8]=1,e}function Se(e,t){var r=Math.sin(t),n=Math.cos(t);return e[0]=n,e[1]=r,e[2]=0,e[3]=-r,e[4]=n,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e}function Ce(e,t){return e[0]=t[0],e[1]=0,e[2]=0,e[3]=0,e[4]=t[1],e[5]=0,e[6]=0,e[7]=0,e[8]=1,e}function Te(e,t){return e[0]=t[0],e[1]=t[1],e[2]=0,e[3]=t[2],e[4]=t[3],e[5]=0,e[6]=t[4],e[7]=t[5],e[8]=1,e}function we(e,t){var r=t[0],n=t[1],o=t[2],i=t[3],a=r+r,s=n+n,l=o+o,u=r*a,c=n*a,d=n*s,p=o*a,f=o*s,h=o*l,m=i*a,g=i*s,y=i*l;return e[0]=1-d-h,e[3]=c-y,e[6]=p+g,e[1]=c+y,e[4]=1-u-h,e[7]=f-m,e[2]=p-g,e[5]=f+m,e[8]=1-u-d,e}function Ae(e,t){var r=t[0],n=t[1],o=t[2],i=t[3],a=t[4],s=t[5],l=t[6],u=t[7],c=t[8],d=t[9],p=t[10],f=t[11],h=t[12],m=t[13],g=t[14],y=t[15],v=r*s-n*a,b=r*l-o*a,x=r*u-i*a,_=n*l-o*s,S=n*u-i*s,C=o*u-i*l,T=c*m-d*h,w=c*g-p*h,A=c*y-f*h,E=d*g-p*m,D=d*y-f*m,P=p*y-f*g,I=v*P-b*D+x*E+_*A-S*w+C*T;return I?(I=1/I,e[0]=(s*P-l*D+u*E)*I,e[1]=(l*A-a*P-u*w)*I,e[2]=(a*D-s*A+u*T)*I,e[3]=(o*D-n*P-i*E)*I,e[4]=(r*P-o*A+i*w)*I,e[5]=(n*A-r*D-i*T)*I,e[6]=(m*C-g*S+y*_)*I,e[7]=(g*x-h*C-y*b)*I,e[8]=(h*S-m*x+y*v)*I,e):null}function Ee(e,t,r){return e[0]=2/t,e[1]=0,e[2]=0,e[3]=0,e[4]=-2/r,e[5]=0,e[6]=-1,e[7]=1,e[8]=1,e}function De(e){return"mat3("+e[0]+", "+e[1]+", "+e[2]+", "+e[3]+", "+e[4]+", "+e[5]+", "+e[6]+", "+e[7]+", "+e[8]+")"}function Pe(e){return Math.hypot(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8])}function Ie(e,t,r){return e[0]=t[0]+r[0],e[1]=t[1]+r[1],e[2]=t[2]+r[2],e[3]=t[3]+r[3],e[4]=t[4]+r[4],e[5]=t[5]+r[5],e[6]=t[6]+r[6],e[7]=t[7]+r[7],e[8]=t[8]+r[8],e}function Oe(e,t,r){return e[0]=t[0]-r[0],e[1]=t[1]-r[1],e[2]=t[2]-r[2],e[3]=t[3]-r[3],e[4]=t[4]-r[4],e[5]=t[5]-r[5],e[6]=t[6]-r[6],e[7]=t[7]-r[7],e[8]=t[8]-r[8],e}function Ne(e,t,r){return e[0]=t[0]*r,e[1]=t[1]*r,e[2]=t[2]*r,e[3]=t[3]*r,e[4]=t[4]*r,e[5]=t[5]*r,e[6]=t[6]*r,e[7]=t[7]*r,e[8]=t[8]*r,e}function Me(e,t,r,n){return e[0]=t[0]+r[0]*n,e[1]=t[1]+r[1]*n,e[2]=t[2]+r[2]*n,e[3]=t[3]+r[3]*n,e[4]=t[4]+r[4]*n,e[5]=t[5]+r[5]*n,e[6]=t[6]+r[6]*n,e[7]=t[7]+r[7]*n,e[8]=t[8]+r[8]*n,e}function Re(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]}function Fe(e,t){var r=e[0],n=e[1],o=e[2],a=e[3],s=e[4],l=e[5],u=e[6],c=e[7],d=e[8],p=t[0],f=t[1],h=t[2],m=t[3],g=t[4],y=t[5],v=t[6],b=t[7],x=t[8];return Math.abs(r-p)<=i*Math.max(1,Math.abs(r),Math.abs(p))&&Math.abs(n-f)<=i*Math.max(1,Math.abs(n),Math.abs(f))&&Math.abs(o-h)<=i*Math.max(1,Math.abs(o),Math.abs(h))&&Math.abs(a-m)<=i*Math.max(1,Math.abs(a),Math.abs(m))&&Math.abs(s-g)<=i*Math.max(1,Math.abs(s),Math.abs(g))&&Math.abs(l-y)<=i*Math.max(1,Math.abs(l),Math.abs(y))&&Math.abs(u-v)<=i*Math.max(1,Math.abs(u),Math.abs(v))&&Math.abs(c-b)<=i*Math.max(1,Math.abs(c),Math.abs(b))&&Math.abs(d-x)<=i*Math.max(1,Math.abs(d),Math.abs(x))}var Be=ye,Le=Oe,ke=r(17);const Ue=r(170)(),Ve={vtkObject:()=>null};function Ge(e){if(null==e)return e;if(e.isA)return e;if(!e.vtkClass)return Ue.console&&Ue.console.error&&Ue.console.error("Invalid VTK object"),null;const t=Ve[e.vtkClass];if(!t)return Ue.console&&Ue.console.error&&Ue.console.error(`No vtk class found for Object of type ${e.vtkClass}`),null;const r={...e};Object.keys(r).forEach(e=>{r[e]&&"object"==typeof r[e]&&r[e].vtkClass&&(r[e]=Ge(r[e]))});const n=t(r);return n&&n.modified&&n.modified(),n}Ge.register=function(e,t){Ve[e]=t};class ze extends Array{push(){for(let e=0;e{throw new Error(`Named parameter '${e}' is missing`)},He=Symbol("void"),Ke={};function Xe(){}["log","debug","info","warn","error","time","timeEnd","group","groupEnd"].forEach(e=>{Ke[e]=Xe}),Ue.console=console.hasOwnProperty("log")?console:Ke;const $e={debug:Xe,error:Ue.console.error||Xe,info:Ue.console.info||Xe,log:Ue.console.log||Xe,warn:Ue.console.warn||Xe};function qe(e,t){$e[e]&&($e[e]=t||Xe)}function Ye(){$e.log(...arguments)}function Je(){$e.info(...arguments)}function Qe(){$e.debug(...arguments)}function Ze(){$e.error(...arguments)}function et(){$e.warn(...arguments)}const tt={};function rt(e){tt[e]||($e.error(e),tt[e]=!0)}const nt=Object.create(null);nt.Float32Array=Float32Array,nt.Float64Array=Float64Array,nt.Uint8Array=Uint8Array,nt.Int8Array=Int8Array,nt.Uint16Array=Uint16Array,nt.Int16Array=Int16Array,nt.Uint32Array=Uint32Array,nt.Int32Array=Int32Array,nt.Uint8ClampedArray=Uint8ClampedArray;try{nt.BigInt64Array=BigInt64Array,nt.BigUint64Array=BigUint64Array}catch{}function ot(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n1?t-1:0),n=1;n1&&void 0!==arguments[1]?arguments[1]:2,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1e3;const n=["TB","GB","MB","KB"];let o=Number(e),i="B";for(;o>r;)o/=r,i=n.pop();return`${o.toFixed(t)} ${i}`}function ct(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:" ";const r=[];let n=e;for(;n>1e3;)r.push(("000"+n%1e3).slice(-3)),n=Math.floor(n/1e3);return n>0&&r.push(n),r.reverse(),r.join(t)}function dt(e){Object.keys(e).forEach(t=>{Array.isArray(e[t])&&(e[t]=[].concat(e[t]))})}function pt(e){return e&&e.isA?e.getState():e}function ft(e){setTimeout(e,0)}function ht(e,t){const r=performance.now();e.finally(()=>{const e=performance.now()-r;t(e)})}function mt(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};dt(t);const r=[];if(Number.isInteger(t.mtime)||(t.mtime=++je),"classHierarchy"in t){if(!(t.classHierarchy instanceof ze)){const e=new ze;for(let r=0;r!!t.deleted,e.modified=n=>{t.deleted?Ze("instance deleted - cannot call any method"):n&&nt&&t(e)))},e.onModified=e=>{if(t.deleted)return Ze("instance deleted - cannot call any method"),null;const o=r.length;return r.push(e),function(e){return Object.freeze({unsubscribe:function(){n(e)}})}(o)},e.getMTime=()=>t.mtime,e.isA=e=>{let r=t.classHierarchy.length;for(;r--;)if(t.classHierarchy[r]===e)return!0;return!1},e.getClassName=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return t.classHierarchy[t.classHierarchy.length-1-e]},e.set=function(){let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]&&arguments[1],o=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=!1;return Object.keys(r).forEach(a=>{const s=o?null:e[`set${at(a)}`];s&&Array.isArray(r[a])&&s.length>1?i=s(...r[a])||i:s?i=s(r[a])||i:(-1!==["mtime"].indexOf(a)||n||et(`Warning: Set value to model directly ${a}, ${r[a]}`),i=t[a]!==r[a]||i,t[a]=r[a])}),i},e.get=function(){for(var e=arguments.length,r=new Array(e),n=0;n{o[e]=t[e]}),o},e.getReferenceByName=e=>t[e],e.delete=()=>{Object.keys(t).forEach(e=>delete t[e]),r.forEach((e,t)=>n(t)),t.deleted=!0},e.getState=()=>{if(t.deleted)return null;const r={...t,vtkClass:e.getClassName()};Object.keys(r).forEach(e=>{null===r[e]||void 0===r[e]||"_"===e[0]?delete r[e]:r[e].isA?r[e]=r[e].getState():Array.isArray(r[e])?r[e]=r[e].map(pt):function(e){return Object.values(nt).some(t=>e instanceof t)}(r[e])&&(r[e]=Array.from(r[e]))});const n={};return Object.keys(r).sort().forEach(e=>{n[e]=r[e]}),n.mtime&&delete n.mtime,n},e.shallowCopy=function(r){let n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(r.getClassName()!==e.getClassName())throw new Error(`Cannot ShallowCopy ${r.getClassName()} into ${e.getClassName()}`);const o=r.get(),i=Object.keys(t).sort();Object.keys(o).sort().forEach(e=>{const r=i.indexOf(e);-1===r?n&&Qe(`add ${e} in shallowCopy`):i.splice(r,1),t[e]=o[e]}),i.length&&n&&Qe(`Untouched keys: ${i.join(", ")}`),e.modified()},e.toJSON=function(){return e.getState()},e}const gt={object:(e,t,r)=>function(){return{...t[r.name]}}};function yt(e,t,r){r.forEach(r=>{if("object"==typeof r){const n=gt[r.type];e[`get${st(r.name)}`]=n?n(e,t,r):()=>t[r.name]}else e[`get${st(r)}`]=()=>t[r]})}const vt={enum(e,t,r){const n=`_on${st(r.name)}Changed`;return o=>{if("string"==typeof o){if(void 0!==r.enum[o])return t[r.name]!==r.enum[o]&&(t[r.name]=r.enum[o],e.modified(),!0);throw Ze(`Set Enum with invalid argument ${r}, ${o}`),new RangeError("Set Enum with invalid string argument")}if("number"==typeof o){if(t[r.name]!==o){if(-1!==Object.keys(r.enum).map(e=>r.enum[e]).indexOf(o)){const i=t[r.name];return t[r.name]=o,t[n]?.(e,t,o,i),e.modified(),!0}throw Ze(`Set Enum outside numeric range ${r}, ${o}`),new RangeError("Set Enum outside numeric range")}return!1}throw Ze(`Set Enum with invalid argument (String/Number) ${r}, ${o}`),new TypeError("Set Enum with invalid argument (String/Number)")}},object(e,t,r){1===r.params?.length&&et('Setter of type "object" with a single "param" field is not supported');const n=`_on${st(r.name)}Changed`;return function(){for(var o=arguments.length,i=new Array(o),a=0;a1&&r.params?.length?r.params.reduce((e,t,r)=>Object.assign(e,{[t]:i[r]}),{}):i[0],!ke(t[r.name],s)){const o=t[r.name];return t[r.name]=s,t[n]?.(e,t,s,o),e.modified(),!0}return!1}}};function bt(e){if("object"==typeof e){const t=vt[e.type];if(t)return(r,n)=>t(r,n,e);throw Ze(`No setter for field ${e}`),new TypeError("No setter for field")}return function(t,r){const n=`_on${st(e)}Changed`;return function(o){if(r.deleted)return Ze("instance deleted - cannot call any method"),!1;if(r[e]!==o){const i=r[e.name];return r[e]=o,r[n]?.(t,r,o,i),t.modified(),!0}return!1}}}function xt(e,t,r){r.forEach(r=>{"object"==typeof r?e[`set${st(r.name)}`]=bt(r)(e,t):e[`set${st(r)}`]=bt(r)(e,t)})}function _t(e,t,r){yt(e,t,r),xt(e,t,r)}function St(e,t,r){r.forEach(r=>{e[`get${st(r)}`]=()=>t[r]?Array.from(t[r]):t[r],e[`get${st(r)}ByReference`]=()=>t[r]})}function Ct(e,t,r,n){let o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:void 0;r.forEach(r=>{if(t[r]&&n&&t[r].length!==n)throw new RangeError(`Invalid initial number of values for array (${r})`);const i=`_on${st(r)}Changed`;e[`set${st(r)}`]=function(){if(t.deleted)return Ze("instance deleted - cannot call any method"),!1;for(var a=arguments.length,s=new Array(a),l=0;l=0)&&(c=c[0],d=!0),null==c)u=t[r]!==c;else{if(n&&c.length!==n){if(!(c.length{const n=t[r];e.forEach((e,t)=>{n[t]=e})}})}function Tt(e,t,r,n){let o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:void 0;St(e,t,r),Ct(e,t,r,n,o)}function wt(e,t,r){for(let e=0;e1&&void 0!==arguments[1]?arguments[1]:0;t.deleted?Ze("instance deleted - cannot call any method"):n>=t.numberOfInputs?Ze(`algorithm ${e.getClassName()} only has ${t.numberOfInputs} input ports. To add more input ports, use addInputData()`):(t.inputData[n]!==r||t.inputConnection[n])&&(t.inputData[n]=r,t.inputConnection[n]=null,e.modified&&e.modified())}function i(r){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(t.deleted)Ze("instance deleted - cannot call any method");else{if(n>=t.numberOfInputs){let r=`algorithm ${e.getClassName()} only has `;return r+=`${t.numberOfInputs}`,r+=" input ports. To add more input ports, use addInputConnection()",void Ze(r)}t.inputData[n]=null,t.inputConnection[n]=r}}function a(){let e=t.numberOfInputs;for(;e&&!t.inputData[e-1]&&!t.inputConnection[e-1];)e--;return e===t.numberOfInputs&&t.numberOfInputs++,e}function s(){let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return t.deleted?(Ze("instance deleted - cannot call any method"),null):(e.shouldUpdate()&&e.update(),t.output[r])}if(t.inputData?t.inputData=t.inputData.map(Ge):t.inputData=[],t.inputConnection?t.inputConnection=t.inputConnection.map(Ge):t.inputConnection=[],t.output?t.output=t.output.map(Ge):t.output=[],t.inputArrayToProcess?t.inputArrayToProcess=t.inputArrayToProcess.map(Ge):t.inputArrayToProcess=[],t.numberOfInputs=r,e.shouldUpdate=()=>{const r=e.getMTime();let o=1/0,i=n;for(;i--;){if(!t.output[i]||t.output[i].isDeleted())return!0;const e=t.output[i].getMTime();if(eo)return!0;return!1},t.numberOfInputs){let r=t.numberOfInputs;for(;r--;)t.inputData.push(null),t.inputConnection.push(null);e.setInputData=o,e.setInputConnection=i,e.addInputData=function(e){t.deleted?Ze("instance deleted - cannot call any method"):o(e,a())},e.addInputConnection=function(e){t.deleted?Ze("instance deleted - cannot call any method"):i(e,a())},e.getInputData=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return t.inputConnection[e]&&(t.inputData[e]=t.inputConnection[e]()),t.inputData[e]},e.getInputConnection=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return t.inputConnection[e]}}n&&(e.getOutputData=s,e.getOutputPort=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;const r=()=>s(t);return r.filter=e,r}),e.update=()=>{const r=[];if(t.numberOfInputs){let n=0;for(;nt.numberOfInputs,e.getNumberOfOutputPorts=()=>n||t.output.length,e.getInputArrayToProcess=e=>{const r=t.inputArrayToProcess[e],n=t.inputData[e];return r&&n?n[`get${r.fieldAssociation}`]().getArray(r.arrayName):null},e.setInputArrayToProcess=function(e,r,n){let o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"Scalars";for(;t.inputArrayToProcess.lengthn.apply(e,arguments),1-o);else if(n.apply(e,arguments)===Et)break}},e[`on${st(r)}`]=function(e){let o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!e.apply)return console.error(`Invalid callback for event ${r}`),null;if(t.deleted)return Ze("instance deleted - cannot call any method"),null;const s=i++;return n.push([s,e,o]),n.sort((e,t)=>t[2]-e[2]),function(e){return Object.freeze({unsubscribe:function(){a(e)}})}(s)},e.delete=()=>{o(),n.forEach(e=>{let[t]=e;return a(t)})}}function Pt(e,t){const r=function(){const t={};return e(t,{},arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),Object.freeze(t)};return t&&Ge.register(t,r),r}function It(){for(var e=arguments.length,t=new Array(e),r=0;r!!e).map(e=>e(...r))}}function Ot(e){return e&&e.isA&&e.isA("vtkObject")}function Nt(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[];if(Ot(e)){if(n.indexOf(e)>=0)return r;n.push(e);const o=t(e);void 0!==o&&r.push(o);const i=e.get();Object.keys(i).forEach(e=>{const o=i[e];Array.isArray(o)?o.forEach(e=>{Nt(e,t,r,n)}):Nt(o,t,r,n)})}return r}function Mt(e,t,r){var n=this;let o;const i=function(){for(var i=arguments.length,a=new Array(i),s=0;s{o=null,r||e.apply(l,a)},t),u&&e.apply(l,a)};return i.cancel=()=>clearTimeout(o),i}function Rt(e,t){let r=!1,n=null;function o(){r=!1,null!==n&&(i(...n),n=null)}function i(){for(var i=arguments.length,a=new Array(i),s=0;s2&&void 0!==arguments[2]?arguments[2]:{};t.keystore=Object.assign(t.keystore||{},r),e.setKey=(e,r)=>{t.keystore[e]=r},e.getKey=e=>t.keystore[e],e.getAllKeys=()=>Object.keys(t.keystore),e.deleteKey=e=>delete t.keystore[e],e.clearKeystore=()=>e.getAllKeys().forEach(e=>delete t.keystore[e])}let Bt=1;const Lt="__root__";function kt(e,t){Ft(e,t);const r=e.delete;t.proxyId=""+Bt++,t.ui=JSON.parse(JSON.stringify(t.ui||[])),yt(e,t,["proxyId","proxyGroup","proxyName"]),_t(e,t,["proxyManager"]);const n={},o={};function i(e,t){o[t]||(o[t]=[]);const r=o[t];for(let t=0;t0&&void 0!==arguments[0]?arguments[0]:Lt;const n=[],i=t.proxyId,s=function(){return o[arguments.length>0&&void 0!==arguments[0]?arguments[0]:Lt]}(r)||[];for(let t=0;t{t.ui=JSON.parse(JSON.stringify(r||[])),Object.keys(n).forEach(e=>delete n[e]),Object.keys(o).forEach(e=>delete o[e]),i(t.ui,Lt),e.modified()},e.updateProxyProperty=(e,t)=>{const r=n[e];r?Object.assign(r,t):n[e]={...t}},e.activate=()=>{if(t.proxyManager){const r=`setActive${st(e.getProxyGroup().slice(0,-1))}`;t.proxyManager[r]&&t.proxyManager[r](e)}},t.propertyLinkSubscribers={},e.registerPropertyLinkForGC=(e,r)=>{r in t.propertyLinkSubscribers||(t.propertyLinkSubscribers[r]=[]),t.propertyLinkSubscribers[r].push(e)},e.gcPropertyLinks=r=>{const n=t.propertyLinkSubscribers[r]||[];for(;n.length;)n.pop().unbind(e)},t.propertyLinkMap={},e.getPropertyLink=function(e){let r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(t.propertyLinkMap[e])return t.propertyLinkMap[e];let n=null;const o=[];let i=0,a=!1;function s(r){let s=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(a)return null;const l=[];let u=null;for(i=o.length;i--;){const e=o[i];e.instance===r?u=e:l.push(e)}if(!u)return null;const c=u.instance[`get${st(u.propertyName)}`]();if(!function(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r2&&void 0!==arguments[2]&&arguments[2];const a=r.onModified(s),u=o[0];return o.push({instance:r,propertyName:n,subscription:a}),i&&(t.propertyLinkMap[e].persistent&&void 0!==t.propertyLinkMap[e].value?r.set({[n]:t.propertyLinkMap[e].value}):u&&s(u.instance,!0)),{unsubscribe:()=>l(r,n)}},unbind:l,unsubscribe:function(){for(;o.length;)o.pop().subscription.unsubscribe()},persistent:r};return t.propertyLinkMap[e]=u,u},e.listPropertyNames=()=>a().map(e=>e.name),e.getPropertyByName=e=>a().find(t=>t.name===e),e.getPropertyDomainByName=e=>(n[e]||{}).domain,e.getProxySection=()=>({id:t.proxyId,name:t.proxyGroup,ui:t.ui,properties:a()}),e.delete=()=>{const n=Object.keys(t.propertyLinkMap);let o=n.length;for(;o--;)t.propertyLinkMap[n[o]].unsubscribe();Object.keys(t.propertyLinkSubscribers).forEach(e.gcPropertyLinks),r()},e.getState=()=>null,ft(function(){if(t.links)for(let r=0;r{for(;o.length;)o.pop().unsubscribe();n()}}function Vt(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};function o(e){const r=Object.keys(e);let n=r.length;for(;n--;){const o=r[n];t[o].set(e[o])}}t.this=e;const i=Object.keys(n);let a=i.length;for(;a--;){const s=i[a];t[s]=n[s];const l=r[s];e[`set${st(s)}`]=r=>{r!==t[s]&&(t[s]=r,o(l[r]),e.modified())}}i.length&&yt(e,t,i)}function Gt(e){let t=0,r=0,n=0,o=0;return"detail"in e&&(r=e.detail),"wheelDelta"in e&&(r=-e.wheelDelta/120),"wheelDeltaY"in e&&(r=-e.wheelDeltaY/120),"wheelDeltaX"in e&&(t=-e.wheelDeltaX/120),"axis"in e&&e.axis===e.HORIZONTAL_AXIS&&(t=r,r=0),n=10*t,o=10*r,"deltaY"in e&&(o=e.deltaY),"deltaX"in e&&(n=e.deltaX),(n||o)&&e.deltaMode&&(1===e.deltaMode?(n*=40,o*=40):(n*=800,o*=800)),n&&!t&&(t=n<1?-1:1),o&&!r&&(r=o<1?-1:1),{spinX:t,spinY:r||t,pixelX:n,pixelY:o||n}}var zt={algo:At,capitalize:at,chain:It,debounce:Mt,enumToString:function(e,t){return Object.keys(e).find(r=>e[r]===t)},event:Dt,EVENT_ABORT:Et,formatBytesToProperUnit:ut,formatNumbersWithThousandSeparator:ct,get:yt,getArray:St,getCurrentGlobalMTime:function(){return je},getStateArrayMapFunc:pt,isVtkObject:Ot,keystore:Ft,measurePromiseExecution:ht,moveToProtected:wt,newInstance:Pt,newTypedArray:ot,newTypedArrayFrom:it,normalizeWheel:Gt,obj:mt,proxy:kt,proxyPropertyMapping:Ut,proxyPropertyState:Vt,safeArrays:dt,set:xt,setArray:Ct,setGet:_t,setGetArray:Tt,setImmediate:ft,setLoggerFunction:qe,throttle:Rt,traverseInstanceTree:Nt,TYPED_ARRAYS:nt,uncapitalize:lt,VOID:He,vtkDebugMacro:Qe,vtkErrorMacro:Ze,vtkInfoMacro:Je,vtkLogMacro:Ye,vtkOnceErrorMacro:rt,vtkWarningMacro:et,objectSetterMap:vt,requiredParam:We},jt=Object.freeze({__proto__:null,requiredParam:We,VOID:He,setLoggerFunction:qe,vtkLogMacro:Ye,vtkInfoMacro:Je,vtkDebugMacro:Qe,vtkErrorMacro:Ze,vtkWarningMacro:et,vtkOnceErrorMacro:rt,TYPED_ARRAYS:nt,newTypedArray:ot,newTypedArrayFrom:it,capitalize:at,_capitalize:st,uncapitalize:lt,formatBytesToProperUnit:ut,formatNumbersWithThousandSeparator:ct,setImmediateVTK:ft,measurePromiseExecution:ht,obj:mt,get:yt,set:xt,setGet:_t,getArray:St,setArray:Ct,setGetArray:Tt,moveToProtected:wt,algo:At,EVENT_ABORT:Et,event:Dt,newInstance:Pt,chain:It,isVtkObject:Ot,traverseInstanceTree:Nt,debounce:Mt,throttle:Rt,keystore:Ft,proxy:kt,proxyPropertyMapping:Ut,proxyPropertyState:Vt,normalizeWheel:Gt,default:zt});const{vtkErrorMacro:Wt}=zt,Ht={renderable:null,myFactory:null,children:[],visited:!1};function Kt(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Ht,r),zt.obj(e,t),zt.event(e,t,"event"),t._renderableChildMap=new Map,zt.get(e,t,["visited"]),zt.setGet(e,t,["_parent","renderable","myFactory"]),zt.getArray(e,t,["children"]),zt.moveToProtected(e,t,["parent"]),function(e,t){function r(e,r){for(let n=0;n{},e.render=e=>{},e.traverse=r=>{const n=r.getTraverseOperation(),o=e[n];if(o)o(r);else{e.apply(r,!0);for(let e=0;e{const n=e[t.getOperation()];n&&n(r,t)},e.getViewNodeFor=function(r){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(n&&n.renderable===r)return n;if(t.renderable===r)return e;for(let e=0;et._parent?t._parent.isA(e)?t._parent:t._parent.getFirstAncestorOfType(e):null,e.getLastAncestorOfType=e=>t._parent?t._parent.getLastAncestorOfType(e)||(t._parent.isA(e)?t._parent:null):null,e.addMissingNode=r=>{if(!r)return;const n=t._renderableChildMap.get(r);if(void 0!==n)return n.setVisited(!0),n;const o=e.createViewNode(r);return o?(o.setParent(e),o.setVisited(!0),t._renderableChildMap.set(r,o),t.children.push(o),o):void 0},e.addMissingNodes=function(n){let o,i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(n&&n.length)for(let a=0;a{if(r&&r.length)for(let n=0;n{const r=t.children.findIndex(t=>t===e);if(r<0)return!1;const n=e.getRenderable();return n&&t._renderableChildMap.delete(n),e.delete(),t.children.splice(r,1),!0},e.prepareNodes=()=>{for(let e=0;e{t.visited=e},e.removeUnusedNodes=()=>{let e=0;for(let r=0;r{if(!t.myFactory)return Wt("Cannot create view nodes without my own factory"),null;const r=t.myFactory.createNode(e);return r&&r.setRenderable(e),r};const n=e.delete;e.delete=()=>{for(let e=0;e2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,$t,r),zt.obj(e,t),function(e,t){t.overrides||(t.overrides={}),t.classHierarchy.push("vtkViewNodeFactory"),e.createNode=r=>{if(r.isDeleted())return null;let n=0,o=r.getClassName(n++),i=!1;const a=Object.keys(t.overrides);for(;o&&!i;)-1!==a.indexOf(o)?i=!0:o=r.getClassName(n++);if(!i)return null;const s=t.overrides[o]();return s.setMyFactory(e),s}}(e,t)}var Yt={newInstance:zt.newInstance(qt,"vtkViewNodeFactory"),extend:qt};const Jt=Object.create(null);function Qt(e,t){Jt[e]=t}const Zt={};function er(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Zt,r),t.overrides=Jt,Yt.extend(e,t,r),function(e,t){t.classHierarchy.push("vtkOpenGLViewNodeFactory")}(0,t)}var tr={newInstance:zt.newInstance(er,"vtkOpenGLViewNodeFactory"),extend:er};const rr={context:null,lastRenderer:null,keyMatrixTime:null,keyMatrices:null};const nr=Pt(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,rr,r),Xt.extend(e,t,r),t.keyMatrixTime={},mt(t.keyMatrixTime),t.keyMatrices={normalMatrix:new Float64Array(9),vcpc:new Float64Array(16),wcvc:new Float64Array(16),wcpc:new Float64Array(16)},_t(e,t,["context","keyMatrixTime"]),function(e,t){t.classHierarchy.push("vtkOpenGLCamera"),e.buildPass=r=>{r&&(t._openGLRenderer=e.getFirstAncestorOfType("vtkOpenGLRenderer"),t._openGLRenderWindow=t._openGLRenderer.getParent(),t.context=t._openGLRenderWindow.getContext())},e.opaquePass=e=>{if(e){const e=t._openGLRenderer.getTiledSizeAndOrigin();t.context.viewport(e.lowerLeftU,e.lowerLeftV,e.usize,e.vsize),t.context.scissor(e.lowerLeftU,e.lowerLeftV,e.usize,e.vsize)}},e.translucentPass=e.opaquePass,e.zBufferPass=e.opaquePass,e.opaqueZBufferPass=e.opaquePass,e.volumePass=e.opaquePass,e.getKeyMatrices=r=>{if(r!==t.lastRenderer||t._openGLRenderWindow.getMTime()>t.keyMatrixTime.getMTime()||e.getMTime()>t.keyMatrixTime.getMTime()||r.getMTime()>t.keyMatrixTime.getMTime()||t.renderable.getMTime()>t.keyMatrixTime.getMTime()){d(t.keyMatrices.wcvc,t.renderable.getViewMatrix()),se(t.keyMatrices.normalMatrix,t.keyMatrices.wcvc),he(t.keyMatrices.normalMatrix,t.keyMatrices.normalMatrix),m(t.keyMatrices.wcvc,t.keyMatrices.wcvc);const e=t._openGLRenderer.getAspectRatio();d(t.keyMatrices.vcpc,t.renderable.getProjectionMatrix(e,-1,1)),m(t.keyMatrices.vcpc,t.keyMatrices.vcpc),b(t.keyMatrices.wcpc,t.keyMatrices.vcpc,t.keyMatrices.wcvc),t.keyMatrixTime.modified(),t.lastRenderer=r}return t.keyMatrices}}(e,t)});Qt("vtkCamera",nr);const{vtkDebugMacro:or}=jt,ir={context:null,_openGLRenderWindow:null,selector:null};const ar=Pt(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,ir,r),Xt.extend(e,t,r),yt(e,t,["shaderCache"]),_t(e,t,["selector"]),wt(0,t,["openGLRenderWindow"]),function(e,t){t.classHierarchy.push("vtkOpenGLRenderer"),e.buildPass=r=>{if(r){if(!t.renderable)return;e.updateLights(),e.prepareNodes(),e.addMissingNode(t.renderable.getActiveCamera()),e.addMissingNodes(t.renderable.getViewPropsWithNestedProps(),!0),e.removeUnusedNodes()}},e.updateLights=()=>{let e=0;const r=t.renderable.getLightsByReference();for(let t=0;t0&&e++;return e||(or("No lights are on, creating one."),t.renderable.createLight()),e},e.zBufferPass=r=>{if(r){let r=0;const n=t.context;t.renderable.getTransparent()||(t.context.clearColor(1,0,0,1),r|=n.COLOR_BUFFER_BIT),t.renderable.getPreserveDepthBuffer()||(n.clearDepth(1),r|=n.DEPTH_BUFFER_BIT,t.context.depthMask(!0));const o=e.getTiledSizeAndOrigin();n.enable(n.SCISSOR_TEST),n.scissor(o.lowerLeftU,o.lowerLeftV,o.usize,o.vsize),n.viewport(o.lowerLeftU,o.lowerLeftV,o.usize,o.vsize),n.colorMask(!0,!0,!0,!0),r&&n.clear(r),n.enable(n.DEPTH_TEST)}},e.opaqueZBufferPass=t=>e.zBufferPass(t),e.cameraPass=t=>{t&&e.clear()},e.getAspectRatio=()=>{const e=t._parent.getSizeByReference(),r=t.renderable.getViewportByReference();return e[0]*(r[2]-r[0])/((r[3]-r[1])*e[1])},e.getTiledSizeAndOrigin=()=>{const e=t.renderable.getViewportByReference(),r=[0,0,1,1],n=e[0]-r[0],o=e[1]-r[1],i=t._parent.normalizedDisplayToDisplay(n,o),a=Math.round(i[0]),s=Math.round(i[1]),l=e[2]-r[0],u=e[3]-r[1],c=t._parent.normalizedDisplayToDisplay(l,u);let d=Math.round(c[0])-a,p=Math.round(c[1])-s;return d<0&&(d=0),p<0&&(p=0),{usize:d,vsize:p,lowerLeftU:a,lowerLeftV:s}},e.clear=()=>{let r=0;const n=t.context;if(!t.renderable.getTransparent()){const e=t.renderable.getBackgroundByReference();n.clearColor(e[0],e[1],e[2],e[3]),r|=n.COLOR_BUFFER_BIT}t.renderable.getPreserveDepthBuffer()||(n.clearDepth(1),r|=n.DEPTH_BUFFER_BIT,n.depthMask(!0)),n.colorMask(!0,!0,!0,!0);const o=e.getTiledSizeAndOrigin();n.enable(n.SCISSOR_TEST),n.scissor(o.lowerLeftU,o.lowerLeftV,o.usize,o.vsize),n.viewport(o.lowerLeftU,o.lowerLeftV,o.usize,o.vsize),r&&n.clear(r),n.enable(n.DEPTH_TEST)},e.releaseGraphicsResources=()=>{null!==t.selector&&t.selector.releaseGraphicsResources(),t.renderable&&t.renderable.getViewProps().forEach(e=>{e.modified()})},e.setOpenGLRenderWindow=r=>{t._openGLRenderWindow!==r&&(e.releaseGraphicsResources(),t._openGLRenderWindow=r,t.context=null,r&&(t.context=t._openGLRenderWindow.getContext()))}}(e,t)},"vtkOpenGLRenderer");Qt("vtkRenderer",ar);const sr={context:null,keyMatrixTime:null,keyMatrices:null,activeTextures:null};const lr=Pt(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,sr,r),Xt.extend(e,t,r),t.keyMatrixTime={},mt(t.keyMatrixTime,{mtime:0}),t.keyMatrices={normalMatrix:pe(new Float64Array(9)),mcwc:h(new Float64Array(16))},_t(e,t,["context"]),yt(e,t,["activeTextures"]),function(e,t){t.classHierarchy.push("vtkOpenGLActor"),e.buildPass=r=>{if(r){t._openGLRenderWindow=e.getLastAncestorOfType("vtkOpenGLRenderWindow"),t._openGLRenderer=e.getFirstAncestorOfType("vtkOpenGLRenderer"),t.context=t._openGLRenderWindow.getContext(),e.prepareNodes(),e.addMissingNodes(t.renderable.getTextures()),e.addMissingNode(t.renderable.getMapper()),e.removeUnusedNodes(),t.ogltextures=null,t.activeTextures=null;for(let e=0;e{t.renderable&&t.renderable.getNestedVisibility()&&(!t._openGLRenderer.getSelector()||t.renderable.getNestedPickable())&&(e.apply(r,!0),t.oglmapper.traverse(r),e.apply(r,!1))},e.traverseOpaqueZBufferPass=t=>e.traverseOpaquePass(t),e.traverseOpaquePass=r=>{t.renderable&&t.renderable.getNestedVisibility()&&t.renderable.getIsOpaque()&&(!t._openGLRenderer.getSelector()||t.renderable.getNestedPickable())&&(e.apply(r,!0),t.oglmapper.traverse(r),e.apply(r,!1))},e.traverseTranslucentPass=r=>{!t.renderable||!t.renderable.getNestedVisibility()||t.renderable.getIsOpaque()||t._openGLRenderer.getSelector()&&!t.renderable.getNestedPickable()||(e.apply(r,!0),t.oglmapper.traverse(r),e.apply(r,!1))},e.activateTextures=()=>{if(t.ogltextures){t.activeTextures=[];for(let e=0;e{if(e){if(!t.renderable||!t.renderable.getVisibility())return;t.renderable.getIsOpaque()?r.incrementOpaqueActorCount():r.incrementTranslucentActorCount()}},e.zBufferPass=(t,r)=>e.opaquePass(t,r),e.opaqueZBufferPass=(t,r)=>e.opaquePass(t,r),e.opaquePass=(r,n)=>{if(r)t.context.depthMask(!0),e.activateTextures();else if(t.activeTextures)for(let e=0;e{if(r)t.context.depthMask(t._openGLRenderer.getSelector()&&t.renderable.getNestedPickable()),e.activateTextures();else if(t.activeTextures)for(let e=0;e(t.renderable.getMTime()>t.keyMatrixTime.getMTime()&&(t.renderable.computeMatrix(),d(t.keyMatrices.mcwc,t.renderable.getMatrix()),m(t.keyMatrices.mcwc,t.keyMatrices.mcwc),t.renderable.getIsIdentity()?pe(t.keyMatrices.normalMatrix):(se(t.keyMatrices.normalMatrix,t.keyMatrices.mcwc),he(t.keyMatrices.normalMatrix,t.keyMatrices.normalMatrix),fe(t.keyMatrices.normalMatrix,t.keyMatrices.normalMatrix)),t.keyMatrixTime.modified()),t.keyMatrices)}(e,t)});Qt("vtkActor",lr);const ur={context:null,activeTextures:null};const cr=Pt(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,ur,r),Xt.extend(e,t,r),_t(e,t,["context"]),yt(e,t,["activeTextures"]),function(e,t){t.classHierarchy.push("vtkOpenGLActor2D"),e.buildPass=r=>{if(r){if(!t.renderable)return;t._openGLRenderWindow=e.getLastAncestorOfType("vtkOpenGLRenderWindow"),t._openGLRenderer=e.getFirstAncestorOfType("vtkOpenGLRenderer"),t.context=t._openGLRenderWindow.getContext(),e.prepareNodes(),e.addMissingNodes(t.renderable.getTextures()),e.addMissingNode(t.renderable.getMapper()),e.removeUnusedNodes(),t.ogltextures=null,t.activeTextures=null;for(let e=0;e{if(e){if(!t.renderable||!t.renderable.getVisibility())return;r.incrementOverlayActorCount()}},e.traverseOpaquePass=r=>{t.oglmapper&&t.renderable&&t.renderable.getNestedVisibility()&&t.renderable.getIsOpaque()&&(!t._openGLRenderer.getSelector()||t.renderable.getNestedPickable())&&(e.apply(r,!0),t.oglmapper.traverse(r),e.apply(r,!1))},e.traverseTranslucentPass=r=>{t.oglmapper&&t.renderable&&t.renderable.getNestedVisibility()&&!t.renderable.getIsOpaque()&&(!t._openGLRenderer.getSelector()||t.renderable.getNestedPickable())&&(e.apply(r,!0),t.oglmapper.traverse(r),e.apply(r,!1))},e.traverseOverlayPass=r=>{t.oglmapper&&t.renderable&&t.renderable.getNestedVisibility()&&(!t._openGLRenderer.getSelector()||t.renderable.getNestedPickable)&&(e.apply(r,!0),t.oglmapper.traverse(r),e.apply(r,!1))},e.activateTextures=()=>{if(t.ogltextures){t.activeTextures=[];for(let e=0;e{if(r)t.context.depthMask(!0),e.activateTextures();else if(t.activeTextures)for(let e=0;e{if(r)t.context.depthMask(!1),e.activateTextures();else if(t.activeTextures)for(let e=0;e{if(r)t.context.depthMask(!0),e.activateTextures();else if(t.activeTextures)for(let e=0;e0&&(i=1/Math.sqrt(i)),e[0]=t[0]*i,e[1]=t[1]*i,e[2]=t[2]*i,e}function xr(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function _r(e,t,r){var n=t[0],o=t[1],i=t[2],a=r[0],s=r[1],l=r[2];return e[0]=o*l-i*s,e[1]=i*a-n*l,e[2]=n*s-o*a,e}function Sr(e,t,r){var n=t[0],o=t[1],i=t[2],a=r[3]*n+r[7]*o+r[11]*i+r[15];return a=a||1,e[0]=(r[0]*n+r[4]*o+r[8]*i+r[12])/a,e[1]=(r[1]*n+r[5]*o+r[9]*i+r[13])/a,e[2]=(r[2]*n+r[6]*o+r[10]*i+r[14])/a,e}function Cr(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]}function Tr(e,t){var r=e[0],n=e[1],o=e[2],a=t[0],s=t[1],l=t[2];return Math.abs(r-a)<=i*Math.max(1,Math.abs(r),Math.abs(a))&&Math.abs(n-s)<=i*Math.max(1,Math.abs(n),Math.abs(s))&&Math.abs(o-l)<=i*Math.max(1,Math.abs(o),Math.abs(l))}Qt("vtkActor2D",cr);var wr=yr,Ar=pr;dr();const Er=Math.sqrt(50),Dr=Math.sqrt(10),Pr=Math.sqrt(2);function Ir(e,t,r){const n=(t-e)/Math.max(0,r),o=Math.floor(Math.log10(n)),i=n/Math.pow(10,o),a=i>=Er?10:i>=Dr?5:i>=Pr?2:1;let s,l,u;return o<0?(u=Math.pow(10,-o)/a,s=Math.round(e*u),l=Math.round(t*u),s/ut&&--l,u=-u):(u=Math.pow(10,o)*a,s=Math.round(e/u),l=Math.round(t/u),s*ut&&--l),lt?1:e>=t?0:NaN}function Mr(e,t){return null==e||null==t?NaN:te?1:t>=e?0:NaN}function Rr(e){let t,r,n;function o(e,n,o=0,i=e.length){if(o>>1;r(e[t],n)<0?o=t+1:i=t}while(oNr(e(t),r),n=(t,r)=>e(t)-r):(t=e===Nr||e===Mr?e:Fr,r=e,n=e),{left:o,center:function(e,t,r=0,i=e.length){const a=o(e,t,r,i-1);return a>r&&n(e[a-1],t)>-n(e[a],t)?a-1:a},right:function(e,n,o=0,i=e.length){if(o>>1;r(e[t],n)<=0?o=t+1:i=t}while(o>8&15|t>>4&240,t>>4&15|240&t,(15&t)<<4|15&t,1):8===r?an(t>>24&255,t>>16&255,t>>8&255,(255&t)/255):4===r?an(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|240&t,((15&t)<<4|15&t)/255):null):(t=$r.exec(e))?new ln(t[1],t[2],t[3],1):(t=qr.exec(e))?new ln(255*t[1]/100,255*t[2]/100,255*t[3]/100,1):(t=Yr.exec(e))?an(t[1],t[2],t[3],t[4]):(t=Jr.exec(e))?an(255*t[1]/100,255*t[2]/100,255*t[3]/100,t[4]):(t=Qr.exec(e))?hn(t[1],t[2]/100,t[3]/100,1):(t=Zr.exec(e))?hn(t[1],t[2]/100,t[3]/100,t[4]):en.hasOwnProperty(e)?on(en[e]):"transparent"===e?new ln(NaN,NaN,NaN,0):null}function on(e){return new ln(e>>16&255,e>>8&255,255&e,1)}function an(e,t,r,n){return n<=0&&(e=t=r=NaN),new ln(e,t,r,n)}function sn(e,t,r,n){return 1===arguments.length?((o=e)instanceof Gr||(o=nn(o)),o?new ln((o=o.rgb()).r,o.g,o.b,o.opacity):new ln):new ln(e,t,r,null==n?1:n);var o}function ln(e,t,r,n){this.r=+e,this.g=+t,this.b=+r,this.opacity=+n}function un(){return`#${fn(this.r)}${fn(this.g)}${fn(this.b)}`}function cn(){const e=dn(this.opacity);return`${1===e?"rgb(":"rgba("}${pn(this.r)}, ${pn(this.g)}, ${pn(this.b)}${1===e?")":`, ${e})`}`}function dn(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function pn(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function fn(e){return((e=pn(e))<16?"0":"")+e.toString(16)}function hn(e,t,r,n){return n<=0?e=t=r=NaN:r<=0||r>=1?e=t=NaN:t<=0&&(e=NaN),new gn(e,t,r,n)}function mn(e){if(e instanceof gn)return new gn(e.h,e.s,e.l,e.opacity);if(e instanceof Gr||(e=nn(e)),!e)return new gn;if(e instanceof gn)return e;var t=(e=e.rgb()).r/255,r=e.g/255,n=e.b/255,o=Math.min(t,r,n),i=Math.max(t,r,n),a=NaN,s=i-o,l=(i+o)/2;return s?(a=t===i?(r-n)/s+6*(r0&&l<1?0:a,new gn(a,s,l,e.opacity)}function gn(e,t,r,n){this.h=+e,this.s=+t,this.l=+r,this.opacity=+n}function yn(e){return(e=(e||0)%360)<0?e+360:e}function vn(e){return Math.max(0,Math.min(1,e||0))}function bn(e,t,r){return 255*(e<60?t+(r-t)*e/60:e<180?r:e<240?t+(r-t)*(240-e)/60:t)}function xn(e,t,r,n,o){var i=e*e,a=i*e;return((1-3*e+3*i-a)*t+(4-6*i+3*a)*r+(1+3*e+3*i-3*a)*n+a*o)/6}Ur(Gr,nn,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:tn,formatHex:tn,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return mn(this).formatHsl()},formatRgb:rn,toString:rn}),Ur(ln,sn,Vr(Gr,{brighter(e){return e=null==e?jr:Math.pow(jr,e),new ln(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=null==e?zr:Math.pow(zr,e),new ln(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new ln(pn(this.r),pn(this.g),pn(this.b),dn(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:un,formatHex:un,formatHex8:function(){return`#${fn(this.r)}${fn(this.g)}${fn(this.b)}${fn(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:cn,toString:cn})),Ur(gn,function(e,t,r,n){return 1===arguments.length?mn(e):new gn(e,t,r,null==n?1:n)},Vr(Gr,{brighter(e){return e=null==e?jr:Math.pow(jr,e),new gn(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=null==e?zr:Math.pow(zr,e),new gn(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+360*(this.h<0),t=isNaN(e)||isNaN(this.s)?0:this.s,r=this.l,n=r+(r<.5?r:1-r)*t,o=2*r-n;return new ln(bn(e>=240?e-240:e+120,o,n),bn(e,o,n),bn(e<120?e+240:e-120,o,n),this.opacity)},clamp(){return new gn(yn(this.h),vn(this.s),vn(this.l),dn(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=dn(this.opacity);return`${1===e?"hsl(":"hsla("}${yn(this.h)}, ${100*vn(this.s)}%, ${100*vn(this.l)}%${1===e?")":`, ${e})`}`}}));const _n=e=>()=>e;function Sn(e,t){var r=t-e;return r?function(e,t){return function(r){return e+r*t}}(e,r):_n(isNaN(e)?t:e)}const Cn=function e(t){var r=function(e){return 1===(e=+e)?Sn:function(t,r){return r-t?function(e,t,r){return e=Math.pow(e,r),t=Math.pow(t,r)-e,r=1/r,function(n){return Math.pow(e+n*t,r)}}(t,r,e):_n(isNaN(t)?r:t)}}(t);function n(e,t){var n=r((e=sn(e)).r,(t=sn(t)).r),o=r(e.g,t.g),i=r(e.b,t.b),a=Sn(e.opacity,t.opacity);return function(t){return e.r=n(t),e.g=o(t),e.b=i(t),e.opacity=a(t),e+""}}return n.gamma=e,n}(1);function Tn(e){return function(t){var r,n,o=t.length,i=new Array(o),a=new Array(o),s=new Array(o);for(r=0;r=1?(r=1,t-1):Math.floor(r*t),o=e[n],i=e[n+1],a=n>0?e[n-1]:2*o-i,s=ni&&(o=t.slice(i,o),s[a]?s[a]+=o:s[++a]=o),(r=r[0])===(n=n[0])?s[a]?s[a]+=n:s[++a]=n:(s[++a]=null,l.push({i:a,x:En(r,n)})),i=In.lastIndex;return i=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Wn(e){if(!(t=jn.exec(e)))throw new Error("invalid format: "+e);var t;return new Hn({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}function Hn(e){this.fill=void 0===e.fill?" ":e.fill+"",this.align=void 0===e.align?">":e.align+"",this.sign=void 0===e.sign?"-":e.sign+"",this.symbol=void 0===e.symbol?"":e.symbol+"",this.zero=!!e.zero,this.width=void 0===e.width?void 0:+e.width,this.comma=!!e.comma,this.precision=void 0===e.precision?void 0:+e.precision,this.trim=!!e.trim,this.type=void 0===e.type?"":e.type+""}function Kn(e,t){if(!isFinite(e)||0===e)return null;var r=(e=t?e.toExponential(t-1):e.toExponential()).indexOf("e"),n=e.slice(0,r);return[n.length>1?n[0]+n.slice(2):n,+e.slice(r+1)]}function Xn(e){return(e=Kn(Math.abs(e)))?e[1]:NaN}function $n(e,t){var r=Kn(e,t);if(!r)return e+"";var n=r[0],o=r[1];return o<0?"0."+new Array(-o).join("0")+n:n.length>o+1?n.slice(0,o+1)+"."+n.slice(o+1):n+new Array(o-n.length+2).join("0")}Wn.prototype=Hn.prototype,Hn.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(void 0===this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(void 0===this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type};const qn={"%":(e,t)=>(100*e).toFixed(t),b:e=>Math.round(e).toString(2),c:e=>e+"",d:function(e){return Math.abs(e=Math.round(e))>=1e21?e.toLocaleString("en").replace(/,/g,""):e.toString(10)},e:(e,t)=>e.toExponential(t),f:(e,t)=>e.toFixed(t),g:(e,t)=>e.toPrecision(t),o:e=>Math.round(e).toString(8),p:(e,t)=>$n(100*e,t),r:$n,s:function(e,t){var r=Kn(e,t);if(!r)return zn=void 0,e.toPrecision(t);var n=r[0],o=r[1],i=o-(zn=3*Math.max(-8,Math.min(8,Math.floor(o/3))))+1,a=n.length;return i===a?n:i>a?n+new Array(i-a+1).join("0"):i>0?n.slice(0,i)+"."+n.slice(i):"0."+new Array(1-i).join("0")+Kn(e,Math.max(0,t+i-1))[0]},X:e=>Math.round(e).toString(16).toUpperCase(),x:e=>Math.round(e).toString(16)};function Yn(e){return e}var Jn,Qn,Zn,eo=Array.prototype.map,to=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function ro(e){var t=e.domain;return e.ticks=function(e){var r=t();return function(e,t,r){if(!((r=+r)>0))return[];if((e=+e)===(t=+t))return[e];const n=t=o))return[];const s=i-o+1,l=new Array(s);if(n)if(a<0)for(let e=0;e0;){if((o=Or(l,u,r))===n)return i[a]=l,i[s]=u,t(i);if(o>0)l=Math.floor(l/o)*o,u=Math.ceil(u/o)*o;else{if(!(o<0))break;l=Math.ceil(l*o)/o,u=Math.floor(u*o)/o}n=o}return e},e}function no(){var e=function(){var e,t,r,n,o,i,a=Bn,s=Bn,l=Mn,u=Ln;function c(){var e,t,r,l=Math.min(a.length,s.length);return u!==Ln&&(e=a[0],t=a[l-1],e>t&&(r=e,e=t,t=r),u=function(r){return Math.max(e,Math.min(t,r))}),n=l>2?Vn:Un,o=i=null,d}function d(t){return null==t||isNaN(t=+t)?r:(o||(o=n(a.map(e),s,l)))(e(u(t)))}return d.invert=function(r){return u(t((i||(i=n(s,a.map(e),En)))(r)))},d.domain=function(e){return arguments.length?(a=Array.from(e,Fn),c()):a.slice()},d.range=function(e){return arguments.length?(s=Array.from(e),c()):s.slice()},d.rangeRound=function(e){return s=Array.from(e),l=Rn,c()},d.clamp=function(e){return arguments.length?(u=!!e||Ln,c()):u!==Ln},d.interpolate=function(e){return arguments.length?(l=e,c()):l},d.unknown=function(e){return arguments.length?(r=e,d):r},function(r,n){return e=r,t=n,c()}}()(Ln,Ln);return e.copy=function(){return t=e,no().domain(t.domain()).range(t.range()).interpolate(t.interpolate()).clamp(t.clamp()).unknown(t.unknown());var t},Gn.apply(e,arguments),ro(e)}Jn=function(e){var t,r,n=void 0===e.grouping||void 0===e.thousands?Yn:(t=eo.call(e.grouping,Number),r=e.thousands+"",function(e,n){for(var o=e.length,i=[],a=0,s=t[0],l=0;o>0&&s>0&&(l+s+1>n&&(s=Math.max(1,n-l)),i.push(e.substring(o-=s,o+s)),!((l+=s+1)>n));)s=t[a=(a+1)%t.length];return i.reverse().join(r)}),o=void 0===e.currency?"":e.currency[0]+"",i=void 0===e.currency?"":e.currency[1]+"",a=void 0===e.decimal?".":e.decimal+"",s=void 0===e.numerals?Yn:function(e){return function(t){return t.replace(/[0-9]/g,function(t){return e[+t]})}}(eo.call(e.numerals,String)),l=void 0===e.percent?"%":e.percent+"",u=void 0===e.minus?"−":e.minus+"",c=void 0===e.nan?"NaN":e.nan+"";function d(e,t){var r=(e=Wn(e)).fill,d=e.align,p=e.sign,f=e.symbol,h=e.zero,m=e.width,g=e.comma,y=e.precision,v=e.trim,b=e.type;"n"===b?(g=!0,b="g"):qn[b]||(void 0===y&&(y=12),v=!0,b="g"),(h||"0"===r&&"="===d)&&(h=!0,r="0",d="=");var x=(t&&void 0!==t.prefix?t.prefix:"")+("$"===f?o:"#"===f&&/[boxX]/.test(b)?"0"+b.toLowerCase():""),_=("$"===f?i:/[%p]/.test(b)?l:"")+(t&&void 0!==t.suffix?t.suffix:""),S=qn[b],C=/[defgprs%]/.test(b);function T(e){var t,o,i,l=x,f=_;if("c"===b)f=S(e)+f,e="";else{var T=(e=+e)<0||1/e<0;if(e=isNaN(e)?c:S(Math.abs(e),y),v&&(e=function(e){e:for(var t,r=e.length,n=1,o=-1;n0&&(o=0)}return o>0?e.slice(0,o)+e.slice(t+1):e}(e)),T&&0===+e&&"+"!==p&&(T=!1),l=(T?"("===p?p:u:"-"===p||"("===p?"":p)+l,f=("s"!==b||isNaN(e)||void 0===zn?"":to[8+zn/3])+f+(T&&"("===p?")":""),C)for(t=-1,o=e.length;++t(i=e.charCodeAt(t))||i>57){f=(46===i?a+e.slice(t+1):e.slice(t))+f,e=e.slice(0,t);break}}g&&!h&&(e=n(e,1/0));var w=l.length+e.length+f.length,A=w>1)+l+e+f+A.slice(w);break;default:e=A+l+e+f}return s(e)}return y=void 0===y?6:/[gprs]/.test(b)?Math.max(1,Math.min(21,y)):Math.max(0,Math.min(20,y)),T.toString=function(){return e+""},T}return{format:d,formatPrefix:function(e,t){var r=3*Math.max(-8,Math.min(8,Math.floor(Xn(t)/3))),n=Math.pow(10,-r),o=d(((e=Wn(e)).type="f",e),{suffix:to[8+r/3]});return function(e){return o(n*e)}}}}({thousands:",",grouping:[3],currency:["$",""]}),Qn=Jn.format,Zn=Jn.formatPrefix;var oo=r(391);const io=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],ao=[1,0,0,0,1,0,0,0,1],so=1e-6,lo=1e-12,{vtkErrorMacro:uo,vtkWarningMacro:co}=zt;let po=0;function fo(e){return()=>uo(`vtkMath::${e} - NOT IMPLEMENTED`)}function ho(e,t,r,n){let o;for(let i=0;i0&&void 0!==arguments[0]?arguments[0]:3;const t=Array(e);for(let r=0;r1&&void 0!==arguments[1]?arguments[1]:3;switch(t){case 1:return Math.abs(e);case 2:return Math.sqrt(e[0]*e[0]+e[1]*e[1]);case 3:return Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);default:{let r=0;for(let n=0;n2&&void 0!==arguments[2]?arguments[2]:so;return e.length===t.length&&e.every(function(e,n){return Math.abs(e-t[n])<=r})}const $o=Xo;function qo(e){for(let t=0;t<3;t++)e[3*t]=e[3*t+1]=e[3*t+2]=0,e[3*t+t]=1}function Yo(e,t){for(let r=0;r1&&void 0!==arguments[1]?arguments[1]:0;if(!`${e}`.includes("e"))return+`${Math.round(`${e}e+${t}`)}e-${t}`;const r=`${e}`.split("e");let n="";return+r[1]+t>0&&(n="+"),+`${Math.round(`${+r[0]}e${n}${+r[1]+t}`)}e-${t}`}function Zo(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[0,0,0],r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return t[0]=Qo(e[0],r),t[1]=Qo(e[1],r),t[2]=Qo(e[2],r),t}function ei(e,t,r,n){let o,i,a,s,l,u,c,d,p,f,h,m,g,y,v,b;const x=go(t),_=go(t),S=(e,t,r)=>{y=e[t],g=e[r],e[t]=y-m*(g+y*f),e[r]=g+m*(y-g*f)};for(Yo(t,n),l=0;l3&&Math.abs(r[l])+y===Math.abs(r[l])&&Math.abs(r[s])+y===Math.abs(r[s]))e[l*t+s]=0;else if(Math.abs(e[l*t+s])>c){for(g=r[s]-r[l],Math.abs(g)+y===Math.abs(g)?p=e[l*t+s]/g:(d=.5*g/e[l*t+s],p=1/(Math.abs(d)+Math.sqrt(1+d*d)),d<0&&(p=-p)),v=1/Math.sqrt(1+p*p),m=p*v,f=m/(1+v),g=p*e[l*t+s],_[l]-=g,_[s]+=g,r[l]-=g,r[s]+=g,e[l*t+s]=0,i=0;i<=l-1;i++)S(e,i*t+l,i*t+s);for(i=l+1;i<=s-1;i++)S(e,l*t+i,i*t+s);for(i=s+1;i=20)return co("vtkMath::Jacobi: Error extracting eigenfunctions"),0;for(i=0;i=b||Math.abs(r[o]-b)>1)+(1&t);for(u=0,o=0;o=0&&u++;if(un?i:n,o=a>o?a:o,r[e]=1,0!==o&&(r[e]/=o)}const i=Math.abs(t[0])*r[0],a=Math.abs(t[3])*r[1],s=Math.abs(t[6])*r[2];n[0]=0,o=i,a>=o&&(o=a,n[0]=1),s>=o&&(n[0]=2),0!==n[0]&&(mo(t,3,n[0],0),r[n[0]]=r[0]);const l=Math.abs(t[4])*r[1],u=Math.abs(t[7])*r[2];n[1]=1,o=l,u>=o&&(n[1]=2,mo(t,3,1,2)),n[2]=2;let c=0;if(Ko(t)<0){c=1;for(let e=0;e<9;e++)t[e]=-t[e]}const d=go(4);if(ti(t,d),Jo(d,t),c)for(let e=0;e<9;e++)t[e]=-t[e];1!==n[1]&&mo(t,3,n[1],1),0!==n[0]&&mo(t,3,n[0],0)}function ni(e,t,r){let n,o,i,a,s,l;if(ei([...e],3,t,r),t[0]!==t[1]||t[0]!==t[2]){for(Ho(r,r),n=0;n<3;n++)if(t[(n+1)%3]===t[(n+2)%3]){for(l=Math.abs(r[3*n]),a=0,o=1;o<3;o++)l<(s=Math.abs(r[3*n+o]))&&(l=s,a=o);a!==n&&(s=t[a],t[a]=t[n],t[n]=s,ho(r,3,n,a)),r[3*a+a]<0&&(r[3*a]=-r[3*a],r[3*a+1]=-r[3*a+1],r[3*a+2]=-r[3*a+2]),o=(a+1)%3,i=(a+2)%3,r[3*o]=0,r[3*o+1]=0,r[3*o+2]=0,r[3*o+o]=1;const e=Fo([r[3*a],r[3*a+1],r[3*a+2]],[r[3*o],r[3*o+1],r[3*o+2]],[]);Lo(e);const u=Fo(e,[r[3*a],r[3*a+1],r[3*a+2]],[]);for(let t=0;t<3;t++)r[3*i+t]=e[t],r[3*o+t]=u[t];return void Ho(r,r)}for(l=Math.abs(r[0]),a=0,n=1;n<3;n++)l<(s=Math.abs(r[3*n]))&&(l=s,a=n);if(0!==a){const e=t[a];t[a]=t[0],t[0]=e,ho(r,3,a,0)}if(Math.abs(r[4])a&&(a=u);if(0===a)return co("Unable to factor linear system"),0;d[n]=1/a}for(o=0;o=a&&(a=l,c=n)}if(o!==c){for(i=0;i=0)for(i=a;i<=o-1;i++)l-=e[o*n+i]*r[i];else 0!==l&&(a=o);r[o]=l}for(o=n-1;o>=0;o--){for(l=r[o],i=o+1;i4&&void 0!==arguments[4]?arguments[4]:null;const o=(arguments.length>3&&void 0!==arguments[3]?arguments[3]:null)||go(r),i=n||go(r);if(0===oi(e,o,r))return null;for(let n=0;nl?l=i:il?l=a:a0?(l-u)/l:0,n>0?(r=o===l?s*(i-a)/(l-u):i===l?1/3+s*(a-o)/(l-u):2/3+s*(o-i)/(l-u),r<0&&(r+=1)):r=0,t[0]=r,t[1]=n,t[2]=c}function ci(e,t){const[r,n,o]=e,i=1/3,a=1/6,s=2/3,l=5/6;let u,c,d;r>a&&r<=i?(c=1,u=(i-r)/a,d=0):r>i&&r<=.5?(c=1,d=(r-i)/a,u=0):r>.5&&r<=s?(d=1,c=(s-r)/a,u=0):r>s&&r<=l?(d=1,u=(r-s)/a,c=0):r>l&&r<=1?(u=1,d=(1-r)/a,c=0):(u=1,c=r/a,d=0),u=n*u+(1-n),c=n*c+(1-n),d=n*d+(1-n),u*=o,c*=o,d*=o,t[0]=u,t[1]=c,t[2]=d}function di(e,t){const[r,n,o]=e;let i=(r+16)/116,a=n/500+i,s=i-o/200;i**3>.008856?i**=3:i=(i-16/116)/7.787,a**3>.008856?a**=3:a=(a-16/116)/7.787,s**3>.008856?s**=3:s=(s-16/116)/7.787,t[0]=.9505*a,t[1]=1*i,t[2]=1.089*s}function pi(e,t){const[r,n,o]=e;let i=r/.9505,a=n/1,s=o/1.089;i>.008856?i**=1/3:i=7.787*i+16/116,a>.008856?a**=1/3:a=7.787*a+16/116,s>.008856?s**=1/3:s=7.787*s+16/116,t[0]=116*a-16,t[1]=500*(i-a),t[2]=200*(a-s)}function fi(e,t){const[r,n,o]=e;let i=3.2406*r+-1.5372*n+-.4986*o,a=-.9689*r+1.8758*n+.0415*o,s=.0557*r+-.204*n+1.057*o;i>.0031308?i=1.055*i**(1/2.4)-.055:i*=12.92,a>.0031308?a=1.055*a**(1/2.4)-.055:a*=12.92,s>.0031308?s=1.055*s**(1/2.4)-.055:s*=12.92;let l=i;l1&&(i/=l,a/=l,s/=l),i<0&&(i=0),a<0&&(a=0),s<0&&(s=0),t[0]=i,t[1]=a,t[2]=s}function hi(e,t){let[r,n,o]=e;r>.04045?r=((r+.055)/1.055)**2.4:r/=12.92,n>.04045?n=((n+.055)/1.055)**2.4:n/=12.92,o>.04045?o=((o+.055)/1.055)**2.4:o/=12.92,t[0]=.4124*r+.3576*n+.1805*o,t[1]=.2126*r+.7152*n+.0722*o,t[2]=.0193*r+.1192*n+.9505*o}function mi(e,t){const r=[0,0,0];hi(e,r),pi(r,t)}function gi(e,t){const r=[0,0,0];di(e,r),fi(r,t)}function yi(e){return e[0]=1,e[1]=-1,e[2]=1,e[3]=-1,e[4]=1,e[5]=-1,e}function vi(e){return!(e[1]-e[0]<0)}function bi(e,t,r){return er?r:e}function xi(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[0,0,0];return n[0]=bi(e[0],t[0],r[0]),n[1]=bi(e[1],t[1],r[1]),n[2]=bi(e[2],t[2],r[2]),n}const _i=fo("GetScalarTypeFittingRange"),Si=fo("GetAdjustedScalarRange");const Ci=e=>!Number.isFinite(e),{isFinite:Ti,isNaN:wi}=Number,Ai=wi;function Ei(){return[].concat([Number.MAX_VALUE,-Number.MAX_VALUE,Number.MAX_VALUE,-Number.MAX_VALUE,Number.MAX_VALUE,-Number.MAX_VALUE])}function Di(e){const t=Math.floor(255*e);return t>15?t.toString(16):`0${t.toString(16)}`}function Pi(e){return Math.round(255*e)}var Ii,Oi={Pi:()=>Math.PI,ldexp:function(e,t){return t>1023?e*2**1023*2**(t-1023):t<-1074?5e-324*e*2**(t+1074):e*2**t},radiansFromDegrees:yo,degreesFromRadians:vo,round:bo,floor:xo,ceil:_o,ceilLog2:To,min:So,max:Co,arrayMin:function(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,r=1/0;for(let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=e.length;n2&&void 0!==arguments[2]?arguments[2]:1,r=-1/0;for(let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=e.length;n2&&void 0!==arguments[2]?arguments[2]:1,r=1/0,n=-1/0;for(let o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=e.length;o=0;--o)if(r[o]0&&void 0!==arguments[0]?arguments[0]:0;return e+((arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)-e)*Math.random()},gaussian:Do,add:Po,subtract:Io,multiplyScalar:Oo,multiplyScalar2D:No,multiplyAccumulate:Mo,multiplyAccumulate2D:function(e,t,r,n){return n[0]=e[0]+t[0]*r,n[1]=e[1]+t[1]*r,n},dot:Ro,outer:function(e,t,r){r[0]=e[0]*t[0],r[1]=e[0]*t[1],r[2]=e[0]*t[2],r[3]=e[1]*t[0],r[4]=e[1]*t[1],r[5]=e[1]*t[2],r[6]=e[2]*t[0],r[7]=e[2]*t[1],r[8]=e[2]*t[2]},cross:Fo,norm:Bo,normalize:Lo,perpendiculars:function(e,t,r,n){const o=e[0]*e[0],i=e[1]*e[1],a=e[2]*e[2],s=Math.sqrt(o+i+a);let l,u,c;o>i&&o>a?(l=0,u=1,c=2):i>a?(l=1,u=2,c=0):(l=2,u=0,c=1);const d=e[l]/s,p=e[u]/s,f=e[c]/s,h=Math.sqrt(d*d+f*f);if(0!==n){const e=Math.sin(n),o=Math.cos(n);t&&(t[l]=(f*o-d*p*e)/h,t[u]=e*h,t[c]=(-d*o-p*f*e)/h),r&&(r[l]=(-f*e-d*p*o)/h,r[u]=o*h,r[c]=(d*e-p*f*o)/h)}else t&&(t[l]=f/h,t[u]=0,t[c]=-d/h),r&&(r[l]=-d*p/h,r[u]=h,r[c]=-p*f/h)},projectVector:function(e,t,r){const n=Ro(t,t);if(0===n)return r[0]=0,r[1]=0,r[2]=0,!1;const o=Ro(e,t)/n;for(let e=0;e<3;e++)r[e]=t[e];return Oo(r,o),!0},projectVector2D:function(e,t,r){const n=Uo(t,t);if(0===n)return r[0]=0,r[1]=0,!1;const o=Uo(e,t)/n;for(let e=0;e<2;e++)r[e]=t[e];return No(r,o),!0},distance2BetweenPoints:Vo,angleBetweenVectors:function(e,t){const r=[0,0,0];return Fo(e,t,r),Math.atan2(Bo(r),Ro(e,t))},gaussianAmplitude:function(e,t,r){const n=Math.abs(e-r);return 1/Math.sqrt(2*Math.PI*t)*Math.exp(-(n**2)/(2*t))},gaussianWeight:function(e,t,r){const n=Math.abs(e-r);return Math.exp(-(n**2)/(2*t))},dot2D:Uo,outer2D:function(e,t,r){r[0]=e[0]*t[0],r[1]=e[0]*t[1],r[2]=e[1]*t[0],r[3]=e[1]*t[1]},norm2D:Go,normalize2D:zo,determinant2x2:jo,LUFactor3x3:function(e,t){let r,n,o;const i=[0,0,0];for(let t=0;t<3;t++)o=Math.abs(e[3*t]),(n=Math.abs(e[3*t+1]))>o&&(o=n),(n=Math.abs(e[3*t+2]))>o&&(o=n),i[t]=1/o;o=i[0]*Math.abs(e[0]),r=0,(n=i[1]*Math.abs(e[3]))>=o&&(o=n,r=1),(n=i[2]*Math.abs(e[6]))>=o&&(r=2),0!==r&&(ho(e,3,r,0),i[r]=i[0]),t[0]=r,e[3]/=e[0],e[6]/=e[0],e[4]-=e[3]*e[1],e[7]-=e[6]*e[1],o=i[1]*Math.abs(e[4]),r=1,(n=i[2]*Math.abs(e[7]))>=o&&(r=2,ho(e,3,1,2),i[2]=i[1]),t[1]=r,e[7]/=e[4],e[5]-=e[3]*e[2],e[8]-=e[6]*e[2]+e[7]*e[5],t[2]=2},LUSolve3x3:function(e,t,r){let n=r[t[0]];r[t[0]]=r[0],r[0]=n,n=r[t[1]],r[t[1]]=r[1],r[1]=n-e[3]*r[0],n=r[t[2]],r[t[2]]=r[2],r[2]=n-e[6]*r[0]-e[7]*r[1],r[2]/=e[8],r[1]=(r[1]-e[5]*r[2])/e[4],r[0]=(r[0]-e[1]*r[1]-e[2]*r[2])/e[0]},linearSolve3x3:function(e,t,r){const n=e[0],o=e[1],i=e[2],a=e[3],s=e[4],l=e[5],u=e[6],c=e[7],d=e[8],p=+jo(s,c,l,d),f=-jo(a,u,l,d),h=+jo(a,u,s,c),m=-jo(o,c,i,d),g=+jo(n,u,i,d),y=-jo(n,u,o,c),v=+jo(o,s,i,l),b=-jo(n,a,i,l),x=+jo(n,a,o,s),_=n*p+o*f+i*h,S=p*t[0]+m*t[1]+v*t[2],C=f*t[0]+g*t[1]+b*t[2],T=h*t[0]+y*t[1]+x*t[2];r[0]=S/_,r[1]=C/_,r[2]=T/_},multiply3x3_vect3:function(e,t,r){const n=e[0]*t[0]+e[1]*t[1]+e[2]*t[2],o=e[3]*t[0]+e[4]*t[1]+e[5]*t[2],i=e[6]*t[0]+e[7]*t[1]+e[8]*t[2];r[0]=n,r[1]=o,r[2]=i},multiply3x3_mat3:Wo,multiplyMatrix:function(e,t,r,n,o,i,a){n!==o&&uo("Number of columns of A must match number of rows of B.");const s=[...e],l=[...t];for(let e=0;e1&&void 0!==arguments[1]?arguments[1]:so)},isIdentity3x3:function(e){return $o(e,ao,arguments.length>1&&void 0!==arguments[1]?arguments[1]:so)},determinant3x3:Ko,quaternionToMatrix3x3:Jo,areEquals:Xo,areMatricesEqual:$o,roundNumber:Qo,roundVector:Zo,matrix3x3ToQuaternion:ti,multiplyQuaternion:function(e,t,r){const n=e[0]*t[0],o=e[0]*t[1],i=e[0]*t[2],a=e[0]*t[3],s=e[1]*t[0],l=e[1]*t[1],u=e[1]*t[2],c=e[1]*t[3],d=e[2]*t[0],p=e[2]*t[1],f=e[2]*t[2],h=e[2]*t[3],m=e[3]*t[0],g=e[3]*t[1],y=e[3]*t[2],v=e[3]*t[3];r[0]=n-l-f-v,r[1]=o+s+h-y,r[2]=i-c+d+g,r[3]=a+u-p+m},orthogonalize3x3:ri,diagonalize3x3:ni,singularValueDecomposition3x3:function(e,t,r,n){let o;const i=[...e],a=Ko(i);if(a<0)for(o=0;o<9;o++)i[o]=-i[o];ri(i,t),Ho(i,i),Wo(i,t,n),ni(n,r,n),Wo(t,n,t),Ho(n,n),a<0&&(r[0]=-r[0],r[1]=-r[1],r[2]=-r[2])},solveLinearSystem:ai,invertMatrix:si,luFactorLinearSystem:oi,luSolveLinearSystem:ii,estimateMatrixCondition:function(e,t){let r=+Number.MAX_VALUE,n=-Number.MAX_VALUE;for(let r=0;rn&&(n=Math.abs(e[r*t+o]));for(let n=0;n6&&void 0!==arguments[6])||arguments[6];if(elo&&(p=0,s[c]=0);if(p&&1===o)return co("Detected homogeneous system (Y=0), calling SolveHomogeneousLeastSquares()"),li(e,t,r,i);if(p)h=1;else for(c=0;c1&&void 0!==arguments[1]?arguments[1]:[0,.5,1];switch(e.length){case 3:return t[0]=17*parseInt(e[0],16)/255,t[1]=17*parseInt(e[1],16)/255,t[2]=17*parseInt(e[2],16)/255,t;case 4:return t[0]=17*parseInt(e[1],16)/255,t[1]=17*parseInt(e[2],16)/255,t[2]=17*parseInt(e[3],16)/255,t;case 6:return t[0]=parseInt(e.substr(0,2),16)/255,t[1]=parseInt(e.substr(2,2),16)/255,t[2]=parseInt(e.substr(4,2),16)/255,t;case 7:return t[0]=parseInt(e.substr(1,2),16)/255,t[1]=parseInt(e.substr(3,2),16)/255,t[2]=parseInt(e.substr(5,2),16)/255,t;case 9:return t[0]=parseInt(e.substr(1,2),16)/255,t[1]=parseInt(e.substr(3,2),16)/255,t[2]=parseInt(e.substr(5,2),16)/255,t[3]=parseInt(e.substr(7,2),16)/255,t;default:return t}},rgb2hsv:ui,hsv2rgb:ci,lab2xyz:di,xyz2lab:pi,xyz2rgb:fi,rgb2xyz:hi,rgb2lab:mi,lab2rgb:gi,uninitializeBounds:yi,areBoundsInitialized:vi,computeBoundsFromPoints:function(e,t,r){return r[0]=Math.min(e[0],t[0]),r[1]=Math.max(e[0],t[0]),r[2]=Math.min(e[1],t[1]),r[3]=Math.max(e[1],t[1]),r[4]=Math.min(e[2],t[2]),r[5]=Math.max(e[2],t[2]),r},clampValue:bi,clampVector:xi,clampAndNormalizeValue:function(e,t){let r=0;return t[0]!==t[1]&&(r=et[1]?t[1]:e,r=(r-t[0])/(t[1]-t[0])),r},getScalarTypeFittingRange:_i,getAdjustedScalarRange:Si,extentIsWithinOtherExtent:function(e,t){if(!e||!t)return 0;for(let r=0;r<6;r+=2)if(e[r]t[r+1]||e[r+1]t[r+1])return 0;return 1},boundsIsWithinOtherBounds:function(e,t,r){if(!e||!t)return 0;for(let n=0;n<6;n+=2)if(e[n]+r[n/2]t[n+1]||e[n+1]+r[n/2]t[n+1])return 0;return 1},pointIsWithinBounds:function(e,t,r){if(!e||!t||!r)return 0;for(let n=0;n<3;n++)if(e[n]+r[n]t[2*n+1])return 0;return 1},solve3PointCircle:function(e,t,r,n){const o=go(3),i=go(3),a=go(3),s=go(3),l=go(3),u=go(3);for(let n=0;n<3;++n)o[n]=e[n]-t[n],i[n]=t[n]-r[n],a[n]=r[n]-e[n],s[n]=-o[n],l[n]=-i[n],u[n]=-a[n];const c=Bo(s),d=Bo(l),p=Bo(a),f=go(3);Fo(o,i,f);const h=Bo(f),m=c*d*p/(2*h),g=2*h*h,y=d*d*Ro(o,u)/g,v=p*p*Ro(s,i)/g,b=c*c*Ro(a,l)/g;for(let o=0;o<3;++o)n[o]=y*e[o]+v*t[o]+b*r[o];return m},inf:1/0,negInf:-1/0,isInf:Ci,isNan:wi,isNaN:wi,isFinite:Ti,createUninitializedBounds:Ei,getMajorAxisIndex:function(e){let t=-1,r=-1;for(let n=0;nt&&(r=n,t=o)}return r},getSparseOrthogonalMatrix:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:3;const r=new Array(t),n=new Array(t);for(let e=0;e0;o--){let i=-1/0,a=0,s=0;for(let l=0;l<=o;++l){const u=r[l];for(let r=0;r<=o;++r){const o=n[r],c=Math.abs(e[u+t*o]);c>i&&(i=c,a=l,s=r)}}[r[o],r[a]]=[r[a],r[o]],[n[o],n[s]]=[n[s],n[o]]}const o=new Array(t*t).fill(0);for(let i=0;i1&&void 0!==arguments[1]?arguments[1]:"#"}${e.map(Di).join("")}`},float2CssRGBA:function(e){return 3===e.length?`rgb(${e.map(Pi).join(", ")})`:`rgba(${Pi(e[0]||0)}, ${Pi(e[1]||0)}, ${Pi(e[2]||0)}, ${e[3]||0})`}};function Ni(e,t,r){var n=t[0],o=t[1],i=t[2],a=t[3];return e[0]=r[0]*n+r[4]*o+r[8]*i+r[12]*a,e[1]=r[1]*n+r[5]*o+r[9]*i+r[13]*a,e[2]=r[2]*n+r[6]*o+r[10]*i+r[14]*a,e[3]=r[3]*n+r[7]*o+r[11]*i+r[15]*a,e}function Mi(){var e=new a(4);return a!=Float32Array&&(e[0]=0,e[1]=0,e[2]=0),e[3]=1,e}function Ri(e,t,r){r*=.5;var n=Math.sin(r);return e[0]=n*t[0],e[1]=n*t[1],e[2]=n*t[2],e[3]=Math.cos(r),e}function Fi(e,t){var r=2*Math.acos(t[3]),n=Math.sin(r/2);return n>i?(e[0]=t[0]/n,e[1]=t[1]/n,e[2]=t[2]/n):(e[0]=1,e[1]=0,e[2]=0),r}function Bi(e,t,r){var n=t[0],o=t[1],i=t[2],a=t[3],s=r[0],l=r[1],u=r[2],c=r[3];return e[0]=n*c+a*s+o*u-i*l,e[1]=o*c+a*l+i*s-n*u,e[2]=i*c+a*u+n*l-o*s,e[3]=a*c-n*s-o*l-i*u,e}function Li(e,t,r,n){var o,a,s,l,u,c=t[0],d=t[1],p=t[2],f=t[3],h=r[0],m=r[1],g=r[2],y=r[3];return(a=c*h+d*m+p*g+f*y)<0&&(a=-a,h=-h,m=-m,g=-g,y=-y),1-a>i?(o=Math.acos(a),s=Math.sin(o),l=Math.sin((1-n)*o)/s,u=Math.sin(n*o)/s):(l=1-n,u=n),e[0]=l*c+u*h,e[1]=l*d+u*m,e[2]=l*p+u*g,e[3]=l*f+u*y,e}Ii=new a(4),a!=Float32Array&&(Ii[0]=0,Ii[1]=0,Ii[2]=0,Ii[3]=0);var ki=function(e,t,r,n){var o=new a(4);return o[0]=e,o[1]=t,o[2]=r,o[3]=n,o};dr(),fr(1,0,0),fr(0,1,0),Mi(),Mi(),ae();const Ui={};function Vi(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Ui,r),zt.obj(e,t),zt.setGet(e,t,["transform"]),function(e,t){t.classHierarchy.push("vtkImplicitFunction"),e.functionValue=r=>{if(!t.transform)return e.evaluateFunction(r);const n=[];return t.transform.transformPoint(r,n),e.evaluateFunction(n)},e.evaluateFunction=e=>{zt.vtkErrorMacro("not implemented")}}(e,t)}var Gi={newInstance:zt.newInstance(Vi,"vtkImplicitFunction"),extend:Vi};const zi=1e-6,ji="coincide",Wi="disjoint";function Hi(e,t,r){const n=r[0]*(e[0]-t[0])+r[1]*(e[1]-t[1])+r[2]*(e[2]-t[2]);return Math.abs(n)}function Ki(e,t,r,n){const o=[];Io(e,t,o);const i=Ro(r,o);n[0]=e[0]-i*r[0],n[1]=e[1]-i*r[1],n[2]=e[2]-i*r[2]}function Xi(e,t,r){const n=Ro(e,t);let o=Ro(t,t);return 0===o&&(o=1),r[0]=e[0]-n*t[0]/o,r[1]=e[1]-n*t[1]/o,r[2]=e[2]-n*t[2]/o,r}function $i(e,t,r,n){const o=[];Io(e,t,o);const i=Ro(r,o),a=Ro(r,r);0!==a?(n[0]=e[0]-i*r[0]/a,n[1]=e[1]-i*r[1]/a,n[2]=e[2]-i*r[2]/a):(n[0]=e[0],n[1]=e[1],n[2]=e[2])}function qi(e,t,r,n){const o={intersection:!1,betweenPoints:!1,t:Number.MAX_VALUE,x:[]},i=[],a=[];Io(t,e,i),Io(r,e,a);const s=Ro(n,a),l=Ro(n,i);let u,c;return u=l<0?-l:l,c=s<0?-s*zi:s*zi,u<=c||(o.t=s/l,o.x[0]=e[0]+o.t*i[0],o.x[1]=e[1]+o.t*i[1],o.x[2]=e[2]+o.t*i[2],o.intersection=!0,o.betweenPoints=o.t>=0&&o.t<=1),o}function Yi(e,t,r,n){const o={intersection:!1,l0:[],l1:[],error:null},i=[];Fo(t,n,i);const a=i.map(e=>Math.abs(e));if(a[0]+a[1]+a[2]a[1]&&a[0]>a[2]?"x":a[1]>a[2]?"y":"z";const l=[],u=-Ro(t,e),c=-Ro(n,r);switch(s){case"x":l[0]=0,l[1]=(c*t[2]-u*n[2])/i[0],l[2]=(u*n[1]-c*t[1])/i[0];break;case"y":l[0]=(u*n[2]-c*t[2])/i[1],l[1]=0,l[2]=(c*t[0]-u*n[0])/i[1];break;case"z":l[0]=(c*t[1]-u*n[1])/i[2],l[1]=(u*n[0]-c*t[0])/i[2],l[2]=0}return o.l0=l,Po(l,i,o.l1),o.intersection=!0,o}const Ji={evaluate:function(e,t,r){return e[0]*(r[0]-t[0])+e[1]*(r[1]-t[1])+e[2]*(r[2]-t[2])},distanceToPlane:Hi,projectPoint:Ki,projectVector:Xi,generalizedProjectPoint:$i,intersectWithLine:qi,intersectWithPlane:Yi,DISJOINT:Wi,COINCIDE:ji},Qi={normal:[0,0,1],origin:[0,0,0]};function Zi(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Qi,r),Gi.extend(e,t,r),zt.setGetArray(e,t,["normal","origin"],3),function(e,t){t.classHierarchy.push("vtkPlane"),e.distanceToPlane=e=>Hi(e,t.origin,t.normal),e.projectPoint=(e,r)=>{Ki(e,t.origin,t.normal,r)},e.projectVector=(e,r)=>Xi(e,t.normal,r),e.push=e=>{if(0!==e)for(let r=0;r<3;r++)t.origin[r]+=e*t.normal[r]},e.generalizedProjectPoint=(e,r)=>{$i(e,t.origin,t.normal,r)},e.evaluateFunction=(e,r,n)=>Array.isArray(e)?t.normal[0]*(e[0]-t.origin[0])+t.normal[1]*(e[1]-t.origin[1])+t.normal[2]*(e[2]-t.origin[2]):t.normal[0]*(e-t.origin[0])+t.normal[1]*(r-t.origin[1])+t.normal[2]*(n-t.origin[2]),e.evaluateGradient=e=>[t.normal[0],t.normal[1],t.normal[2]],e.intersectWithLine=(e,r)=>qi(e,r,t.origin,t.normal),e.intersectWithPlane=(e,r)=>Yi(e,r,t.origin,t.normal)}(e,t)}var ea={newInstance:zt.newInstance(Zi,"vtkPlane"),extend:Zi,...Ji};const ta=[Number.MAX_VALUE,-Number.MAX_VALUE,Number.MAX_VALUE,-Number.MAX_VALUE,Number.MAX_VALUE,-Number.MAX_VALUE];function ra(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]}function na(e){return e?.length>=6&&e[0]<=e[1]&&e[2]<=e[3]&&e[4]<=e[5]}function oa(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e}function ia(e){return oa(e,ta)}function aa(e,t,r,n){const[o,i,a,s,l,u]=e;return e[0]=ot?i:t,e[2]=ar?s:r,e[4]=ln?u:n,e}function sa(e,t){if(0===t.length)return e;if(Array.isArray(t[0]))for(let r=0;ri?t:i,e[2]=r,e[3]=r>s?r:s,e[4]=n,e[5]=n>u?n:u,o!==t||a!==r||l!==n}function ca(e,t,r,n){const[o,i,a,s,l,u]=e;return e[0]=tn&&(n=o,r=i),t[i]=o>0?1:0;if(r<0)return da(e,.5);for(let r=0;r<3;++r)if(!t[r]){const t=.005*n;e[2*r]-=t,e[2*r+1]+=t}return e}(e):(e[0]-=t,e[1]+=t,e[2]-=t,e[3]+=t,e[4]-=t,e[5]+=t,e)}function pa(e,t,r,n){return!!na(e)&&(t>=0?(e[0]*=t,e[1]*=t):(e[0]=t*e[1],e[1]=t*e[0]),r>=0?(e[2]*=r,e[3]*=r):(e[2]=r*e[3],e[3]=r*e[2]),n>=0?(e[4]*=n,e[5]*=n):(e[4]=n*e[5],e[5]=n*e[4]),!0)}function fa(e){return[.5*(e[0]+e[1]),.5*(e[2]+e[3]),.5*(e[4]+e[5])]}function ha(e,t){return e[2*t+1]-e[2*t]}function ma(e){return[ha(e,0),ha(e,1),ha(e,2)]}function ga(e){return e.slice(0,2)}function ya(e){return e.slice(2,4)}function va(e){return e.slice(4,6)}function ba(e){const t=ma(e);return t[0]>t[1]?t[0]>t[2]?t[0]:t[2]:t[1]>t[2]?t[1]:t[2]}function xa(e){if(na(e)){const t=ma(e);return t[0]*t[0]+t[1]*t[1]+t[2]*t[2]}return null}function _a(e){const t=xa(e);return null!==t?Math.sqrt(t):null}function Sa(e){return[e[0],e[2],e[4]]}function Ca(e){return[e[1],e[3],e[5]]}function Ta(e,t){return e<=0&&t>=0||e>=0&&t<=0}function wa(e,t){return t[0]=[e[0],e[2],e[4]],t[1]=[e[0],e[2],e[5]],t[2]=[e[0],e[3],e[4]],t[3]=[e[0],e[3],e[5]],t[4]=[e[1],e[2],e[4]],t[5]=[e[1],e[2],e[5]],t[6]=[e[1],e[3],e[4]],t[7]=[e[1],e[3],e[5]],t}function Aa(e,t,r){return t[0]=e[0],t[1]=e[2],t[2]=e[4],r[0]=e[1],r[1]=e[3],r[2]=e[5],t}function Ea(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];const n=wa(e,[]);for(let e=0;e1&&void 0!==arguments[1]?arguments[1]:[];return t[0]=.5*(e[1]-e[0]),t[1]=.5*(e[3]-e[2]),t[2]=.5*(e[5]-e[4]),t}function Pa(e,t,r,n){const o=[].concat(ta),i=e.getData();for(let e=0;ee[2*r+1]?(a[r]=0,u[r]=e[2*r+1],i=!1):a[r]=2;if(i)return n[0]=t[0],n[1]=t[1],n[2]=t[2],o[0]=0,1;for(let e=0;e<3;e++)2!==a[e]&&0!==r[e]?l[e]=(u[e]-t[e])/r[e]:l[e]=-1;for(let e=0;e<3;e++)l[s]1||l[s]<0)return 0;o[0]=l[s];for(let o=0;o<3;o++)if(s!==o){if(n[o]=t[o]+l[s]*r[o],n[o]e[2*o+1])return 0}else n[o]=u[o];return 1}function Oa(e,t,r){const n=[];let o=0,i=1,a=1;for(let s=4;s<=5;++s){n[2]=e[s];for(let s=2;s<=3;++s){n[1]=e[s];for(let s=0;s<=1;++s)if(n[0]=e[s],o=ea.evaluate(r,t,n),a&&(i=o>=0?1:-1,a=0),0===o||i>0&&o<0||i<0&&o>0)return 1}}return 0}function Na(e,t){if(!na(e)||!na(t))return!1;const r=[0,0,0,0,0,0];let n;for(let o=0;o<3;o++)if(n=!1,t[2*o]>=e[2*o]&&t[2*o]<=e[2*o+1]?(n=!0,r[2*o]=t[2*o]):e[2*o]>=t[2*o]&&e[2*o]<=t[2*o+1]&&(n=!0,r[2*o]=e[2*o]),t[2*o+1]>=e[2*o]&&t[2*o+1]<=e[2*o+1]?(n=!0,r[2*o+1]=t[2*o+1]):e[2*o+1]>=t[2*o]&&e[2*o+1]<=t[2*o+1]&&(n=!0,r[2*o+1]=e[2*o+1]),!n)return!1;return e[0]=r[0],e[1]=r[1],e[2]=r[2],e[3]=r[3],e[4]=r[4],e[5]=r[5],!0}function Ma(e,t){if(!na(e)||!na(t))return!1;for(let r=0;r<3;r++)if(!(t[2*r]>=e[2*r]&&t[2*r]<=e[2*r+1]||e[2*r]>=t[2*r]&&e[2*r]<=t[2*r+1]||t[2*r+1]>=e[2*r]&&t[2*r+1]<=e[2*r+1]||e[2*r+1]>=t[2*r]&&e[2*r+1]<=t[2*r+1]))return!1;return!0}function Ra(e,t,r,n){return!(te[1]||re[3]||ne[5])}function Fa(e,t,r){const n=[[0,1,2,3,4,5,6,7],[0,1,4,5,2,3,6,7],[0,2,4,6,1,3,5,7]],o=[0,0,0,0,0,0,0,0];let i=0;for(let n=0;n<2;n++)for(let a=2;a<4;a++)for(let s=4;s<6;s++){const l=[e[n],e[a],e[s]];o[i++]=ea.evaluate(r,t,l)}let a=2;for(;a--&&!(Ta(o[n[a][0]],o[n[a][4]])&&Ta(o[n[a][1]],o[n[a][5]])&&Ta(o[n[a][2]],o[n[a][6]])&&Ta(o[n[a][3]],o[n[a][7]])););if(a<0)return!1;const s=Math.sign(r[a]),l=Math.abs((e[2*a+1]-e[2*a])*r[a]);let u=s>0?1:0;for(let e=0;e<4;e++){if(0===l)continue;const t=Math.abs(o[n[a][e]])/l;s>0&&tu&&(u=t)}const c=(1-u)*e[2*a]+u*e[2*a+1];return s>0?e[2*a]=c:e[2*a+1]=c,!0}function Ba(e,t){for(let e=0;e<3;++e)t[e]=t[e]<1?1:t[e];let r=t[0]*t[1]*t[2];for(;r>e;){for(let e=0;e<3;++e)t[e]=t[e]>1?t[e]-1:1;r=t[0]*t[1]*t[2]}}function La(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[];t=t<=0?1:t;let o=0;const i=[0,0,0];let a=-1,s=0;const l=ma(e),u=l[0]+l[1]+l[2],c=u*(.001/3);for(let e=0;e<3;++e)l[e]>s&&(a=e,s=l[e]),l[e]>c?(i[e]=1,o++):i[e]=0;const d=Sa(e),p=Ca(e);if(o<1)return r[0]=1,r[1]=1,r[2]=1,n[0]=d[0]-.5,n[1]=p[0]+.5,n[2]=d[1]-.5,n[3]=p[1]+.5,n[4]=d[2]-.5,n[5]=p[2]+.5,1;let f=t;f/=i[0]?l[0]/u:1,f/=i[1]?l[1]/u:1,f/=i[2]?l[2]/u:1,f**=1/o;for(let e=0;e<3;++e)r[e]=i[e]?Math.floor(f*l[e]/u):1,r[e]=r[e]<1?1:r[e];Ba(t,r);const h=.5*l[a]/r[a];for(let e=0;e<3;++e)i[e]?(n[2*e]=d[e],n[2*e+1]=p[e]):(n[2*e]=d[e]-h,n[2*e+1]=p[e]+h);return r[0]*r[1]*r[2]}function ka(e,t){if(e[0]>=t[0]&&e[0]<=t[1]&&e[1]>=t[2]&&e[1]<=t[3]&&e[2]>=t[4]&&e[2]<=t[5])return 0;const r=[0,0,0];return e[0]t[1]&&(r[0]=e[0]-t[1]),e[1]t[3]&&(r[1]=e[1]-t[3]),e[2]t[5]&&(r[2]=e[2]-t[5]),Ro(r,r)}class Ua{constructor(e){this.bounds=e,this.bounds||(this.bounds=new Float64Array(ta))}getBounds(){return this.bounds}equals(e){return ra(this.bounds,e)}isValid(){return na(this.bounds)}setBounds(e){return oa(this.bounds,e)}reset(){return ia(this.bounds)}addPoint(){for(var e=arguments.length,t=new Array(e),r=0;r1&&void 0!==arguments[1]?arguments[1]:[];return Ea(this.bounds,e,t)}computeScale3(e){return Da(this.bounds,e)}cutWithPlane(e,t){return Fa(this.bounds,e,t)}intersectBox(e,t,r,n){return Ia(this.bounds,e,t,r,n)}intersectPlane(e,t){return Oa(this.bounds,e,t)}intersect(e){return Na(this.bounds,e)}intersects(e){return Ma(this.bounds,e)}containsPoint(e,t,r){return Ra(this.bounds,e,t,r)}contains(e){return Ma(this.bounds,e)}computeDivisions(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];return La(this.bounds,e,t,r)}distance2ToBounds(e){return ka(e,this.bounds)}}var Va={newInstance:function(e){const t=e&&e.bounds;return new Ua(t)},equals:ra,isValid:na,setBounds:oa,reset:ia,addPoint:aa,addPoints:sa,addBounds:la,setMinPoint:ua,setMaxPoint:ca,inflate:da,scale:pa,scaleAboutCenter:function(e,t,r,n){if(!na(e))return!1;const o=fa(e);return e[0]-=o[0],e[1]-=o[0],e[2]-=o[1],e[3]-=o[1],e[4]-=o[2],e[5]-=o[2],pa(e,t,r,n),e[0]+=o[0],e[1]+=o[0],e[2]+=o[1],e[3]+=o[1],e[4]+=o[2],e[5]+=o[2],!0},getCenter:fa,getLength:ha,getLengths:ma,getMaxLength:ba,getDiagonalLength:_a,getDiagonalLength2:xa,getMinPoint:Sa,getMaxPoint:Ca,getXRange:ga,getYRange:ya,getZRange:va,getCorners:wa,computeCornerPoints:Aa,computeLocalBounds:Pa,transformBounds:Ea,computeScale3:Da,cutWithPlane:Fa,intersectBox:Ia,intersectPlane:Oa,intersect:Na,intersects:Ma,containsPoint:Ra,contains:function(e,t){return!!Ma(e,t)&&!!Ra(e,...Sa(t))&&!!Ra(e,...Ca(t))},computeDivisions:La,clampDivisions:Ba,distance2ToBounds:ka,INIT_BOUNDS:ta},Ga={CoordinateSystem:{DISPLAY:0,WORLD:1}};const{CoordinateSystem:za}=Ga;function ja(e){return()=>zt.vtkErrorMacro(`vtkProp::${e} - NOT IMPLEMENTED`)}const Wa={allocatedRenderTime:10,coordinateSystem:za.WORLD,dragable:!0,estimatedRenderTime:0,paths:null,pickable:!0,renderTimeMultiplier:1,savedEstimatedRenderTime:0,textures:[],useBounds:!0,visibility:!0};function Ha(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Wa,r),zt.obj(e,t),zt.get(e,t,["estimatedRenderTime","allocatedRenderTime"]),zt.setGet(e,t,["_parentProp","coordinateSystem","dragable","pickable","renderTimeMultiplier","useBounds","visibility"]),zt.moveToProtected(e,t,["parentProp"]),function(e,t){t.classHierarchy.push("vtkProp"),e.getMTime=()=>{let e=t.mtime;for(let r=0;re&&(e=n)}return e},e.processSelectorPixelBuffers=(e,t)=>{},e.getNestedProps=()=>null,e.getActors=()=>[],e.getActors2D=()=>[],e.getVolumes=()=>[],e.pick=ja("pick"),e.hasKey=ja("hasKey"),e.getNestedVisibility=()=>t.visibility&&(!t._parentProp||t._parentProp.getNestedVisibility()),e.getNestedPickable=()=>t.pickable&&(!t._parentProp||t._parentProp.getNestedPickable()),e.getNestedDragable=()=>t.dragable&&(!t._parentProp||t._parentProp.getNestedDragable()),e.getRedrawMTime=()=>t.mtime,e.setEstimatedRenderTime=e=>{t.estimatedRenderTime=e,t.savedEstimatedRenderTime=e},e.restoreEstimatedRenderTime=()=>{t.estimatedRenderTime=t.savedEstimatedRenderTime},e.addEstimatedRenderTime=e=>{t.estimatedRenderTime+=e},e.setAllocatedRenderTime=e=>{t.allocatedRenderTime=e,t.savedEstimatedRenderTime=t.estimatedRenderTime,t.estimatedRenderTime=0},e.getSupportsSelection=()=>!1,e.getTextures=()=>t.textures,e.hasTexture=e=>-1!==t.textures.indexOf(e),e.addTexture=r=>{r&&!e.hasTexture(r)&&(t.textures=t.textures.concat(r),e.modified())},e.removeTexture=r=>{const n=t.textures.filter(e=>e!==r);t.textures.length!==n.length&&(t.textures=n,e.modified())},e.removeAllTextures=()=>{t.textures=[],e.modified()},e.setCoordinateSystemToWorld=()=>e.setCoordinateSystem(za.WORLD),e.setCoordinateSystemToDisplay=()=>e.setCoordinateSystem(za.DISPLAY)}(e,t)}var Ka={newInstance:zt.newInstance(Ha,"vtkProp"),extend:Ha,...Ga};const Xa={origin:[0,0,0],position:[0,0,0],orientation:[0,0,0],rotation:null,scale:[1,1,1],bounds:[...Va.INIT_BOUNDS],properties:[],userMatrix:null,userMatrixMTime:null,cachedProp3D:null,isIdentity:!0,matrixMTime:null};function $a(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Xa,r),Ka.extend(e,t,r),t.matrixMTime={},zt.obj(t.matrixMTime),zt.get(e,t,["isIdentity"]),zt.getArray(e,t,["orientation"]),zt.setGetArray(e,t,["origin","position","scale"],3),zt.setGet(e,t,["properties"]),t.matrix=h(new Float64Array(16)),t.rotation=h(new Float64Array(16)),t.userMatrix=h(new Float64Array(16)),t.transform=null,function(e,t){t.classHierarchy.push("vtkProp3D"),e.addPosition=r=>{t.position=t.position.map((e,t)=>e+r[t]),e.modified()},e.getOrientationWXYZ=()=>{const e=Mi();B(e,t.rotation);const r=new Float64Array(3);return[vo(Fi(r,e)),r[0],r[1],r[2]]},e.getOrientationQuaternion=function(){return B(arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t.rotation)},e.rotateX=r=>{0!==r&&(C(t.rotation,t.rotation,yo(r)),e.modified())},e.rotateY=r=>{0!==r&&(T(t.rotation,t.rotation,yo(r)),e.modified())},e.rotateZ=r=>{0!==r&&(w(t.rotation,t.rotation,yo(r)),e.modified())},e.rotateWXYZ=(r,n,o,i)=>{if(0===r||0===n&&0===o&&0===i)return;const a=yo(r),s=Mi();Ri(s,[n,o,i],a);const l=new Float64Array(16);U(l,s),b(t.rotation,t.rotation,l),e.modified()},e.rotateQuaternion=r=>{if(Math.abs(r[3])>=.999999)return;const n=U(new Float64Array(16),r);b(t.rotation,t.rotation,n),e.modified()},e.setOrientation=(r,n,o)=>(r!==t.orientation[0]||n!==t.orientation[1]||o!==t.orientation[2])&&(t.orientation=[r,n,o],h(t.rotation),e.rotateZ(o),e.rotateX(r),e.rotateY(n),e.modified(),!0),e.setOrientationFromQuaternion=r=>{const n=u();return U(n,r),!$o(n,t.rotation)&&(t.rotation=n,e.modified(),!0)},e.setUserMatrix=r=>!$o(t.userMatrix,r)&&(d(t.userMatrix,r),e.modified(),!0),e.getMatrix=()=>(e.computeMatrix(),t.matrix),e.computeMatrix=()=>{if(e.getMTime()>t.matrixMTime.getMTime()){h(t.matrix),t.userMatrix&&b(t.matrix,t.matrix,t.userMatrix),x(t.matrix,t.matrix,t.origin),x(t.matrix,t.matrix,t.position),b(t.matrix,t.matrix,t.rotation),_(t.matrix,t.matrix,t.scale),x(t.matrix,t.matrix,[-t.origin[0],-t.origin[1],-t.origin[2]]),m(t.matrix,t.matrix),t.isIdentity=!0;for(let e=0;e<4;++e)for(let r=0;r<4;++r)(e===r?1:0)!==t.matrix[e+4*r]&&(t.isIdentity=!1);t.matrixMTime.modified()}},e.getBoundsByReference=()=>{if(null===t.mapper)return t.bounds;const r=t.mapper.getBounds();if(!r||6!==r.length)return r;if(r[0]>r[1])return t.mapperBounds=r,t.bounds=[...Va.INIT_BOUNDS],t.boundsMTime.modified(),r;if(!t.mapperBounds||!r.every((e,n)=>r[n]===t.mapperBounds[n])||e.getMTime()>t.boundsMTime.getMTime()){zt.vtkDebugMacro("Recomputing bounds..."),t.mapperBounds=r,e.computeMatrix();const n=new Float64Array(16);m(n,t.matrix),Va.transformBounds(r,n,t.bounds),t.boundsMTime.modified()}return t.bounds},e.getBounds=()=>{const t=e.getBoundsByReference();try{return[...t]}catch{return t}},e.getCenter=()=>Va.getCenter(t.bounds),e.getLength=()=>Va.getLength(t.bounds),e.getXRange=()=>Va.getXRange(t.bounds),e.getYRange=()=>Va.getYRange(t.bounds),e.getZRange=()=>Va.getZRange(t.bounds),e.getUserMatrix=()=>t.userMatrix,e.onModified(function(){e.computeMatrix()}),e.getProperty=function(){let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return null==t.properties[r]&&(t.properties[r]=e.makeProperty?.()),t.properties[r]},e.getProperties=()=>(0===t.properties.length&&(t.properties[0]=e.makeProperty?.()),t.properties),e.setProperty=(e,r)=>{const n=Number.isInteger(e),[o,i]=n?[e,r]:[0,e];return t.properties[o]!==i&&(t.properties[o]=i,!0)},e.getMTime=()=>{let e=t.mtime;return t.properties.forEach(t=>{if(null!==t){const r=t.getMTime();e=r>e?r:e}}),e}}(e,t)}var qa={newInstance:zt.newInstance($a,"vtkProp3D"),extend:$a};const Ya={FLAT:0,GOURAUD:1,PHONG:2},Ja={POINTS:0,WIREFRAME:1,SURFACE:2};var Qa={Shading:Ya,Representation:Ja,Interpolation:Ya};const{Representation:Za,Interpolation:es}=Qa;function ts(e){return()=>zt.vtkErrorMacro(`vtkProperty::${e} - NOT IMPLEMENTED`)}const rs={color:[1,1,1],ambientColor:[1,1,1],diffuseColor:[1,1,1],specularColor:[1,1,1],edgeColor:[0,0,0],ambient:0,diffuse:1,metallic:0,roughness:.6,normalStrength:1,emission:1,baseIOR:1.45,specular:0,specularPower:1,opacity:1,interpolation:es.GOURAUD,representation:Za.SURFACE,edgeVisibility:!1,backfaceCulling:!1,frontfaceCulling:!1,pointSize:1,lineWidth:1,lighting:!0,shading:!1,materialName:null,ORMTexture:null,RMTexture:null};function ns(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,rs,r),zt.obj(e,t),zt.setGet(e,t,["lighting","interpolation","ambient","diffuse","metallic","roughness","normalStrength","emission","baseIOR","specular","specularPower","opacity","edgeVisibility","lineWidth","pointSize","backfaceCulling","frontfaceCulling","representation","diffuseTexture","metallicTexture","roughnessTexture","normalTexture","ambientOcclusionTexture","emissionTexture","ORMTexture","RMTexture"]),zt.setGetArray(e,t,["ambientColor","specularColor","diffuseColor","edgeColor"],3),function(e,t){t.classHierarchy.push("vtkProperty"),e.setColor=(r,n,o)=>{Array.isArray(r)?t.color[0]===r[0]&&t.color[1]===r[1]&&t.color[2]===r[2]||(t.color[0]=r[0],t.color[1]=r[1],t.color[2]=r[2],e.modified()):t.color[0]===r&&t.color[1]===n&&t.color[2]===o||(t.color[0]=r,t.color[1]=n,t.color[2]=o,e.modified()),e.setDiffuseColor(t.color),e.setAmbientColor(t.color),e.setSpecularColor(t.color)},e.computeCompositeColor=ts("ComputeCompositeColor"),e.getColor=()=>{let e=0;t.ambient+t.diffuse+t.specular>0&&(e=1/(t.ambient+t.diffuse+t.specular));for(let r=0;r<3;r++)t.color[r]=e*(t.ambient*t.ambientColor[r]+t.diffuse*t.diffuseColor[r]+t.specular*t.specularColor[r]);return[].concat(t.color)},e.setSpecularPower=r=>{const n=1/Math.max(1,r);t.roughness===n&&t.specularPower===r||(t.specularPower=r,t.roughness=n,e.modified())},e.addShaderVariable=ts("AddShaderVariable"),e.setInterpolationToFlat=()=>e.setInterpolation(es.FLAT),e.setInterpolationToGouraud=()=>e.setInterpolation(es.GOURAUD),e.setInterpolationToPhong=()=>e.setInterpolation(es.PHONG),e.getInterpolationAsString=()=>zt.enumToString(es,t.interpolation),e.setRepresentationToWireframe=()=>e.setRepresentation(Za.WIREFRAME),e.setRepresentationToSurface=()=>e.setRepresentation(Za.SURFACE),e.setRepresentationToPoints=()=>e.setRepresentation(Za.POINTS),e.getRepresentationAsString=()=>zt.enumToString(Za,t.representation)}(e,t)}var os={newInstance:zt.newInstance(ns,"vtkProperty"),extend:ns,...Qa};const is={mapper:null,backfaceProperty:null,forceOpaque:!1,forceTranslucent:!1};function as(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,is,r),qa.extend(e,t,r),t.boundsMTime={},zt.obj(t.boundsMTime),zt.setGet(e,t,["backfaceProperty","forceOpaque","forceTranslucent","mapper"]),function(e,t){t.classHierarchy.push("vtkActor");const r={...e};e.getActors=()=>[e],e.getIsOpaque=()=>{if(t.forceOpaque)return!0;if(t.forceTranslucent)return!1;t.properties[0]||e.getProperty();let r=t.properties[0].getOpacity()>=1;return r=r&&(!t.texture||!t.texture.isTranslucent()),r=r&&(!t.mapper||t.mapper.getIsOpaque()),r},e.hasTranslucentPolygonalGeometry=()=>null!==t.mapper&&(t.properties[0]||e.getProperty(),!e.getIsOpaque()),e.makeProperty=os.newInstance,e.getMTime=()=>{let e=r.getMTime();if(null!==t.backfaceProperty){const r=t.backfaceProperty.getMTime();e=r>e?r:e}return e},e.getRedrawMTime=()=>{let e=t.mtime;if(null!==t.mapper){let r=t.mapper.getMTime();e=r>e?r:e,null!==t.mapper.getInput()&&(t.mapper.getInputAlgorithm().update(),r=t.mapper.getInput().getMTime(),e=r>e?r:e)}return e},e.getSupportsSelection=()=>!!t.mapper&&t.mapper.getSupportsSelection(),e.processSelectorPixelBuffers=(e,r)=>{t.mapper&&t.mapper.processSelectorPixelBuffers&&t.mapper.processSelectorPixelBuffers(e,r)}}(e,t)}var ss={newInstance:zt.newInstance(as,"vtkActor"),extend:as};const ls={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},us={VOID:"",CHAR:"Int8Array",SIGNED_CHAR:"Int8Array",UNSIGNED_CHAR:"Uint8Array",UNSIGNED_CHAR_CLAMPED:"Uint8ClampedArray",SHORT:"Int16Array",UNSIGNED_SHORT:"Uint16Array",INT:"Int32Array",UNSIGNED_INT:"Uint32Array",FLOAT:"Float32Array",DOUBLE:"Float64Array"};var cs={DefaultDataType:us.FLOAT,DataTypeByteSize:ls,VtkDataTypes:us};const{vtkErrorMacro:ds}=jt,{DefaultDataType:ps}=cs;function fs(e,t,r){const n=e.length;let o,i,a=Number.MAX_VALUE,s=-Number.MAX_VALUE;for(i=t;is&&(s=o);return{min:a,max:s}}function hs(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;if(t<0&&r>1){const t=e.length/r,n=new Float64Array(t);for(let o=0,i=0;o1&&void 0!==arguments[1]?arguments[1]:0;const r=e||[];for(;r.length<=t;)r.push(null);return r}function gs(e){return Object.prototype.toString.call(e).slice(8,-1)}const ys={computeRange:hs,createRangeHelper:function(){let e=Number.MAX_VALUE,t=-Number.MAX_VALUE,r=0,n=0;return{add(o){e>o&&(e=o),t({min:e,max:t,count:r,sum:n,mean:n/r}),getRange:()=>({min:e,max:t})}},fastComputeRange:fs,getDataType:gs,getMaxNorm:function(e){const t=e.getNumberOfComponents();let r=0;const n=new Array(t);for(let o=0;or&&(r=i)}return r}},vs={name:"",numberOfComponents:1,dataType:ps,rangeTuple:[0,0]};function bs(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(Object.assign(t,vs,r),Array.isArray(r.values)&&void 0===r.dataType&&console.warn("vtkDataArray.newInstance: no dataType provided, converting to Float32Array"),!t.empty&&!t.values&&!t.size)throw new TypeError("Cannot create vtkDataArray object without: size > 0, values");if(t.values?Array.isArray(t.values)&&(t.values=it(t.dataType,t.values)):t.values=ot(t.dataType,t.size),t.values&&(t.size=t.size??t.values.length,t.dataType=gs(t.values)),mt(e,t),xt(e,t,["name","numberOfComponents"]),t.size%t.numberOfComponents!==0)throw new RangeError("model.size is not a multiple of model.numberOfComponents");!function(e,t){function r(r){if(r<0)return!1;const n=e.getNumberOfComponents(),o=t.values.length/(n>0?n:1);if(r===o)return!0;if(r>o){const e=t.values;return t.values=ot(t.dataType,(r+o)*n),t.values.set(e),!0}return t.size>r*n&&(t.size=r*n,e.dataChange()),!0}t.classHierarchy.push("vtkDataArray"),e.dataChange=()=>{t.ranges=null,e.modified()},e.allocate=t=>{r(e.getNumberOfTuples()+t)},e.resize=n=>{r(n);const o=n*e.getNumberOfComponents();return t.size!==o&&(t.size=o,e.dataChange(),!0)},e.initialize=()=>(e.resize(0),e),e.getElementComponentSize=()=>t.values.BYTES_PER_ELEMENT,e.getComponent=function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return t.values[e*t.numberOfComponents+r]},e.setComponent=(r,n,o)=>{o!==t.values[r*t.numberOfComponents+n]&&(t.values[r*t.numberOfComponents+n]=o,e.dataChange())},e.getValue=r=>{const n=r/t.numberOfComponents,o=r%t.numberOfComponents;return e.getComponent(n,o)},e.setValue=(r,n)=>{const o=r/t.numberOfComponents,i=r%t.numberOfComponents;e.setComponent(o,i,n)},e.getData=()=>t.size===t.values.length?t.values:t.values.subarray(0,t.size),e.getRange=function(){let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1,n=r;n<0&&(n=1===t.numberOfComponents?0:t.numberOfComponents);let o=null;return t.ranges||(t.ranges=ms(t.ranges,t.numberOfComponents)),o=t.ranges[n],o?(t.rangeTuple[0]=o.min,t.rangeTuple[1]=o.max,t.rangeTuple):(o=hs(e.getData(),r,t.numberOfComponents),t.ranges[n]=o,t.rangeTuple[0]=o.min,t.rangeTuple[1]=o.max,t.rangeTuple)},e.setRange=(e,r)=>{t.ranges||(t.ranges=ms(t.ranges,t.numberOfComponents));const n={min:e.min,max:e.max};return t.ranges[r]=n,t.rangeTuple[0]=n.min,t.rangeTuple[1]=n.max,t.rangeTuple},e.getRanges=function(){if(arguments.length>0&&void 0!==arguments[0]&&!arguments[0])return structuredClone(t.ranges);const r=[];for(let n=0;n1){const[t,n]=e.getRange(-1),o={min:t,max:n};r.push(o)}return r},e.setTuple=(e,r)=>{const n=e*t.numberOfComponents;for(let e=0;e{let n=e*t.numberOfComponents;const o=Math.min(r.length,t.size-n);for(let e=0;e(t.size<=n*t.numberOfComponents&&(t.size=(n+1)*t.numberOfComponents,r(n+1)),e.setTuple(n,o),n),e.insertTuples=(n,o)=>{const i=n+o.length/t.numberOfComponents;return t.size{const n=t.size/t.numberOfComponents;return e.insertTuple(n,r)},e.insertNextTuples=r=>{const n=t.size/t.numberOfComponents;return e.insertTuples(n,r)},e.findTuple=function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e-6;for(let n=0;nr){o=!1;break}if(o)return n/t.numberOfComponents}return-1},e.getTuple=function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];const n=t.numberOfComponents||1,o=e*n;switch(n){case 4:r[3]=t.values[o+3];case 3:r[2]=t.values[o+2];case 2:r[1]=t.values[o+1];case 1:r[0]=t.values[o];break;default:for(let e=n-1;e>=0;--e)r[e]=t.values[o+e]}return r},e.getTuples=(r,n)=>{const o=(r??0)*t.numberOfComponents,i=(n??e.getNumberOfTuples())*t.numberOfComponents,a=e.getData().subarray(o,i);return a.length>0?a:null},e.getTupleLocation=function(){return(arguments.length>0&&void 0!==arguments[0]?arguments[0]:1)*t.numberOfComponents},e.getNumberOfComponents=()=>t.numberOfComponents,e.getNumberOfValues=()=>t.size,e.getNumberOfTuples=()=>t.size/t.numberOfComponents,e.getDataType=()=>t.dataType,e.newClone=()=>xs({empty:!0,name:t.name,dataType:t.dataType,numberOfComponents:t.numberOfComponents}),e.getName=()=>(t.name||(e.modified(),t.name=`vtkDataArray${e.getMTime()}`),t.name),e.setData=(r,n)=>{t.values=r,t.size=r.length,t.dataType=gs(r),n&&(t.numberOfComponents=n),t.size%t.numberOfComponents!==0&&(t.numberOfComponents=1),e.dataChange()},e.getState=()=>{if(t.deleted)return null;const r={...t,vtkClass:e.getClassName()};r.values=Array.from(r.values),delete r.buffer,Object.keys(r).forEach(e=>{r[e]||delete r[e]});const n={};return Object.keys(r).sort().forEach(e=>{n[e]=r[e]}),n.mtime&&delete n.mtime,n},e.deepCopy=r=>{const n=e.getDataType(),o=t.values;e.shallowCopy(r),t.ranges=structuredClone(r.getRanges()),o?.length>=r.getNumberOfValues()&&n===r.getDataType()?(o.set(r.getData()),t.values=o,e.dataChange()):e.setData(r.getData().slice())},e.interpolateTuple=(r,n,o,i,a,s)=>{const l=t.numberOfComponents||1;l===n.getNumberOfComponents()&&l===i.getNumberOfComponents()||ds("numberOfComponents must match");const u=n.getTuple(o),c=i.getTuple(a),d=[];switch(d.length=l,l){case 4:d[3]=u[3]+(c[3]-u[3])*s;case 3:d[2]=u[2]+(c[2]-u[2])*s;case 2:d[1]=u[1]+(c[1]-u[1])*s;case 1:d[0]=u[0]+(c[0]-u[0])*s;break;default:for(let e=0;e2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Ss,r),zt.obj(e,t),zt.algo(e,t,1,0),t.clippingPlanes||(t.clippingPlanes=[]),function(e,t){t.classHierarchy.push("vtkAbstractMapper"),e.update=()=>{e.getInputData()},e.addClippingPlane=r=>!!r.isA("vtkPlane")&&!t.clippingPlanes.includes(r)&&(t.clippingPlanes.push(r),e.modified(),!0),e.getNumberOfClippingPlanes=()=>t.clippingPlanes.length,e.removeAllClippingPlanes=()=>0!==t.clippingPlanes.length&&(t.clippingPlanes.length=0,e.modified(),!0),e.removeClippingPlane=r=>{const n=t.clippingPlanes.indexOf(r);return-1!==n&&(t.clippingPlanes.splice(n,1),e.modified(),!0)},e.getClippingPlanes=()=>t.clippingPlanes,e.setClippingPlanes=t=>{if(t)if(Array.isArray(t)){const r=t.length;for(let n=0;n{const o=t.clippingPlanes,i=e;if(o){const e=o.length;if(r>=0&&r2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,(e=>({bounds:[...Va.INIT_BOUNDS],center:[0,0,0],viewSpecificProperties:{},...e}))(r)),Cs(e,t,r),zt.setGet(e,t,["viewSpecificProperties"]),function(e,t){e.getBounds=()=>(zt.vtkErrorMacro("vtkAbstractMapper3D.getBounds - NOT IMPLEMENTED"),Ei()),e.getCenter=()=>{const r=e.getBounds();return t.center=Va.isValid(r)?Va.getCenter(r):null,t.center?.slice()},e.getLength=()=>{const t=e.getBounds();return Va.getDiagonalLength(t)}}(e,t)};const{vtkErrorMacro:ws,vtkWarningMacro:As}=zt,Es={arrays:[],copyFieldFlags:[],doCopyAllOn:!0,doCopyAllOff:!1};function Ds(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Es,r),zt.obj(e,t),function(e,t){t.classHierarchy.push("vtkFieldData");const r=e.getState;t.arrays&&(t.arrays=t.arrays.map(e=>({data:Ge(e.data)}))),e.initialize=()=>{e.initializeFields(),e.copyAllOn(),e.clearFieldFlags()},e.initializeFields=()=>{t.arrays=[],t.copyFieldFlags={},e.modified()},e.copyStructure=r=>{e.initializeFields(),t.copyFieldFlags=r.getCopyFieldFlags().map(e=>e),t.arrays=r.getArrays().map(e=>({data:e}))},e.getNumberOfArrays=()=>t.arrays.length,e.getNumberOfActiveArrays=()=>t.arrays.length,e.addArray=r=>{const n=r.getName(),{array:o,index:i}=e.getArrayWithIndex(n);return null!=o?(t.arrays[i]={data:r},i):(t.arrays=[].concat(t.arrays,{data:r}),t.arrays.length-1)},e.removeAllArrays=()=>{t.arrays=[]},e.removeArray=r=>{const n=t.arrays.findIndex(e=>e.data.getName()===r);return e.removeArrayByIndex(n)},e.removeArrayByIndex=e=>-1!==e&&et.arrays.map(e=>e.data),e.getArray=t=>"number"==typeof t?e.getArrayByIndex(t):e.getArrayByName(t),e.getArrayByName=e=>t.arrays.reduce((t,r,n)=>r.data.getName()===e?r.data:t,null),e.getArrayWithIndex=e=>{const r=t.arrays.findIndex(t=>t.data.getName()===e);return{array:-1!==r?t.arrays[r].data:null,index:r}},e.getArrayByIndex=e=>e>=0&&ee.getArrayWithIndex(t).index>=0,e.getArrayName=e=>{const r=t.arrays[e];return r?r.data.getName():""},e.getCopyFieldFlags=()=>t.copyFieldFlags,e.getFlag=e=>t.copyFieldFlags[e],e.passData=function(r){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1;r.getArrays().forEach(i=>{const a=e.getFlag(i.getName());if(!1!==a&&(!t.doCopyAllOff||!0===a)&&i){let t=e.getArrayByName(i.getName());if(t)if(i.getNumberOfComponents()===t.getNumberOfComponents())if(n>-1&&n-1?o:n;t.insertTuple(e,i.getTuple(n))}else t.insertTuples(0,i.getTuples());else ws("Unhandled case in passData");else if(n<0||n>i.getNumberOfTuples())e.addArray(i),r.getAttributes(i).forEach(t=>{e.setAttribute(i,t)});else{const a=i.getNumberOfComponents();let s=i.getNumberOfValues();const l=o>-1?o:n;s<=l*a&&(s=(l+1)*a),t=_s.newInstance({name:i.getName(),dataType:i.getDataType(),numberOfComponents:a,values:zt.newTypedArray(i.getDataType(),s),size:0}),t.insertTuple(l,i.getTuple(n)),e.addArray(t),r.getAttributes(i).forEach(r=>{e.setAttribute(t,r)})}}})},e.interpolateData=function(r){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:-1,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:.5;r.getArrays().forEach(s=>{const l=e.getFlag(s.getName());if(!1!==l&&(!t.doCopyAllOff||!0===l)&&s){let t=e.getArrayByName(s.getName());if(t)if(s.getNumberOfComponents()===t.getNumberOfComponents())if(n>-1&&n-1?i:n;t.interpolateTuple(e,s,n,s,o,a),As("Unexpected case in interpolateData")}else t.insertTuples(s.getTuples());else ws("Unhandled case in interpolateData");else if(n<0||o<0||n>s.getNumberOfTuples())e.addArray(s),r.getAttributes(s).forEach(t=>{e.setAttribute(s,t)});else{const l=s.getNumberOfComponents();let u=s.getNumberOfValues();const c=i>-1?i:n;u<=c*l&&(u=(c+1)*l),t=_s.newInstance({name:s.getName(),dataType:s.getDataType(),numberOfComponents:l,values:zt.newTypedArray(s.getDataType(),u),size:0}),t.interpolateTuple(c,s,n,s,o,a),e.addArray(t),r.getAttributes(s).forEach(r=>{e.setAttribute(t,r)})}}})},e.copyFieldOn=e=>{t.copyFieldFlags[e]=!0},e.copyFieldOff=e=>{t.copyFieldFlags[e]=!1},e.copyAllOn=()=>{t.doCopyAllOn&&!t.doCopyAllOff||(t.doCopyAllOn=!0,t.doCopyAllOff=!1,e.modified())},e.copyAllOff=()=>{!t.doCopyAllOn&&t.doCopyAllOff||(t.doCopyAllOn=!1,t.doCopyAllOff=!0,e.modified())},e.clearFieldFlags=()=>{t.copyFieldFlags={}},e.deepCopy=e=>{t.arrays=e.getArrays().map(e=>{const t=e.newClone();return t.deepCopy(e),{data:t}})},e.copyFlags=e=>e.getCopyFieldFlags().map(e=>e),e.reset=()=>t.arrays.forEach(e=>e.data.reset()),e.getMTime=()=>t.arrays.reduce((e,t)=>t.data.getMTime()>e?t.data.getMTime():e,t.mtime),e.getNumberOfComponents=()=>t.arrays.reduce((e,t)=>e+t.data.getNumberOfComponents(),0),e.getNumberOfTuples=()=>t.arrays.length>0?t.arrays[0].getNumberOfTuples():0,e.getState=()=>{const e=r();return e&&(e.arrays=t.arrays.map(e=>({data:e.data.getState()}))),e}}(e,t)}var Ps={newInstance:zt.newInstance(Ds,"vtkFieldData"),extend:Ds};const Is={SCALARS:0,VECTORS:1,NORMALS:2,TCOORDS:3,TENSORS:4,GLOBALIDS:5,PEDIGREEIDS:6,EDGEFLAG:7,NUM_ATTRIBUTES:8};var Os={AttributeCopyOperations:{COPYTUPLE:0,INTERPOLATE:1,PASSDATA:2,ALLCOPY:3},AttributeLimitTypes:{MAX:0,EXACT:1,NOLIMIT:2},AttributeTypes:Is,CellGhostTypes:{DUPLICATECELL:1,HIGHCONNECTIVITYCELL:2,LOWCONNECTIVITYCELL:4,REFINEDCELL:8,EXTERIORCELL:16,HIDDENCELL:32},DesiredOutputPrecision:{DEFAULT:0,SINGLE:1,DOUBLE:2},PointGhostTypes:{DUPLICATEPOINT:1,HIDDENPOINT:2},ghostArrayName:"vtkGhostType"};const{AttributeTypes:Ns,AttributeCopyOperations:Ms}=Os,{vtkWarningMacro:Rs}=zt,Fs={activeScalars:-1,activeVectors:-1,activeTensors:-1,activeNormals:-1,activeTCoords:-1,activeGlobalIds:-1,activePedigreeIds:-1};function Bs(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Fs,r),Ps.extend(e,t,r),zt.setGet(e,t,["activeScalars","activeNormals","activeTCoords","activeVectors","activeTensors","activeGlobalIds","activePedigreeIds"]),t.arrays||(t.arrays={}),function(e,t){const r=["Scalars","Vectors","Normals","TCoords","Tensors","GlobalIds","PedigreeIds"];function n(e){let t=r.find(t=>Ns[t.toUpperCase()]===e||"number"!=typeof e&&t.toLowerCase()===e.toLowerCase());return void 0===t&&(t=null),t}t.classHierarchy.push("vtkDataSetAttributes");const o={...e};e.checkNumberOfComponents=e=>!0,e.setAttribute=(r,o)=>{const i=n(o);if(r&&"PEDIGREEIDS"===i.toUpperCase()&&!r.isA("vtkDataArray"))return Rs(`Cannot set attribute ${i}. The attribute must be a vtkDataArray.`),-1;if(r&&!e.checkNumberOfComponents(r,i))return Rs(`Cannot set attribute ${i}. Incorrect number of components.`),-1;if(r){const n=e.addArray(r);t[`active${i}`]=n}else t[`active${i}`]=-1;return e.modified(),t[`active${i}`]},e.getAttributes=t=>r.filter(r=>e[`get${r}`]()===t),e.setActiveAttributeByName=(t,r)=>e.setActiveAttributeByIndex(e.getArrayWithIndex(t).index,r),e.setActiveAttributeByIndex=(r,o)=>{const i=n(o);if(r>=0&&r{const r=n(t);return e[`get${r}`]()},e.removeAllArrays=()=>{r.forEach(e=>{t[`active${e}`]=-1}),o.removeAllArrays()},e.removeArrayByIndex=e=>(-1!==e&&r.forEach(r=>{e===t[`active${r}`]?t[`active${r}`]=-1:e{const n=`active${r}`;e[`get${r}`]=()=>e.getArrayByIndex(t[n]),e[`set${r}`]=t=>e.setAttribute(t,r),e[`setActive${r}`]=t=>e.setActiveAttributeByIndex(e.getArrayWithIndex(t).index,r),e[`copy${r}Off`]=()=>{const e=r.toUpperCase();t.copyAttributeFlags[Ms.PASSDATA][Ns[e]]=!1},e[`copy${r}On`]=()=>{const e=r.toUpperCase();t.copyAttributeFlags[Ms.PASSDATA][Ns[e]]=!0}}),e.initializeAttributeCopyFlags=()=>{t.copyAttributeFlags=[],Object.keys(Ms).filter(e=>"ALLCOPY"!==e).forEach(e=>{t.copyAttributeFlags[Ms[e]]=Object.keys(Ns).filter(e=>"NUM_ATTRIBUTES"!==e).reduce((e,t)=>(e[Ns[t]]=!0,e),[])}),t.copyAttributeFlags[Ms.COPYTUPLE][Ns.GLOBALIDS]=!1,t.copyAttributeFlags[Ms.INTERPOLATE][Ns.GLOBALIDS]=!1,t.copyAttributeFlags[Ms.COPYTUPLE][Ns.PEDIGREEIDS]=!1},e.initialize=zt.chain(e.initialize,e.initializeAttributeCopyFlags),t.dataArrays&&Object.keys(t.dataArrays).length&&Object.keys(t.dataArrays).forEach(r=>{t.dataArrays[r].ref||"vtkDataArray"!==t.dataArrays[r].type||e.addArray(_s.newInstance(t.dataArrays[r]))});const i=e.shallowCopy;e.shallowCopy=(e,r)=>{i(e,r),t.arrays=e.getArrays().map(e=>{const t=e.newClone();return t.shallowCopy(e,r),{data:t}})},e.initializeAttributeCopyFlags()}(e,t)}var Ls={newInstance:zt.newInstance(Bs,"vtkDataSetAttributes"),extend:Bs,...Os};const ks=["pointData","cellData","fieldData"],Us={};function Vs(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Us,r),zt.obj(e,t),zt.setGet(e,t,ks),zt.getArray(e,t,["bounds"],6),function(e,t){t.classHierarchy.push("vtkDataSet"),ks.forEach(e=>{t[e]?t[e]=Ge(t[e]):t[e]=Ls.newInstance()}),e.computeBounds=()=>{if(t.modifiedTime&&t.computeTime&&t.modifiedTime>t.computeTime||!t.computeTime){const r=e.getPoints();r?.getNumberOfPoints()?Va.setBounds(t.bounds,r.getBoundsByReference()):t.bounds=Oi.createUninitializedBounds(),t.computeTime=zt.getCurrentGlobalMTime()}},e.getLength2=()=>{const t=e.getBoundsByReference();return t&&6===t.length?Va.getDiagonalLength2(t):0},e.getLength=()=>Math.sqrt(e.getLength2()),e.getCenter=()=>{const t=e.getBoundsByReference();return t&&6===t.length?Va.getCenter(t):[0,0,0]},e.getCellBounds=t=>{const r=e.getCell(t);return r?r.getBounds():Oi.createUninitializedBounds()},e.getBounds=zt.chain(()=>e.computeBounds,e.getBounds),e.getBoundsByReference=zt.chain(()=>e.computeBounds,e.getBoundsByReference);const r=e.shallowCopy;e.shallowCopy=function(e){r(e,arguments.length>1&&void 0!==arguments[1]&&arguments[1]),ks.forEach(r=>{t[r]=Ls.newInstance(),t[r].shallowCopy(e.getReferenceByName(r))})};const n=e.getMTime;e.getMTime=()=>ks.reduce((e,r)=>Math.max(e,t[r]?.getMTime()??e),n()),e.initialize=()=>(ks.forEach(e=>t[e]?.initialize()),e)}(e,t)}var Gs={newInstance:zt.newInstance(Vs,"vtkDataSet"),extend:Vs,FieldDataTypes:{UNIFORM:0,DATA_OBJECT_FIELD:0,COORDINATE:1,POINT_DATA:1,POINT:2,POINT_FIELD_DATA:2,CELL:3,CELL_FIELD_DATA:3,VERTEX:4,VERTEX_FIELD_DATA:4,EDGE:5,EDGE_FIELD_DATA:5,ROW:6,ROW_DATA:6},FieldAssociations:{FIELD_ASSOCIATION_POINTS:0,FIELD_ASSOCIATION_CELLS:1,FIELD_ASSOCIATION_NONE:2,FIELD_ASSOCIATION_POINTS_THEN_CELLS:3,FIELD_ASSOCIATION_VERTICES:4,FIELD_ASSOCIATION_EDGES:5,FIELD_ASSOCIATION_ROWS:6,NUMBER_OF_ASSOCIATIONS:7}};const zs={UNCHANGED:0,SINGLE_POINT:1,X_LINE:2,Y_LINE:3,Z_LINE:4,XY_PLANE:5,YZ_PLANE:6,XZ_PLANE:7,XYZ_GRID:8,EMPTY:9};var js={StructuredType:zs};const{StructuredType:Ws}=js;var Hs={getDataDescriptionFromExtent:function(e){let t=0;for(let r=0;r<3;++r)e[2*r]e[1]||e[2]>e[3]||e[4]>e[5]?Ws.EMPTY:3===t?Ws.XYZ_GRID:2===t?e[0]===e[1]?Ws.YZ_PLANE:e[2]===e[3]?Ws.XZ_PLANE:Ws.XY_PLANE:1===t?e[0]2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Xs,r),Gs.extend(e,t,r),t.direction?Array.isArray(t.direction)&&(t.direction=new Float64Array(t.direction.slice(0,9))):t.direction=pe(new Float64Array(9)),t.indexToWorld=new Float64Array(16),t.worldToIndex=new Float64Array(16),zt.get(e,t,["indexToWorld","worldToIndex"]),zt.setGetArray(e,t,["origin","spacing"],3),zt.setGetArray(e,t,["direction"],9),zt.getArray(e,t,["extent"],6),function(e,t){t.classHierarchy.push("vtkImageData"),e.setExtent=function(){if(t.deleted)return Ks("instance deleted - cannot call any method"),!1;for(var r=arguments.length,n=new Array(r),o=0;oe!==i[t]);return a&&(t.extent=i.slice(),t.dataDescription=Hs.getDataDescriptionFromExtent(t.extent),e.modified()),a},e.setDimensions=function(){let r,n,o;if(t.deleted)Ks("instance deleted - cannot call any method");else{if(1===arguments.length){const e=arguments.length<=0?void 0:arguments[0];r=e[0],n=e[1],o=e[2]}else{if(3!==arguments.length)return void Ks("Bad dimension specification");r=arguments.length<=0?void 0:arguments[0],n=arguments.length<=1?void 0:arguments[1],o=arguments.length<=2?void 0:arguments[2]}e.setExtent(0,r-1,0,n-1,0,o-1)}},e.getDimensions=()=>[t.extent[1]-t.extent[0]+1,t.extent[3]-t.extent[2]+1,t.extent[5]-t.extent[4]+1],e.getNumberOfCells=()=>{const t=e.getDimensions();let r=1;for(let e=0;e<3;e++){if(0===t[e])return 0;t[e]>1&&(r*=t[e]-1)}return r},e.getNumberOfPoints=()=>{const t=e.getDimensions();return t[0]*t[1]*t[2]},e.getPoint=r=>{const n=e.getDimensions();if(0===n[0]||0===n[1]||0===n[2])return Ks("Requesting a point from an empty image."),null;const o=new Float64Array(3);switch(t.dataDescription){case zs.EMPTY:return null;case zs.SINGLE_POINT:break;case zs.X_LINE:o[0]=r;break;case zs.Y_LINE:o[1]=r;break;case zs.Z_LINE:o[2]=r;break;case zs.XY_PLANE:o[0]=r%n[0],o[1]=r/n[0];break;case zs.YZ_PLANE:o[1]=r%n[1],o[2]=r/n[1];break;case zs.XZ_PLANE:o[0]=r%n[0],o[2]=r/n[0];break;case zs.XYZ_GRID:o[0]=r%n[0],o[1]=r/n[0]%n[1],o[2]=r/(n[0]*n[1]);break;default:Ks("Invalid dataDescription")}const i=[0,0,0];return e.indexToWorld(o,i),i},e.getBounds=()=>e.extentToBounds(e.getSpatialExtent()),e.extentToBounds=e=>Va.transformBounds(e,t.indexToWorld),e.getSpatialExtent=()=>Va.inflate([...t.extent],.5),e.computeTransforms=()=>{A(t.indexToWorld,t.origin),t.indexToWorld[0]=t.direction[0],t.indexToWorld[1]=t.direction[1],t.indexToWorld[2]=t.direction[2],t.indexToWorld[4]=t.direction[3],t.indexToWorld[5]=t.direction[4],t.indexToWorld[6]=t.direction[5],t.indexToWorld[8]=t.direction[6],t.indexToWorld[9]=t.direction[7],t.indexToWorld[10]=t.direction[8],_(t.indexToWorld,t.indexToWorld,t.spacing),g(t.worldToIndex,t.indexToWorld)},e.indexToWorld=function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return Sr(r,e,t.indexToWorld),r},e.indexToWorldVec3=e.indexToWorld,e.worldToIndex=function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return Sr(r,e,t.worldToIndex),r},e.worldToIndexVec3=e.worldToIndex,e.indexToWorldBounds=function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return Va.transformBounds(e,t.indexToWorld,r)},e.worldToIndexBounds=function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return Va.transformBounds(e,t.worldToIndex,r)},t._onOriginChanged=e.computeTransforms,t._onDirectionChanged=e.computeTransforms,t._onSpacingChanged=e.computeTransforms,e.computeTransforms(),e.getCenter=()=>Va.getCenter(e.getBounds()),e.computeHistogram=function(t){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;const n=[0,0,0,0,0,0];e.worldToIndexBounds(t,n);const o=[0,0,0],i=[0,0,0];Va.computeCornerPoints(n,o,i),Zo(o,o),Zo(i,i);const a=e.getDimensions();xi(o,[0,0,0],[a[0]-1,a[1]-1,a[2]-1],o),xi(i,[0,0,0],[a[0]-1,a[1]-1,a[2]-1],i);const s=a[0],l=a[0]*a[1],u=e.getPointData().getScalars().getData();let c=-1/0,d=1/0,p=0,f=0,h=0;for(let e=o[2];e<=i[2];e++)for(let t=o[1];t<=i[1];t++){let a=o[0]+t*s+e*l;for(let s=o[0];s<=i[0];s++){if(!r||r([s,t,e],n)){const e=u[a];e>c&&(c=e),e0?f/h:0,g=h?Math.abs(p/h-m*m):0;return{minimum:d,maximum:c,average:m,variance:g,sigma:Math.sqrt(g),count:h}},e.computeIncrements=function(e){const t=[];let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;for(let n=0;n<3;++n)t[n]=r,r*=e[2*n+1]-e[2*n]+1;return t},e.computeOffsetIndex=t=>{let[r,n,o]=t;const i=e.getExtent(),a=e.getPointData().getScalars().getNumberOfComponents(),s=e.computeIncrements(i,a);return Math.floor((Math.round(r)-i[0])*s[0]+(Math.round(n)-i[2])*s[1]+(Math.round(o)-i[4])*s[2])},e.getOffsetIndexFromWorld=t=>{const r=e.getExtent(),n=e.worldToIndex(t);for(let e=0;e<3;++e)if(n[e]r[2*e+1])return Ks(`GetScalarPointer: Pixel ${n} is not in memory. Current extent = ${r}`),NaN;return e.computeOffsetIndex(n)},e.getScalarValueFromWorld=function(t){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;const n=e.getPointData().getScalars().getNumberOfComponents();if(r<0||r>=n)return Ks(`GetScalarPointer: Scalar Component ${r} is not within bounds. Current Scalar numberOfComponents: ${n}`),NaN;const o=e.getOffsetIndexFromWorld(t);return Number.isNaN(o)?o:e.getPointData().getScalars().getComponent(o,r)};const r=e.initialize;e.initialize=()=>(e.set({direction:pe(t.direction),spacing:[1,1,1],origin:[0,0,0],extent:[0,-1,0,-1,0,-1],dataDescription:zs.EMPTY}),r())}(e,t)}var qs={newInstance:zt.newInstance($s,"vtkImageData"),extend:$s};const Ys={LUMINANCE:1,LUMINANCE_ALPHA:2,RGB:3,RGBA:4};var Js={VectorMode:{MAGNITUDE:0,COMPONENT:1,RGBCOLORS:2},ScalarMappingTarget:Ys,Scale:{LINEAR:0,LOG10:1}},Qs={ColorMode:{DEFAULT:0,MAP_SCALARS:1,DIRECT_SCALARS:2},GetArray:{BY_ID:0,BY_NAME:1},ScalarMode:{DEFAULT:0,USE_POINT_DATA:1,USE_CELL_DATA:2,USE_POINT_FIELD_DATA:3,USE_CELL_FIELD_DATA:4,USE_FIELD_DATA:5}};const{ScalarMappingTarget:Zs,Scale:el,VectorMode:tl}=Js,{VtkDataTypes:rl}=_s,{ColorMode:nl}=Qs,{vtkErrorMacro:ol}=zt;function il(e){return e}function al(e){return Math.floor(255*e+.5)}const sl={alpha:1,vectorComponent:0,vectorSize:-1,vectorMode:tl.COMPONENT,mappingRange:null,annotationArray:null,annotatedValueMap:null,indexedLookup:!1,scale:el.LINEAR};function ll(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,sl,r),zt.obj(e,t),t.mappingRange=[0,255],t.annotationArray=[],t.annotatedValueMap=[],zt.setGet(e,t,["vectorSize","vectorComponent","vectorMode","alpha","indexedLookup"]),zt.setArray(e,t,["mappingRange"],2),zt.getArray(e,t,["mappingRange"]),function(e,t){t.classHierarchy.push("vtkScalarsToColors"),e.setVectorModeToMagnitude=()=>e.setVectorMode(tl.MAGNITUDE),e.setVectorModeToComponent=()=>e.setVectorMode(tl.COMPONENT),e.setVectorModeToRGBColors=()=>e.setVectorMode(tl.RGBCOLORS),e.build=()=>{},e.isOpaque=()=>!0,e.setAnnotations=(r,n)=>{if(!(r&&!n||!r&&n))if(r&&n&&r.length!==n.length)ol("Values and annotations do not have the same number of tuples so ignoring");else{if(t.annotationArray=[],n&&r){const e=n.length;for(let o=0;o{let o=e.checkForAnnotatedValue(r),i=!1;return o>=0?t.annotationArray[o].annotation!==n&&(t.annotationArray[o].annotation=n,i=!0):(t.annotationArray.push({value:r,annotation:n}),o=t.annotationArray.length-1,i=!0),i&&(e.updateAnnotatedValueMap(),e.modified()),o},e.getNumberOfAnnotatedValues=()=>t.annotationArray.length,e.getAnnotatedValue=e=>e<0||e>=t.annotationArray.length?null:t.annotationArray[e].value,e.getAnnotation=e=>void 0===t.annotationArray[e]?null:t.annotationArray[e].annotation,e.getAnnotatedValueIndex=r=>t.annotationArray.length?e.checkForAnnotatedValue(r):-1,e.removeAnnotation=r=>{const n=e.checkForAnnotatedValue(r),o=n>=0;return o&&(t.annotationArray.splice(n,1),e.updateAnnotatedValueMap(),e.modified()),o},e.resetAnnotations=()=>{t.annotationArray=[],t.annotatedValueMap=[],e.modified()},e.getAnnotationColor=(r,n)=>{if(t.indexedLookup){const t=e.getAnnotatedValueIndex(r);e.getIndexedColor(t,n)}else e.getColor(parseFloat(r),n),n[3]=1},e.checkForAnnotatedValue=t=>e.getAnnotatedValueIndexInternal(t),e.getAnnotatedValueIndexInternal=e=>{if(void 0!==t.annotatedValueMap[e]){const r=t.annotationArray.length;return t.annotatedValueMap[e]%r}return-1},e.getIndexedColor=(e,t)=>{t[0]=0,t[1]=0,t[2]=0,t[3]=0},e.updateAnnotatedValueMap=()=>{t.annotatedValueMap=[];const e=t.annotationArray.length;for(let r=0;r{const o=t.getNumberOfComponents();let i=null;if(r===nl.DEFAULT&&(t.getDataType()===rl.UNSIGNED_CHAR||t.getDataType()===rl.UNSIGNED_CHAR_CLAMPED)||r===nl.DIRECT_SCALARS&&t)i=e.convertToRGBA(t,o,t.getNumberOfTuples());else{const r={type:"vtkDataArray",name:"temp",numberOfComponents:4,dataType:rl.UNSIGNED_CHAR},a=zt.newTypedArray(r.dataType,4*t.getNumberOfTuples());r.values=a,r.size=a.length,i=_s.newInstance(r);let s=n;s<0&&o>1?e.mapVectorsThroughTable(t,i,Zs.RGBA,-1,-1):(s<0&&(s=0),s>=o&&(s=o-1),e.mapScalarsThroughTable(t,i,Zs.RGBA,s))}return i},e.mapVectorsToMagnitude=(e,t,r)=>{const n=e.getNumberOfTuples(),o=e.getNumberOfComponents(),i=t.getData(),a=e.getData();for(let e=0;e{let a=e.getVectorMode(),s=i,l=o;const u=t.getNumberOfComponents();a===tl.COMPONENT?(-1===l&&(l=e.getVectorComponent()),l<0&&(l=0),l>=u&&(l=u-1)):(-1===s&&(s=e.getVectorSize()),s<=0?(l=0,s=u):(l<0&&(l=0),l>=u&&(l=u-1),l+s>u&&(s=u-l)),a!==tl.MAGNITUDE||1!==u&&1!==s||(a=tl.COMPONENT));let c=0;switch(l>0&&(c=l),a){case tl.COMPONENT:e.mapScalarsThroughTable(t,r,n,c);break;case tl.RGBCOLORS:break;case tl.MAGNITUDE:default:{const o=_s.newInstance({numberOfComponents:1,values:new Float32Array(t.getNumberOfTuples())});e.mapVectorsToMagnitude(t,o,s),e.mapScalarsThroughTable(o,r,n,0);break}}},e.luminanceToRGBA=(e,t,r,n)=>{const o=n(r),i=t.getData(),a=e.getData(),s=i.length;let l=0;for(let e=0;e{const o=t.getData(),i=e.getData(),a=o.length;let s=0;for(let e=0;e{const o=al(r),i=t.getData(),a=e.getData(),s=i.length;let l=0;for(let e=0;e{const o=t.getData(),i=e.getData(),a=o.length;let s=0;for(let e=0;e{let{alpha:i}=t;if(4===n&&i>=1&&r.getDataType()===rl.UNSIGNED_CHAR)return r;const a=_s.newInstance({numberOfComponents:4,empty:!0,size:4*o,dataType:rl.UNSIGNED_CHAR});if(o<=0)return a;i=i>0?i:0,i=i<1?i:1;let s=il;switch(r.getDataType()!==rl.FLOAT&&r.getDataType()!==rl.DOUBLE||(s=al),n){case 1:e.luminanceToRGBA(a,r,i,s);break;case 2:e.luminanceAlphaToRGBA(a,r,s);break;case 3:e.rGBToRGBA(a,r,i,s);break;case 4:e.rGBAToRGBA(a,r,i,s);break;default:return ol("Cannot convert colors"),null}return a},e.usingLogScale=()=>!1,e.getNumberOfAvailableColors=()=>16777216,e.setRange=(t,r)=>e.setMappingRange(t,r),e.getRange=()=>e.getMappingRange(),e.areScalarsOpaque=(r,n,o)=>{if(!r)return e.isOpaque();const i=r.getNumberOfComponents();return(n!==nl.DEFAULT||r.getDataType()!==rl.UNSIGNED_CHAR)&&n!==nl.DIRECT_SCALARS||(3===i||1===i?t.alpha>=1:255===r.getRange(i-1)[0])}}(e,t)}var ul={newInstance:zt.newInstance(ll,"vtkScalarsToColors"),extend:ll,...Js};const{vtkErrorMacro:cl}=zt,dl={numberOfColors:256,hueRange:[0,.66667],saturationRange:[1,1],valueRange:[1,1],alphaRange:[1,1],nanColor:[.5,0,0,1],belowRangeColor:[0,0,0,1],aboveRangeColor:[1,1,1,1],useAboveRangeColor:!1,useBelowRangeColor:!1,alpha:1};function pl(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,dl,r),ul.extend(e,t,r),t.table||(t.table=[]),t.buildTime={},zt.obj(t.buildTime),t.opaqueFlagBuildTime={},zt.obj(t.opaqueFlagBuildTime,{mtime:0}),t.insertTime={},zt.obj(t.insertTime,{mtime:0}),zt.get(e,t,["buildTime"]),zt.setGet(e,t,["numberOfColors","useAboveRangeColor","useBelowRangeColor"]),zt.setArray(e,t,["alphaRange","hueRange","saturationRange","valueRange"],2),zt.setArray(e,t,["nanColor","belowRangeColor","aboveRangeColor"],4),zt.getArray(e,t,["hueRange","saturationRange","valueRange","alphaRange","nanColor","belowRangeColor","aboveRangeColor"]),function(e,t){t.classHierarchy.push("vtkLookupTable"),e.isOpaque=()=>{if(t.opaqueFlagBuildTime.getMTime()!1,e.getNumberOfAvailableColors=()=>t.table.length/4-3,e.linearIndexLookup=(e,t)=>{let r=0;const n=Number(e);return nt.range[1]?r=t.maxIndex+1+1.5:(r=(n+t.shift)*t.scale,r=r{let o=0;o=Ai(t)?Math.floor(n.maxIndex+1.5+2):e.linearIndexLookup(t,n);const i=4*o;return r.slice(i,i+4)},e.indexedLookupFunction=(r,n,o)=>{let i=e.getAnnotatedValueIndexInternal(r);-1===i&&(i=t.numberOfColors+2);const a=4*i;return[n[a],n[a+1],n[a+2],n[a+3]]},e.lookupShiftAndScale=(e,t)=>{t.shift=-e[0],t.scale=Number.MAX_VALUE,e[1]>e[0]&&(t.scale=(t.maxIndex+1)/(e[1]-e[0]))},e.mapScalarsThroughTable=(r,n,o,i)=>{let a=e.linearLookup;t.indexedLookup&&(a=e.indexedLookupFunction);const s=e.getMappingRange(),l={maxIndex:e.getNumberOfColors()-1,range:s,shift:0,scale:0};e.lookupShiftAndScale(s,l);const u=e.getAlpha(),c=r.getNumberOfTuples(),d=r.getNumberOfComponents(),p=n.getData(),f=r.getData();if(u>=1){if(o===Ys.RGBA)for(let e=0;e{let r=0,n=0,o=0,i=0;const a=t.numberOfColors-1;a&&(r=(t.hueRange[1]-t.hueRange[0])/a,n=(t.saturationRange[1]-t.saturationRange[0])/a,o=(t.valueRange[1]-t.valueRange[0])/a,i=(t.alphaRange[1]-t.alphaRange[0])/a),t.table.length=4*a+16;const s=[],l=[];for(let e=0;e<=a;e++)s[0]=t.hueRange[0]+e*r,s[1]=t.saturationRange[0]+e*n,s[2]=t.valueRange[0]+e*o,ci(s,l),l[3]=t.alphaRange[0]+e*i,t.table[4*e]=255*l[0]+.5,t.table[4*e+1]=255*l[1]+.5,t.table[4*e+2]=255*l[2]+.5,t.table[4*e+3]=255*l[3]+.5;e.buildSpecialColors(),t.buildTime.modified()},e.setTable=r=>{if(Array.isArray(r)){const n=r[0].length;t.numberOfColors=r.length;const o=4-n;let i=0;for(let e=0;e{const{numberOfColors:e}=t,r=t.table;let n=4*(e+0);t.useBelowRangeColor||0===e?(r[n]=255*t.belowRangeColor[0]+.5,r[n+1]=255*t.belowRangeColor[1]+.5,r[n+2]=255*t.belowRangeColor[2]+.5,r[n+3]=255*t.belowRangeColor[3]+.5):(r[n]=r[0],r[n+1]=r[1],r[n+2]=r[2],r[n+3]=r[3]),n=4*(e+1),t.useAboveRangeColor||0===e?(r[n]=255*t.aboveRangeColor[0]+.5,r[n+1]=255*t.aboveRangeColor[1]+.5,r[n+2]=255*t.aboveRangeColor[2]+.5,r[n+3]=255*t.aboveRangeColor[3]+.5):(r[n]=r[4*(e-1)+0],r[n+1]=r[4*(e-1)+1],r[n+2]=r[4*(e-1)+2],r[n+3]=r[4*(e-1)+3]),n=4*(e+2),r[n]=255*t.nanColor[0]+.5,r[n+1]=255*t.nanColor[1]+.5,r[n+2]=255*t.nanColor[2]+.5,r[n+3]=255*t.nanColor[3]+.5},e.build=()=>{(t.table.length<1||e.getMTime()>t.buildTime.getMTime()&&t.insertTime.getMTime()<=t.buildTime.getMTime())&&e.forceBuild()},t.table.length>0&&(e.buildSpecialColors(),t.insertTime.modified())}(e,t)}var fl={newInstance:zt.newInstance(pl,"vtkLookupTable"),extend:pl};const hl={Off:0,PolygonOffset:1};let ml=hl.PolygonOffset,gl=hl.Off;const yl=["VTK_RESOLVE_OFF","VTK_RESOLVE_POLYGON_OFFSET"];function vl(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;const t=gl===e;return gl=e,t}var bl={Resolve:hl,getResolveCoincidentTopologyAsString:function(){return yl[gl]},getResolveCoincidentTopologyPolygonOffsetFaces:function(){return ml},getResolveCoincidentTopology:function(){return gl},setResolveCoincidentTopology:vl,setResolveCoincidentTopologyPolygonOffsetFaces:function(e){const t=ml===e;return ml=e,t},setResolveCoincidentTopologyToDefault:function(){return vl(hl.Off)},setResolveCoincidentTopologyToOff:function(){return vl(hl.Off)},setResolveCoincidentTopologyToPolygonOffset:function(){return vl(hl.PolygonOffset)}};function xl(e,t,r){r.forEach(r=>{e[`get${r.method}`]=()=>t[r.key],e[`set${r.method}`]=zt.objectSetterMap.object(e,t,{name:r.key,params:["factor","offset"]})})}const _l=["Polygon","Line","Point"],Sl={modified:()=>{}};xl(Sl,{Polygon:{factor:2,offset:0},Line:{factor:1,offset:-1},Point:{factor:0,offset:-2}},_l.map(e=>({key:e,method:`ResolveCoincidentTopology${e}OffsetParameters`})));var Cl={implementCoincidentTopologyMethods:function(e,t){void 0===t.resolveCoincidentTopology&&(t.resolveCoincidentTopology=!1),zt.setGet(e,t,["resolveCoincidentTopology"]),t.topologyOffset={Polygon:{factor:0,offset:0},Line:{factor:0,offset:0},Point:{factor:0,offset:0}},Object.keys(bl).forEach(t=>{e[t]=bl[t]}),Object.keys(Sl).filter(e=>"modified"!==e).forEach(t=>{e[t]=Sl[t]}),xl(e,t.topologyOffset,_l.map(e=>({key:e,method:`RelativeCoincidentTopology${e}OffsetParameters`}))),e.getCoincidentTopologyPolygonOffsetParameters=()=>{const t=Sl.getResolveCoincidentTopologyPolygonOffsetParameters(),r=e.getRelativeCoincidentTopologyPolygonOffsetParameters();return{factor:t.factor+r.factor,offset:t.offset+r.offset}},e.getCoincidentTopologyLineOffsetParameters=()=>{const t=Sl.getResolveCoincidentTopologyLineOffsetParameters(),r=e.getRelativeCoincidentTopologyLineOffsetParameters();return{factor:t.factor+r.factor,offset:t.offset+r.offset}},e.getCoincidentTopologyPointOffsetParameter=()=>{const t=Sl.getResolveCoincidentTopologyPointOffsetParameters(),r=e.getRelativeCoincidentTopologyPointOffsetParameters();return{factor:t.factor+r.factor,offset:t.offset+r.offset}}},staticOffsetAPI:Sl,otherStaticMethods:bl,CATEGORIES:_l,Resolve:hl};const Tl={MIN_KNOWN_PASS:0,ACTOR_PASS:0,COMPOSITE_INDEX_PASS:1,ID_LOW24:2,ID_HIGH24:3,MAX_KNOWN_PASS:3};var wl={PassTypes:Tl};const{FieldAssociations:Al}=Gs,{staticOffsetAPI:El,otherStaticMethods:Dl}=Cl,{ColorMode:Pl,ScalarMode:Il,GetArray:Ol}=Qs,{VectorMode:Nl}=Js,{VtkDataTypes:Ml}=_s;function Rl(e){return()=>zt.vtkErrorMacro(`vtkMapper::${e} - NOT IMPLEMENTED`)}function Fl(e,t){const r=e[1]%2==0?1:-1;if(e[0]+=r,e[0]>=t[0]||e[0]<0){const n=e[2]%2==0?1:-1;e[0]-=r,e[1]+=n,(e[1]>=t[1]||e[1]<0)&&(e[1]-=n,e[2]++)}}function Bl(e,t){return e[0]+t[0]*(e[1]+t[1]*e[2])}function Ll(e,t,r){const n=Math.floor(t),o=n%(2*r[0]);let i,a;o2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Ul,r),Ts(e,t,r),zt.get(e,t,["areScalarsMappedFromCells","colorCoordinates","colorMapColors","colorTextureMap","numberOfColorsInRange","selectionWebGLIdsToVTKIds"]),zt.setGet(e,t,["colorByArrayName","arrayAccessMode","colorMode","fieldDataTupleId","interpolateScalarsBeforeMapping","lookupTable","populateSelectionSettings","renderTime","scalarMode","scalarVisibility","static","useLookupTableScalarRange","customShaderAttributes"]),zt.setGetArray(e,t,["scalarRange"],2),Cl.implementCoincidentTopologyMethods(e,t),function(e,t){t.classHierarchy.push("vtkMapper"),e.getBounds=()=>{const r=e.getInputData();return r?(t.static||e.update(),t.bounds=r.getBounds()):t.bounds=Ei(),t.bounds},e.setForceCompileOnly=e=>{t.forceCompileOnly=e},e.setSelectionWebGLIdsToVTKIds=e=>{t.selectionWebGLIdsToVTKIds=e},e.createDefaultLookupTable=()=>{t.lookupTable=fl.newInstance()},e.getColorModeAsString=()=>zt.enumToString(Pl,t.colorMode),e.setColorModeToDefault=()=>e.setColorMode(0),e.setColorModeToMapScalars=()=>e.setColorMode(1),e.setColorModeToDirectScalars=()=>e.setColorMode(2),e.getScalarModeAsString=()=>zt.enumToString(Il,t.scalarMode),e.setScalarModeToDefault=()=>e.setScalarMode(0),e.setScalarModeToUsePointData=()=>e.setScalarMode(1),e.setScalarModeToUseCellData=()=>e.setScalarMode(2),e.setScalarModeToUsePointFieldData=()=>e.setScalarMode(3),e.setScalarModeToUseCellFieldData=()=>e.setScalarMode(4),e.setScalarModeToUseFieldData=()=>e.setScalarMode(5),e.getAbstractScalars=(e,r,n,o,i)=>{if(!e||!t.scalarVisibility)return{scalars:null,cellFlag:!1};let a=null,s=!1;if(r===Il.DEFAULT)a=e.getPointData().getScalars(),a||(a=e.getCellData().getScalars(),s=!0);else if(r===Il.USE_POINT_DATA)a=e.getPointData().getScalars();else if(r===Il.USE_CELL_DATA)a=e.getCellData().getScalars(),s=!0;else if(r===Il.USE_POINT_FIELD_DATA){const t=e.getPointData();a=n===Ol.BY_ID?t.getArrayByIndex(o):t.getArrayByName(i)}else if(r===Il.USE_CELL_FIELD_DATA){const t=e.getCellData();s=!0,a=n===Ol.BY_ID?t.getArrayByIndex(o):t.getArrayByName(i)}else if(r===Il.USE_FIELD_DATA){const t=e.getFieldData();a=n===Ol.BY_ID?t.getArrayByIndex(o):t.getArrayByName(i)}return{scalars:a,cellFlag:s}},e.mapScalars=(r,n)=>{const{scalars:o,cellFlag:i}=e.getAbstractScalars(r,t.scalarMode,t.arrayAccessMode,t.arrayId,t.colorByArrayName);if(t.areScalarsMappedFromCells=i,!o)return t.colorCoordinates=null,t.colorTextureMap=null,void(t.colorMapColors=null);const a=`${e.getMTime()}${o.getMTime()}${n}`;if(t.colorBuildString!==a){if(t.useLookupTableScalarRange||e.getLookupTable().setRange(t.scalarRange[0],t.scalarRange[1]),e.canUseTextureMapForColoring(o,i))t.mapScalarsToTexture(o,i,n);else{t.colorCoordinates=null,t.colorTextureMap=null;const r=e.getLookupTable();r&&(r.build(),t.colorMapColors=r.mapScalars(o,t.colorMode,t.fieldDataTupleId))}t.colorBuildString=`${e.getMTime()}${o.getMTime()}${n}`}},t.mapScalarsToTexture=(r,n,o)=>{const i=t.lookupTable.getRange(),a=t.lookupTable.usingLogScale(),s=t.lookupTable.getAlpha(),l=a?[Math.log10(i[0]),Math.log10(i[1])]:i;if(t.colorMapColors=null,null==t.colorTextureMap||e.getMTime()>t.colorTextureMap.getMTime()||t.lookupTable.getMTime()>t.colorTextureMap.getMTime()||t.lookupTable.getAlpha()!==o){t.lookupTable.setAlpha(o),t.colorTextureMap=null,t.lookupTable.build();const e=t.lookupTable.getNumberOfAvailableColors(),r=2048,i=2,u=n?r**3-3:4094;t.numberOfColorsInRange=Math.min(Math.max(e,i),u);const c=t.numberOfColorsInRange+3,d=t.numberOfColorsInRange+2,p=n?[Math.min(Math.ceil(c/r**0),r),Math.min(Math.ceil(c/r**1),r),Math.min(Math.ceil(c/r**2),r)]:[d,2,1],f=p[0]*p[1]*p[2],h=new Float64Array(f);h.fill(NaN);const m=t.numberOfColorsInRange,g=m+2,y=[0,0,0],v=l[0],b=l[1]-l[0];for(let e=0;e1?-1:t.lookupTable.getVectorComponent();t.colorCoordinates=function(e,t,r,n,o,i,a){const s=new Array(arguments.length);for(let e=0;e=b,_=i[2]<=1?2:3,S=_s.newInstance({numberOfComponents:_,values:new Float32Array(v*_)}),C=S.getData(),T=[0,0,0];Ll(T,o+2,i);let w=0,A=0;const E=[.5,.5,.5];for(let e=0;eo&&(t=o+1),Ll(E,t,i)}else{E[1]=.49;const t=(e-f)*h;E[0]=t>1e3?1e3:t<-1e3?-1e3:t}for(let e=0;e<_;++e)C[A++]=E[e]}return kl.set(e,{stringHash:l,textureCoordinates:S}),S}(r,u,l,a,t.numberOfColorsInRange,t.colorTextureMap.getDimensions(),n)},e.getIsOpaque=()=>{const r=e.getInputData(),n=e.getAbstractScalars(r,t.scalarMode,t.arrayAccessMode,t.arrayId,t.colorByArrayName).scalars;if(!t.scalarVisibility||null==n)return!0;const o=e.getLookupTable();return!o||(o.build(),o.areScalarsOpaque(n,t.colorMode,-1))},e.canUseTextureMapForColoring=(e,r)=>!((!r||t.colorMode===Pl.DIRECT_SCALARS)&&(!t.interpolateScalarsBeforeMapping||t.lookupTable&&t.lookupTable.getIndexedLookup()||!e||t.colorMode===Pl.DEFAULT&&e.getDataType()===Ml.UNSIGNED_CHAR||t.colorMode===Pl.DIRECT_SCALARS)),e.clearColorArrays=()=>{t.colorMapColors=null,t.colorCoordinates=null,t.colorTextureMap=null},e.getLookupTable=()=>(t.lookupTable||e.createDefaultLookupTable(),t.lookupTable),e.getMTime=()=>{let e=t.mtime;if(null!==t.lookupTable){const r=t.lookupTable.getMTime();e=r>e?r:e}return e},e.getPrimitiveCount=()=>{const t=e.getInputData();return{points:t.getPoints().getNumberOfValues()/3,verts:t.getVerts().getNumberOfValues()-t.getVerts().getNumberOfCells(),lines:t.getLines().getNumberOfValues()-2*t.getLines().getNumberOfCells(),triangles:t.getPolys().getNumberOfValues()-3*t.getPolys().getNumberOfCells()}},e.acquireInvertibleLookupTable=Rl("AcquireInvertibleLookupTable"),e.valueToColor=Rl("ValueToColor"),e.colorToValue=Rl("ColorToValue"),e.useInvertibleColorFor=Rl("UseInvertibleColorFor"),e.clearInvertibleColor=Rl("ClearInvertibleColor"),e.processSelectorPixelBuffers=(e,r)=>{if(!e||!t.selectionWebGLIdsToVTKIds||!t.populateSelectionSettings)return;const n=e.getRawPixelBuffer(Tl.ID_LOW24),o=e.getRawPixelBuffer(Tl.ID_HIGH24),i=e.getCurrentPass(),a=e.getFieldAssociation();let s=null;a===Al.FIELD_ASSOCIATION_POINTS?s=t.selectionWebGLIdsToVTKIds.points:a===Al.FIELD_ASSOCIATION_CELLS&&(s=t.selectionWebGLIdsToVTKIds.cells),s&&r.forEach(t=>{if(i===Tl.ID_LOW24){let r=0;o&&(r+=o[t],r*=256),r+=n[t+2],r*=256,r+=n[t+1],r*=256,r+=n[t];const i=s[r],a=e.getPixelBuffer(Tl.ID_LOW24);a[t]=255&i,a[t+1]=(65280&i)>>8,a[t+2]=(16711680&i)>>16}else if(i===Tl.ID_HIGH24&&o){let r=0;r+=o[t],r*=256,r+=n[t+2],r*=256,r+=n[t+1],r*=256,r+=n[t];const i=s[r];e.getPixelBuffer(Tl.ID_HIGH24)[t]=(4278190080&i)>>24}})}}(e,t)}var Gl={newInstance:zt.newInstance(Vl,"vtkMapper"),extend:Vl,...El,...Dl,...Qs};const{isVtkObject:zl}=zt;function jl(e){let t=0;return e.filter((e,r)=>r===t&&(t+=e+1,!0))}function Wl(e){let t=0;for(let r=0;r2&&void 0!==arguments[2]?arguments[2]:{};_s.extend(e,t,function(e){return{empty:!0,numberOfComponents:1,dataType:us.UNSIGNED_INT,...e}}(r)),function(e,t){t.classHierarchy.push("vtkCellArray");const r={...e};e.getNumberOfCells=r=>void 0===t.numberOfCells||r?(t.cellSizes?t.numberOfCells=t.cellSizes.length:t.numberOfCells=Wl(e.getData()),t.numberOfCells):t.numberOfCells,e.getCellSizes=r=>void 0===t.cellSizes||r?(t.cellSizes=jl(e.getData()),t.cellSizes):t.cellSizes,e.resize=n=>{const o=e.getNumberOfTuples();r.resize(n);const i=e.getNumberOfTuples();i{r.setData(e,1),t.numberOfCells=void 0,t.cellSizes=void 0},e.getCell=e=>{let r=e;const n=t.values[r++];return t.values.subarray(r,r+n)},e.insertNextCell=r=>{let n;n=zl(r)?r.getPointsIds():r;const o=e.getNumberOfCells();return e.insertNextTuples([n.length,...n]),++t.numberOfCells,null!=t.cellSizes&&t.cellSizes.push(n.length),o},e.getMaxCellSize=()=>e.getCellSizes().reduce((e,t)=>Math.max(e,t),0)}(e,t)}var Xl={newInstance:zt.newInstance(Kl,"vtkCellArray"),extend:Kl,...Hl};const{vtkErrorMacro:$l}=zt,ql={empty:!0,numberOfComponents:3,dataType:us.FLOAT,bounds:[1,-1,1,-1,1,-1]};function Yl(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,ql,r),_s.extend(e,t,r),zt.getArray(e,t,["bounds"],6),function(e,t){let r=0;t.classHierarchy.push("vtkPoints"),e.getNumberOfPoints=e.getNumberOfTuples,e.setNumberOfPoints=function(r){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:3;e.getNumberOfPoints()!==r&&(t.size=r*n,t.values=zt.newTypedArray(t.dataType,t.size),e.setNumberOfComponents(n),e.modified())},e.setPoint=function(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;oe.insertNextTuple([t,r,n]),e.insertPoint=(t,r)=>e.insertTuple(t,r);const n=e.getBounds;e.getBounds=()=>(r(r{if(3===e.getNumberOfComponents()){const r=e.getRange(0);t.bounds[0]=r[0],t.bounds[1]=r[1];const n=e.getRange(1);t.bounds[2]=n[0],t.bounds[3]=n[1];const o=e.getRange(2);t.bounds[4]=o[0],t.bounds[5]=o[1]}else if(2===e.getNumberOfComponents()){const r=e.getRange(0);t.bounds[0]=r[0],t.bounds[1]=r[1];const n=e.getRange(1);t.bounds[2]=n[0],t.bounds[3]=n[1],t.bounds[4]=0,t.bounds[5]=0}else $l(`getBounds called on an array with components of ${e.getNumberOfComponents()}`),yi(t.bounds);r=zt.getCurrentGlobalMTime()},e.setNumberOfComponents(t.numberOfComponents<2?3:t.numberOfComponents)}(e,t)}var Jl={newInstance:zt.newInstance(Yl,"vtkPoints"),extend:Yl};const Ql={bounds:[-1,-1,-1,-1,-1,-1],pointsIds:[]};function Zl(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Ql,r),zt.obj(e,t),t.points||(t.points=Jl.newInstance()),zt.get(e,t,["points","pointsIds"]),function(e,t){t.classHierarchy.push("vtkCell"),e.initialize=function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(r){t.pointsIds=r;let n=t.points.getData();n.length!==3*t.pointsIds.length&&(n=zt.newTypedArray(e.getDataType(),3*t.pointsIds.length));const o=e.getData();t.pointsIds.forEach((e,t)=>{let r=3*e,i=3*t;n[i]=o[r],n[++i]=o[++r],n[++i]=o[++r]}),t.points.setData(n)}else{t.points=e,t.pointsIds=new Array(e.getNumberOfPoints());for(let r=e.getNumberOfPoints()-1;r>=0;--r)t.pointsIds[r]=r}},e.getBounds=()=>t.points.getBounds(),e.getLength2=()=>{const t=Va.getLengths(e.getBounds());return t[0]*t[0]+t[1]*t[1]+t[2]*t[2]},e.getParametricDistance=e=>{let t,r=0;for(let n=0;n<3;n++)t=e[n]<0?-e[n]:e[n]>1?e[n]-1:0,t>r&&(r=t);return r},e.getNumberOfPoints=()=>t.points.getNumberOfPoints(),e.deepCopy=e=>{e.initialize(t.points,t.pointsIds)},e.getCellDimension=()=>{},e.intersectWithLine=(e,t,r,n,o,i,a)=>{},e.evaluatePosition=(e,t,r,n,o,i)=>{zt.vtkErrorMacro("vtkCell.evaluatePosition is not implemented.")}}(e,t)}var eu={newInstance:zt.newInstance(Zl,"vtkCell"),extend:Zl};const tu={array:null,maxId:0,extend:0};function ru(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,tu,r),zt.obj(e,t),function(e,t){t.classHierarchy.push("vtkCellLinks"),e.buildLinks=r=>{const n=r.getPoints().getNumberOfPoints(),o=r.getNumberOfCells(),i=new Uint32Array(n);if(r.isA("vtkPolyData")){for(let t=0;t{e.incrementLinkCount(t)})}e.allocateLinks(n),t.maxId=n-1;for(let t=0;t{e.insertCellReference(r,i[r]++,t)})}}else{for(let t=0;t{e.incrementLinkCount(t)});e.allocateLinks(n),t.maxId=n-1;for(let t=0;t{e.insertCellReference(r,i[r]++,t)})}},e.allocate=function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e3;t.array=Array(e).fill().map(()=>({ncells:0,cells:null})),t.extend=r,t.maxId=-1},e.initialize=()=>{t.array=null},e.getLink=e=>t.array[e],e.getNcells=e=>t.array[e].ncells,e.getCells=e=>t.array[e].cells,e.insertNextPoint=e=>{t.array.push({ncells:e,cells:Array(e)}),++t.maxId},e.insertNextCellReference=(e,r)=>{t.array[e].cells[t.array[e].ncells++]=r},e.deletePoint=e=>{t.array[e].ncells=0,t.array[e].cells=null},e.removeCellReference=(e,r)=>{t.array[r].cells=t.array[r].cells.filter(t=>t!==e),t.array[r].ncells=t.array[r].cells.length},e.addCellReference=(e,r)=>{t.array[r].cells[t.array[r].ncells++]=e},e.resizeCellList=(e,r)=>{t.array[e].cells.length=r},e.squeeze=()=>{!function(e,t){let r=t;for(t>=e.array.length&&(r+=e.array.length);r>e.array.length;)e.array.push({ncells:0,cells:null});e.array.length=r}(t,t.maxId+1)},e.reset=()=>{t.maxId=-1},e.deepCopy=e=>{t.array=[...e.array],t.extend=e.extend,t.maxId=e.maxId},e.incrementLinkCount=e=>{++t.array[e].ncells},e.allocateLinks=e=>{for(let r=0;r{t.array[e].cells[r]=n}}(e,t)}var nu={newInstance:zt.newInstance(ru,"vtkCellLinks"),extend:ru};const ou=0,iu=1,au=2,su=3,lu=4,uu=5,cu=6,du=7,pu=9,fu=21,hu=41,mu=42,gu=["vtkEmptyCell","vtkVertex","vtkPolyVertex","vtkLine","vtkPolyLine","vtkTriangle","vtkTriangleStrip","vtkPolygon","vtkPixel","vtkQuad","vtkTetra","vtkVoxel","vtkHexahedron","vtkWedge","vtkPyramid","vtkPentagonalPrism","vtkHexagonalPrism","UnknownClass","UnknownClass","UnknownClass","UnknownClass","vtkQuadraticEdge","vtkQuadraticTriangle","vtkQuadraticQuad","vtkQuadraticTetra","vtkQuadraticHexahedron","vtkQuadraticWedge","vtkQuadraticPyramid","vtkBiQuadraticQuad","vtkTriQuadraticHexahedron","vtkQuadraticLinearQuad","vtkQuadraticLinearWedge","vtkBiQuadraticQuadraticWedge","vtkBiQuadraticQuadraticHexahedron","vtkBiQuadraticTriangle","vtkCubicLine","vtkQuadraticPolygon","UnknownClass","UnknownClass","UnknownClass","UnknownClass","vtkConvexPointSet","UnknownClass","UnknownClass","UnknownClass","UnknownClass","UnknownClass","UnknownClass","UnknownClass","UnknownClass","UnknownClass","vtkParametricCurve","vtkParametricSurface","vtkParametricTriSurface","vtkParametricQuadSurface","vtkParametricTetraRegion","vtkParametricHexRegion","UnknownClass","UnknownClass","UnknownClass","vtkHigherOrderEdge","vtkHigherOrderTriangle","vtkHigherOrderQuad","vtkHigherOrderPolygon","vtkHigherOrderTetrahedron","vtkHigherOrderWedge","vtkHigherOrderPyramid","vtkHigherOrderHexahedron"],yu={getClassNameFromTypeId:function(e){return e2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,vu,r),zt.obj(e,t),zt.get(e,t,["size","maxId","extend"]),zt.getArray(e,t,["typeArray","locationArray"]),function(e,t){t.classHierarchy.push("vtkCellTypes"),e.allocate=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:512,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e3;t.size=e>0?e:1,t.extend=r>0?r:1,t.maxId=-1,t.typeArray=new Uint8Array(e),t.locationArray=new Uint32Array(e)},e.insertCell=(e,r,n)=>{t.typeArray[e]=r,t.locationArray[e]=n,e>t.maxId&&(t.maxId=e)},e.insertNextCell=(r,n)=>(e.insertCell(++t.maxId,r,n),t.maxId),e.setCellTypes=(e,r,n)=>{t.size=e,t.typeArray=r,t.locationArray=n,t.maxId=e-1},e.getCellLocation=e=>t.locationArray[e],e.deleteCell=e=>{t.typeArray[e]=ou},e.getNumberOfTypes=()=>t.maxId+1,e.isType=t=>{const r=e.getNumberOfTypes();for(let n=0;ne.insertNextCell(t,-1),e.getCellType=e=>t.typeArray[e],e.reset=()=>{t.maxId=-1},e.deepCopy=r=>{e.allocate(r.getSize(),r.getExtend()),t.typeArray.set(r.getTypeArray()),t.locationArray.set(r.getLocationArray()),t.maxId=r.getMaxId()}}(e,t)}var xu={newInstance:zt.newInstance(bu,"vtkCellTypes"),extend:bu,...yu};const _u={NO_INTERSECTION:0,YES_INTERSECTION:1,ON_LINE:2};var Su={IntersectionState:_u};const{IntersectionState:Cu}=Su;function Tu(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;const o={t:Number.MIN_VALUE,distance:0},i=[];let a;i[0]=r[0]-t[0],i[1]=r[1]-t[1],i[2]=r[2]-t[2];const s=i[0]*(e[0]-t[0])+i[1]*(e[1]-t[1])+i[2]*(e[2]-t[2]),l=Ro(i,i);let u=1e-5*s;return 0!==l&&(o.t=s/l),u<0&&(u=-u),-u1?a=r:(a=i,i[0]=t[0]+o.t*i[0],i[1]=t[1]+o.t*i[1],i[2]=t[2]+o.t*i[2]),n&&(n[0]=a[0],n[1]=a[1],n[2]=a[2]),o.distance=Vo(a,e),o}function wu(e,t,r,n,o,i){const a=[],s=[],l=[];o[0]=0,i[0]=0,Io(t,e,a),Io(n,r,s),Io(r,e,l);const u=[Ro(a,a),-Ro(a,s),-Ro(a,s),Ro(s,s)],c=[];if(c[0]=Ro(a,l),c[1]=-Ro(s,l),0===ai(u,c,2)){let a=Number.MAX_VALUE;const s=[e,t,r,n],l=[r,r,e,e],u=[n,n,t,t];let c;i[0],i[0],o[0],o[0],o[0],o[0],i[0],i[0];for(let e=0;e<4;e++)c=Tu(s[e],l[e],u[e]),c.distance=0&&o[0]<=1&&i[0]>=0&&i[0]<=1?Cu.YES_INTERSECTION:Cu.NO_INTERSECTION}const Au={distanceToLine:Tu,intersection:wu},Eu={orientations:null};function Du(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Eu,r),eu.extend(e,t,r),zt.setGet(e,t,["orientations"]),function(e,t){t.classHierarchy.push("vtkLine"),e.getCellDimension=()=>1,e.intersectWithLine=(e,r,n,o,i)=>{const a={intersect:0,t:Number.MAX_VALUE,subId:0,betweenPoints:null};i[1]=0,i[2]=0;const s=[],l=[],u=[];t.points.getPoint(0,l),t.points.getPoint(1,u);const c=[],d=[],p=wu(e,r,l,u,c,d);var f;if(a.t=c[0],a.betweenPoints=(f=a.t)>=0&&f<=1,i[0]=d[0],p===Cu.YES_INTERSECTION){for(let t=0;t<3;t++)o[t]=l[t]+i[0]*(u[t]-l[t]),s[t]=e[t]+a.t*(r[t]-e[t]);if(Vo(o,s)<=n*n)return a.intersect=1,a}else{let t;if(a.t<0)return t=Tu(e,l,u,o),t.distance<=n*n?(a.t=0,a.intersect=1,a.betweenPoints=!0,a):a;if(a.t>1)return t=Tu(r,l,u,o),t.distance<=n*n?(a.t=1,a.intersect=1,a.betweenPoints=!0,a):a;if(i[0]<0)return i[0]=0,t=Tu(l,e,r,o),a.t=t.t,t.distance<=n*n?(a.intersect=1,a):a;if(i[0]>1)return i[0]=1,t=Tu(u,e,r,o),a.t=t.t,t.distance<=n*n?(a.intersect=1,a):a}return a},e.evaluateLocation=(e,r,n)=>{const o=[],i=[];t.points.getPoint(0,o),t.points.getPoint(1,i);for(let t=0;t<3;t++)r[t]=o[t]+e[0]*(i[t]-o[t]);n[0]=1-e[0],n[1]=e[0]},e.evaluateOrientation=(e,r,n)=>!!t.orientations&&(Li(r,t.orientations[0],t.orientations[1],e[0]),n[0]=1-e[0],n[1]=e[0],!0)}(e,t)}var Pu={newInstance:zt.newInstance(Du,"vtkLine"),extend:Du,...Au,...Su};const Iu={};function Ou(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Iu,r),Gs.extend(e,t,r),zt.setGet(e,t,["points"]),function(e,t){t.classHierarchy.push("vtkPointSet"),t.points?t.points=Ge(t.points):t.points=Jl.newInstance(),e.getNumberOfPoints=()=>t.points.getNumberOfPoints(),e.getBounds=()=>t.points.getBounds(),e.computeBounds=()=>{e.getBounds()};const r=e.shallowCopy;e.shallowCopy=function(e){r(e,arguments.length>1&&void 0!==arguments[1]&&arguments[1]),t.points=Jl.newInstance(),t.points.shallowCopy(e.getPoints())};const n=e.getMTime;e.getMTime=()=>{const e=n();return Math.max(e,t.points?.getMTime()??e)};const o=e.initialize;e.initialize=()=>(t.points?.initialize(),o())}(e,t)}var Nu={newInstance:zt.newInstance(Ou,"vtkPointSet"),extend:Ou};const Mu={orientations:null,distanceFunction:function(e,t){var r=t[0]-e[0],n=t[1]-e[1],o=t[2]-e[2];return Math.hypot(r,n,o)}};function Ru(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Mu,r),eu.extend(e,t,r),zt.setGet(e,t,["orientations","distanceFunction"]),t.distancesTime={},zt.obj(t.distancesTime,{mtime:0}),function(e,t){t.classHierarchy.push("vtkPolyLine");const r=Pu.newInstance();r.getPoints().setNumberOfPoints(2),e.getCellDimension=()=>1,e.intersectWithLine=(n,o,i,a,s,l,u)=>{const c={intersect:0,t:Number.MAX_VALUE,subId:0,betweenPoints:null},d=e.getNumberOfPoints()-1;let p=Number.MAX_VALUE;for(let e=0;e=n&&f.t<=o){c.intersect=1;const t=r.getParametricDistance(d);if(t(r.getPoints().getData().set(t.points.getData().subarray(3*e,3*(e+2))),r.evaluateLocation(n,o,i)),e.evaluateOrientation=(e,n,o,i)=>(t.orientations?r.setOrientations([t.orientations[e],t.orientations[e+1]]):r.setOrientations(null),r.evaluateOrientation(n,o,i)),e.getDistancesToFirstPoint=()=>{const r=t.distancesTime.getMTime();if(r0){const e=new Array(3),n=new Array(3);let o=0;t.distances[0]=o,t.points.getPoint(0,e);for(let i=1;i{const r=e.getDistancesToFirstPoint();if(r.length<2)return-1;let n=0,o=r.length-1;if(tr[o]||0===r[o])return-1;for(;o-n>1;){const e=Math.floor((n+o)/2);r[e]<=t?n=e:o=e}return n}}(e,t)}var Fu={newInstance:zt.newInstance(Ru,"vtkPolyLine"),extend:Ru};const Bu={elements:[]};function Lu(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Bu,r),zt.obj(e,t),function(e,t){t.classHierarchy.push("vtkPriorityQueue"),e.push=(e,r)=>{const n=t.elements.findIndex(t=>t.priority>e);t.elements.splice(n,0,{priority:e,element:r})},e.pop=()=>t.elements.length>0?t.elements.shift().element:null,e.deleteById=e=>{t.elements=t.elements.filter(t=>{let{element:r}=t;return r.id!==e})},e.length=()=>t.elements.length}(e,t)}var ku={newInstance:zt.newInstance(Lu,"vtkPriorityQueue"),extend:Lu};const Uu=1e-6,Vu=1.1920929e-7,Gu={FAILURE:-1,OUTSIDE:0,INSIDE:1,INTERSECTION:2,ON_LINE:3};function zu(e,t,r,n,o){return(n[e]-r[e])*(o[t]-r[t])-(o[e]-r[e])*(n[t]-r[t])}const ju={PolygonWithPointIntersectionState:Gu,pointInPolygon:function(e,t,r,n){if(e[0]r[1]||e[1]r[3]||e[2]r[5])return Gu.OUTSIDE;if(Lo(n)<=Vu)return Gu.FAILURE;let o=1e-8*((r[1]-r[0])*(r[1]-r[0])+(r[3]-r[2])*(r[3]-r[2])+(r[5]-r[4])*(r[5]-r[4]));o*=o,o=0===o?Vu:o;const i=[],a=[];for(let r=0;r0&&s<1)return Gu.INSIDE}let s,l;Math.abs(n[0])>Math.abs(n[1])?Math.abs(n[0])>Math.abs(n[2])?(s=1,l=2):(s=0,l=1):Math.abs(n[1])>Math.abs(n[2])?(s=0,l=2):(s=0,l=1);let u=0;for(let r=0;re[l]&&zu(s,l,i,a,e)>0&&++u:a[l]<=e[l]&&zu(s,l,i,a,e)<0&&--u;return 0===u?Gu.OUTSIDE:Gu.INSIDE},getBounds:function(e,t,r){const n=e.length,o=[];t.getPoint(e[0],o),r[0]=o[0],r[1]=o[0],r[2]=o[1],r[3]=o[1],r[4]=o[2],r[5]=o[2];for(let i=1;i2&&void 0!==arguments[2]?arguments[2]:[0,0,0];r[0]=0,r[1]=0,r[2]=0;const n=e.length,o=[];for(let i=0;iUu?1:a<-1e-6?-1:0,l=s<0?1:0;for(let e=n.next.next;e.id!==r.id;e=e.next){const t=e.previous;a=ea.evaluate(i,r.point,e.point);const o=a>Uu?1:a<-1e-6?-1:0;if(o!==s){if(l||(l=o<=0?1:0),Pu.intersection(r.point,n.point,e.point,t.point,[0],[0])===_u.YES_INTERSECTION)return!1;s=o}}return 1===l}function o(e,n){t.pointCount-=1;const o=e.previous,i=e.next;t.tris=t.tris.concat(e.point),t.tris=t.tris.concat(i.point),t.tris=t.tris.concat(o.point),o.next=i,i.previous=o,n.deleteById(o.id),n.deleteById(i.id);const a=r(o);a>0&&n.push(a,o);const s=r(i);s>0&&n.push(s,i),e.id===t.firstPoint.id&&(t.firstPoint=i)}t.classHierarchy.push("vtkPolygon"),e.triangulate=()=>t.firstPoint?function(){!function(){const e=[0,0,0],r=[0,0,0];t.normal=[0,0,0];const n=[...t.firstPoint.point];let o=t.firstPoint;for(let i=0;i0&&e.push(t,i),i=i.next}for(;t.pointCount>2&&e.length()>0;)if(t.pointCount===e.length())o(e.pop(),e);else{const t=e.pop();n(t)&&o(t,e)}return t.pointCount<=2}():null,e.setPoints=e=>{t.pointCount=e.length,t.firstPoint={id:0,point:e[0],next:null,previous:null};let r=t.firstPoint;for(let n=1;nt.tris}const Hu={firstPoint:null,pointCount:0,tris:[]};function Ku(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Hu,r),zt.obj(e,t),Wu(e,t)}var Xu={newInstance:zt.newInstance(Ku,"vtkPolygon"),extend:Ku,...ju};function $u(e,t,r,n){const o=r[0]-t[0],i=r[1]-t[1],a=r[2]-t[2],s=e[0]-t[0],l=e[1]-t[1],u=e[2]-t[2];n[0]=i*u-a*l,n[1]=a*s-o*u,n[2]=o*l-i*s}function qu(e,t,r,n){$u(e,t,r,n);const o=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]);0!==o&&(n[0]/=o,n[1]/=o,n[2]/=o)}function Yu(e){e[0]=-1,e[1]=1,e[2]=0,e[3]=-1,e[4]=0,e[5]=1}const Ju={computeNormalDirection:$u,computeNormal:qu,interpolationDerivs:Yu,intersectWithTriangle:function(e,t,r,n,o,i){let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:1e-6,s=!1;const l=[],u=[],c=[],d=[],p=[];qu(e,t,r,d),qu(n,o,i,p);const f=-Ro(d,e),h=-Ro(p,n),m=[Ro(p,e)+h,Ro(p,t)+h,Ro(p,r)+h];if(m[0]*m[1]>a&&m[0]*m[2]>a)return{intersect:!1,coplanar:s,pt1:l,pt2:u,surfaceId:c};const g=[Ro(d,n)+f,Ro(d,o)+f,Ro(d,i)+f];if(g[0]*g[1]>a&&g[0]*g[2]>a)return{intersect:!1,coplanar:s,pt1:l,pt2:u,surfaceId:c};if(Math.abs(d[0]-p[0])<1e-9&&Math.abs(d[1]-p[1])<1e-9&&Math.abs(d[2]-p[2])<1e-9&&Math.abs(f-h)<1e-9)return s=!0,{intersect:!1,coplanar:s,pt1:l,pt2:u,surfaceId:c};const y=[e,t,r],v=[n,o,i],b=Ro(d,p),x=(f-h*b)/(b*b-1),_=(h-f*b)/(b*b-1),S=[x*d[0]+_*p[0],x*d[1]+_*p[1],x*d[2]+_*p[2]],C=Fo(d,p,[]);Lo(C);let T=0,w=0;const A=[],E=[];let D,P,I=50,O=50;for(let t=0;t<3;t++){const r=t,o=(t+1)%3,i=ea.intersectWithLine(y[r],y[o],n,p);i.intersection&&i.t>0-a&&i.t<1+a&&(i.t<1+a&&i.t>1-a&&(I=T),A[T++]=Ro(i.x,C)-Ro(S,C));const s=ea.intersectWithLine(v[r],v[o],e,d);s.intersection&&s.t>0-a&&s.t<1+a&&(s.t<1+a&&s.t>1-a&&(O=w),E[w++]=Ro(s.x,C)-Ro(S,C))}if(T>2){T--;const e=A[2];A[2]=A[I],A[I]=e}if(w>2){w--;const e=E[2];E[2]=E[O],E[O]=e}if(2!==T||2!==w)return{intersect:!1,coplanar:s,pt1:l,pt2:u,surfaceId:c};if(Number.isNaN(A[0])||Number.isNaN(A[1])||Number.isNaN(E[0])||Number.isNaN(E[1]))return{intersect:!1,coplanar:s,pt1:l,pt2:u,surfaceId:c};if(A[0]>A[1]){const e=A[1];A[1]=A[0],A[0]=e}if(E[0]>E[1]){const e=E[1];E[1]=E[0],E[0]=e}return A[1]2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Qu,r),eu.extend(e,t,r),function(e,t){t.classHierarchy.push("vtkTriangle"),e.getCellDimension=()=>2,e.intersectWithLine=(r,n,o,i,a)=>{const s={subId:0,t:Number.MAX_VALUE,intersect:0,betweenPoints:!1};a[2]=0;const l=[],u=o*o,c=[],d=[],p=[];t.points.getPoint(0,c),t.points.getPoint(1,d),t.points.getPoint(2,p);const f=[],h=[];if(qu(c,d,p,f),0!==f[0]||0!==f[1]||0!==f[2]){const t=ea.intersectWithLine(r,n,c,f);if(s.betweenPoints=t.betweenPoints,s.t=t.t,i[0]=t.x[0],i[1]=t.x[1],i[2]=t.x[2],!t.intersection)return a[0]=0,a[1]=0,s.intersect=0,s;const o=e.evaluatePosition(i,l,a,h);if(o.evaluation>=0)return o.dist2<=u?(s.intersect=1,s):(s.intersect=o.evaluation,s)}const m=Vo(c,d),g=Vo(d,p),y=Vo(p,c);t.line||(t.line=Pu.newInstance()),m>g&&m>y?(t.line.getPoints().setPoint(0,c),t.line.getPoints().setPoint(1,d)):g>y&&g>m?(t.line.getPoints().setPoint(0,d),t.line.getPoints().setPoint(1,p)):(t.line.getPoints().setPoint(0,p),t.line.getPoints().setPoint(1,c));const v=t.line.intersectWithLine(r,n,o,i,a);if(s.betweenPoints=v.betweenPoints,s.t=v.t,v.intersect){const e=[],t=[],r=[];for(let n=0;n<3;n++)e[n]=c[n]-p[n],t[n]=d[n]-p[n],r[n]=i[n]-p[n];return a[0]=Ro(r,e)/y,a[1]=Ro(r,t)/g,s.intersect=1,s}return a[0]=0,a[1]=0,s.intersect=0,s},e.evaluatePosition=(e,r,n,o)=>{const i={subId:0,dist2:0,evaluation:-1};let a,s;const l=[],u=[],c=[],d=[];let p;const f=[],h=[],m=[];let g=0,y=0;const v=[];let b,x,_,S=[];const C=[],T=[],w=[];i.subId=0,n[2]=0,t.points.getPoint(1,l),t.points.getPoint(2,u),t.points.getPoint(0,c),$u(l,u,c,d),ea.generalizedProjectPoint(e,l,d,w);let A=0;for(a=0;a<3;a++)p=d[a]<0?-d[a]:d[a],p>A&&(A=p,y=a);for(s=0,a=0;a<3;a++)a!==y&&(v[s++]=a);for(a=0;a<2;a++)f[a]=w[v[a]]-c[v[a]],h[a]=l[v[a]]-c[v[a]],m[a]=u[v[a]]-c[v[a]];if(g=jo(h,m),0===g)return n[0]=0,n[1]=0,i.evaluation=-1,i;if(n[0]=jo(f,m)/g,n[1]=jo(h,f)/g,o[0]=1-(n[0]+n[1]),o[1]=n[0],o[2]=n[1],o[0]>=0&&o[0]<=1&&o[1]>=0&&o[1]<=1&&o[2]>=0&&o[2]<=1)r&&(i.dist2=Vo(w,e),r[0]=w[0],r[1]=w[1],r[2]=w[2]),i.evaluation=1;else{let t;if(r)if(o[1]<0&&o[2]<0)for(b=Vo(e,c),x=Pu.distanceToLine(e,l,c,t,C),_=Pu.distanceToLine(e,c,u,t,T),b{const o=[],i=[],a=[];t.points.getPoint(0,o),t.points.getPoint(1,i),t.points.getPoint(2,a);const s=1-e[0]-e[1];for(let t=0;t<3;t++)r[t]=o[t]*s+i[t]*e[0]+a[t]*e[1];n[0]=s,n[1]=e[0],n[2]=e[1]},e.getParametricDistance=e=>{let t,r=0;const n=[];n[0]=e[0],n[1]=e[1],n[2]=1-e[0]-e[1];for(let e=0;e<3;e++)t=n[e]<0?-n[e]:n[e]>1?n[e]-1:0,t>r&&(r=t);return r},e.derivatives=(e,r,n,o,i)=>{const a=t.points.getPoint(0),s=t.points.getPoint(1),l=t.points.getPoint(2),u=[],c=[],d=[],p=[];qu(a,s,l,u),Io(s,a,c),Io(l,a,p),Fo(u,c,d);const f=Lo(c);if(f<=0||Lo(d)<=0){for(let e=0;e{const o=r[0]-r[1],i=.5*(1-r[0])-r[1],a=2*r[0]+r[1]-1;return o>=0&&i>=0?(n[0]=t.pointsIds[0],n[1]=t.pointsIds[1]):i<0&&a>=0?(n[0]=t.pointsIds[1],n[1]=t.pointsIds[2]):(n[0]=t.pointsIds[2],n[1]=t.pointsIds[0]),!(r[0]<0||r[1]<0||r[0]>1||r[1]>1||1-r[0]-r[1]<0)}}(e,t)}var ec={newInstance:zt.newInstance(Zu,"vtkTriangle"),extend:Zu,...Ju};const tc={};function rc(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,tc,r),eu.extend(e,t,r),function(e,t){t.classHierarchy.push("vtkQuad"),e.getCellDimension=()=>2,e.getCellType=()=>pu,e.getNumberOfEdges=()=>4,e.getNumberOfFaces=()=>0,e.intersectWithLine=(e,r,n,o,i)=>{let a,s={subId:0,t:Number.MAX_VALUE,intersect:0,betweenPoints:!1};const l=t.points.getPoint(0,[]),u=t.points.getPoint(1,[]),c=t.points.getPoint(2,[]),d=t.points.getPoint(3,[]),p=Vo(l,c),f=Vo(u,d);if(p===f){let e,r=0,n=0;for(let o=0;o<4;o++)e=t.pointsIds[o],e>r&&(r=e,n=o);a=0===n||2===n?0:1}else a=p{const r=1-e[0],n=1-e[1];t[0]=r*n,t[1]=e[0]*n,t[2]=e[0]*e[1],t[3]=r*e[1]},e.evaluateLocation=(r,n,o)=>{const i=[];e.interpolationFunctions(r,o),n[0]=0,n[1]=0,n[2]=0;for(let e=0;e<4;e++){t.points.getPoint(e,i);for(let t=0;t<3;t++)n[t]+=i[t]*o[e]}}}(e,t)}var nc={newInstance:zt.newInstance(rc,"vtkQuad"),extend:rc};const{vtkErrorMacro:oc}=zt;function ic(e){return()=>oc(`vtkTriangleStrip.${e} - NOT IMPLEMENTED`)}const ac={decomposeStrip:function(e,t){if(!Array.isArray(e)||e.length<3)return void oc("decomposeStrip - Invalid points array");let r=e[0],n=e[1];for(let o=0;o2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,sc,r),eu.extend(e,t,r),t.line||(t.line=Pu.newInstance()),t.triangle||(t.triangle=ec.newInstance()),function(e,t){t.classHierarchy.push("vtkTriangleStrip");const r=e.initialize;e.initialize=(e,n)=>{t.triangle.initialize(e,n),r(e,n)},e.getCellType=()=>cu,e.getCellDimension=()=>2,e.getNumberOfEdges=()=>t.pointsIds.length,e.getNumberOfFaces=()=>0,e.evaluatePosition=(e,r,n,o,i)=>{const a=[0,0,0];let s=Number.MAX_VALUE,l=0;const u=[],c=[],d=[];n[2]=0,c[0]=0,c[1]=0,c[2]=0;const p=t.triangle.getPoints();p.setNumberOfPoints(3);const f=t.triangle.getPointsIds().length;for(let e=0;e=0&&(g{const i=[[0,1,2],[1,0,2]],a=e%2,s=t.pointsIds.length;for(let e=0;e{const o=[[0,1,2],[1,0,2]],i=e%2,a=t.triangle.getPointsIds();return a[0]=t.pointsIds[o[i][0]],a[1]=t.pointsIds[o[i][1]],a[2]=t.pointsIds[o[i][2]],t.triangle.cellBoundary(0,r,n)},e.getEdge=e=>{let r,n;const o=t.pointsIds.length;return 0===e?(r=0,n=1):e===o-1?(r=e-1,n=e):(r=e-1,n=e+1),t.line.getPointsIds()[0]=t.pointsIds[r],t.line.getPointsIds()[1]=t.pointsIds[n],t.line.getPoints().setPoint(0,t.points.getPoint(r)),t.line.getPoints().setPoint(1,t.points.getPoint(n)),t.line},e.intersectWithLine=(e,r,n,o,i)=>{const a=t.pointsIds.length-2,s=t.triangle.getPoints();s.setNumberOfPoints(3);for(let l=0;l{const e=t.points.getNumberOfPoints()-2;t.tris=new Array(3*e);const r=[[0,1,2],[1,0,2]];for(let n=0;nt.tris,e.derivatives=(e,r,n,o,i)=>{const a=[];t.points.getPoint(e,a);const s=[];t.points.getPoint(e+1,s);const l=[];t.points.getPoint(e+2,l);const u=t.triangle.getPoints();u.setPoint(0,...a),u.setPoint(1,...s),u.setPoint(2,...l),t.triangle.derivatives(0,r,n,o,i)},e.getParametricCenter=e=>(e[0]=.333333,e[1]=.333333,e[2]=0,Math.floor((t.pointsIds.length-2)/2)),e.contour=(e,t,r,n,o,i,a,s,l,u,c)=>ic("contour")(),e.clip=(e,t,r,n,o,i,a,s,l,u)=>ic("clip")()}(e,t)}var uc={newInstance:zt.newInstance(lc,"vtkTriangleStrip"),extend:lc,...ac};const cc=["verts","lines","polys","strips"],{vtkWarningMacro:dc}=zt,pc={[su]:Pu,[pu]:nc,[lu]:Pu,[uu]:ec,[cu]:uc,[lu]:Fu,[du]:Xu},fc={};function hc(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,fc,r),Nu.extend(e,t,r),zt.get(e,t,["cells","links"]),zt.setGet(e,t,["verts","lines","polys","strips"]),function(e,t){function r(e){return e.replace(/(?:^\w|[A-Z]|\b\w)/g,e=>e.toUpperCase()).replace(/\s+/g,"")}function n(){t.cells=void 0,t.links=void 0}t.classHierarchy.push("vtkPolyData"),cc.forEach(o=>{e[`getNumberOf${r(o)}`]=()=>t[o].getNumberOfCells(),t[o]?t[o]=Ge(t[o]):t[o]=Xl.newInstance(),t[`_on${r(o)}Changed`]=n}),e.getNumberOfCells=()=>cc.reduce((e,r)=>e+t[r].getNumberOfCells(),0);const o=e.shallowCopy;e.shallowCopy=function(e){o(e,arguments.length>1&&void 0!==arguments[1]&&arguments[1]),cc.forEach(r=>{t[r]=Xl.newInstance(),t[r].shallowCopy(e.getReferenceByName(r))})};const i=e.getMTime;e.getMTime=()=>cc.reduce((e,r)=>Math.max(e,t[r]?.getMTime()??e),i());const a=e.initialize;e.initialize=()=>(cc.forEach(e=>t[e]?.initialize()),n(),a()),e.buildCells=()=>{const r=e.getNumberOfVerts(),n=e.getNumberOfLines(),o=e.getNumberOfPolys(),i=e.getNumberOfStrips(),a=r+n+o+i,s=new Uint8Array(a);let l=s;const u=new Uint32Array(a);let c=u;if(r){let e=0;t.verts.getCellSizes().forEach((t,r)=>{c[r]=e,l[r]=t>1?au:iu,e+=t+1}),c=c.subarray(r),l=l.subarray(r)}if(n){let e=0;t.lines.getCellSizes().forEach((t,r)=>{c[r]=e,l[r]=t>2?lu:su,1===t&&dc("Building VTK_LINE ",r," with only one point, but VTK_LINE needs at least two points. Check the input."),e+=t+1}),c=c.subarray(n),l=l.subarray(n)}if(o){let e=0;t.polys.getCellSizes().forEach((t,r)=>{switch(c[r]=e,t){case 3:l[r]=uu;break;case 4:l[r]=pu;break;default:l[r]=du}t<3&&dc("Building VTK_TRIANGLE ",r," with less than three points, but VTK_TRIANGLE needs at least three points. Check the input."),e+=t+1}),c+=c.subarray(o),l+=l.subarray(o)}if(i){let e=0;l.fill(cu,0,i),t.strips.getCellSizes().forEach((t,r)=>{c[r]=e,e+=t+1})}t.cells=xu.newInstance(),t.cells.setCellTypes(a,s,u)},e.buildLinks=function(){let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;null==t.cells&&e.buildCells(),t.links=nu.newInstance(),r>0?t.links.allocate(r):t.links.allocate(e.getPoints().getNumberOfPoints()),t.links.buildLinks(e)},e.getCellType=e=>t.cells.getCellType(e),e.getCellPoints=r=>{const n=e.getCellType(r);let o=null;switch(n){case iu:case au:o=t.verts;break;case su:case lu:o=t.lines;break;case uu:case pu:case du:o=t.polys;break;case cu:o=t.strips;break;default:return o=null,{type:0,cellPointIds:null}}const i=t.cells.getCellLocation(r);return{cellType:n,cellPointIds:o.getCell(i)}},e.getPointCells=e=>t.links.getCells(e),e.getCellEdgeNeighbors=(e,r,n)=>{const o=t.links.getLink(r),i=t.links.getLink(n);return o.cells.filter(t=>t!==e&&-1!==i.cells.indexOf(t))},e.getCell=function(t){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;const n=e.getCellPoints(t),o=r||pc[n.cellType].newInstance();return o.initialize(e.getPoints(),n.cellPointIds),o},e.getMaxCellSize=()=>cc.reduce((e,r)=>Math.max(e,t[r]?.getMaxCellSize?.()??0),0)}(e,t)}var mc={newInstance:zt.newInstance(hc,"vtkPolyData"),extend:hc};const gc={image:null,canvas:null,jsImageData:null,imageBitmap:null,imageLoaded:!1,repeat:!1,interpolate:!1,edgeClamp:!1,mipLevel:0,resizable:!1};function yc(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,gc,r),zt.obj(e,t),zt.algo(e,t,6,0),zt.get(e,t,["canvas","image","jsImageData","imageBitmap","imageLoaded","resizable"]),zt.setGet(e,t,["repeat","edgeClamp","interpolate","mipLevel"]),function(e,t){t.classHierarchy.push("vtkTexture"),e.imageLoaded=()=>{t.image.removeEventListener("load",e.imageLoaded),t.imageLoaded=!0,e.modified()},e.setJsImageData=r=>{t.jsImageData!==r&&(null!==r&&(e.setInputData(null),e.setInputConnection(null),t.image=null,t.canvas=null,t.imageBitmap=null),t.jsImageData=r,t.imageLoaded=!0,e.modified())},e.setImageBitmap=r=>{t.imageBitmap!==r&&(null!==r&&(e.setInputData(null),e.setInputConnection(null),t.image=null,t.canvas=null,t.jsImageData=null),t.imageBitmap=r,t.imageLoaded=!0,e.modified())},e.setCanvas=r=>{t.canvas!==r&&(null!==r&&(e.setInputData(null),e.setInputConnection(null),t.image=null,t.imageBitmap=null,t.jsImageData=null),t.canvas=r,e.modified())},e.setImage=r=>{t.image!==r&&(null!==r&&(e.setInputData(null),e.setInputConnection(null),t.canvas=null,t.jsImageData=null,t.imageBitmap=null),t.image=r,t.imageLoaded=!1,r.complete?e.imageLoaded():r.addEventListener("load",e.imageLoaded),e.modified())},e.getDimensionality=()=>{let r=0,n=0,o=1;if(e.getInputData()){const t=e.getInputData();r=t.getDimensions()[0],n=t.getDimensions()[1],o=t.getDimensions()[2]}return t.jsImageData&&(r=t.jsImageData.width,n=t.jsImageData.height),t.canvas&&(r=t.canvas.width,n=t.canvas.height),t.image&&(r=t.image.width,n=t.image.height),t.imageBitmap&&(r=t.imageBitmap.width,n=t.imageBitmap.height),(r>1)+(n>1)+(o>1)},e.getInputAsJsImageData=()=>{if(!t.imageLoaded||e.getInputData())return null;if(t.jsImageData)return t.jsImageData;if(t.imageBitmap)return t.imageBitmap;if(t.canvas)return t.canvas.getContext("2d").getImageData(0,0,t.canvas.width,t.canvas.height);if(t.image){const e=t.image.width,r=t.image.height,n=new OffscreenCanvas(e,r).getContext("2d");return n.translate(0,r),n.scale(1,-1),n.drawImage(t.image,0,0,e,r),n.getImageData(0,0,e,r)}return null}}(e,t)}var vc={newInstance:zt.newInstance(yc,"vtkTexture"),extend:yc,generateMipmaps:(e,t,r)=>{const n=e.createShaderModule({code:"\n @group(0) @binding(0) var inputTexture: texture_2d;\n @group(0) @binding(1) var outputTexture: texture_storage_2d;\n\n @compute @workgroup_size(8, 8)\n fn main(@builtin(global_invocation_id) global_id: vec3) {\n let texelCoord = vec2(global_id.xy);\n let outputSize = textureDimensions(outputTexture);\n\n if (texelCoord.x >= i32(outputSize.x) || texelCoord.y >= i32(outputSize.y)) {\n return;\n }\n\n let inputSize = textureDimensions(inputTexture);\n let scale = vec2(inputSize) / vec2(outputSize);\n\n // Compute the floating-point source coordinate\n let srcCoord = (vec2(texelCoord) + 0.5) * scale - 0.5;\n\n // Get integer coordinates for the four surrounding texels\n let x0 = i32(floor(srcCoord.x));\n let x1 = min(x0 + 1, i32(inputSize.x) - 1);\n let y0 = i32(floor(srcCoord.y));\n let y1 = min(y0 + 1, i32(inputSize.y) - 1);\n\n // Compute the weights\n let wx = srcCoord.x - f32(x0);\n let wy = srcCoord.y - f32(y0);\n\n // Fetch the four texels\n let c00 = textureLoad(inputTexture, vec2(x0, y0), 0);\n let c10 = textureLoad(inputTexture, vec2(x1, y0), 0);\n let c01 = textureLoad(inputTexture, vec2(x0, y1), 0);\n let c11 = textureLoad(inputTexture, vec2(x1, y1), 0);\n\n // Bilinear interpolation\n let color = mix(\n mix(c00, c10, wx),\n mix(c01, c11, wx),\n wy\n );\n\n textureStore(outputTexture, texelCoord, color);\n }\n "}),o=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.COMPUTE,storageTexture:{format:"rgba8unorm",access:"write-only"}},{binding:2,visibility:GPUShaderStage.COMPUTE,sampler:{type:"filtering"}}]}),i=e.createPipelineLayout({bindGroupLayouts:[o]}),a=e.createComputePipeline({label:"ComputeMipmapPipeline",layout:i,compute:{module:n,entryPoint:"main"}}),s=e.createSampler({magFilter:"linear",minFilter:"linear"});for(let n=1;n>n),d=Math.max(1,t.height>>n),p=Math.ceil(c/8),f=Math.ceil(d/8);u.dispatchWorkgroups(p,f),u.end(),e.queue.submit([l.finish()])}}};const bc=[[-1,0,0],[1,0,0],[0,-1,0],[0,1,0],[0,0,-1],[0,0,1]],xc=[[8,7,11,3],[9,1,10,5],[4,9,0,8],[2,11,6,10],[0,3,2,1],[4,5,6,7]],_c=[[0,1],[1,3],[2,3],[0,2],[4,5],[5,7],[6,7],[4,6],[0,4],[1,5],[3,7],[2,6]],Sc=[0,1,0,1,0,1,0,1,2,2,2,2],Cc=[[1,2],[1,2],[0,2],[0,2],[0,1],[0,1]],Tc=new Float64Array(3),wc=new Float64Array(3),Ac=new Float64Array(3),Ec=new Float64Array(3),Dc=new Float64Array(3),Pc=new Float64Array(3),Ic=new Float64Array(16);function Oc(e,t){e.strokeStyle=t.strokeColor,e.lineWidth=t.strokeSize,e.fillStyle=t.fontColor,e.font=`${t.fontStyle} ${t.fontSize}px ${t.fontFamily}`}function Nc(e){const t=[],r=[];for(let n=0;n<3;n++){const o=no().domain([e[2*n],e[2*n+1]]);t[n]=o.ticks(5);const i=o.tickFormat(5);r[n]=t[n].map(i)}return{ticks:t,tickStrings:r}}const Mc=zt.newInstance(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{renderable:null};Object.assign(t,{},r),zt.obj(e,t),t.tmPolyData=mc.newInstance(),t.tmMapper=Gl.newInstance(),t.tmMapper.setInputData(t.tmPolyData),t.tmActor=ss.newInstance({parentProp:e}),t.tmActor.setMapper(t.tmMapper),zt.setGet(e,t,["renderable"]),zt.get(e,t,["lastSize","lastAspectRatio","axisTextStyle","tickTextStyle","tmActor","ticks"]),t.forceUpdate=!1,t.lastRedrawTime={},zt.obj(t.lastRedrawTime,{mtime:0}),t.lastRebuildTime={},zt.obj(t.lastRebuildTime,{mtime:0}),t.lastSize=[-1,-1],t.lastTickBounds=[],function(e,t){t.classHierarchy.push("vtkCubeAxesActorHelper"),e.setRenderable=r=>{t.renderable!==r&&(t.renderable=r,t.tmActor.addTexture(t.renderable.getTmTexture()),t.tmActor.setProperty(r.getProperty()),t.tmActor.setParentProp(r),e.modified())},e.createPolyDataForOneLabel=(e,r,n,o,i,a,s)=>{const l=t.renderable.get_tmAtlas().get(e);if(!l)return;const u=t.renderable.getTextPolyData().getPoints().getData(),c=t.lastSize;Tc[0]=u[3*r],Tc[1]=u[3*r+1],Tc[2]=u[3*r+2],Sr(Ac,Tc,n),Ac[0]+=.1,Sr(wc,Ac,o),yr(Dc,wc,Tc),Ac[0]-=.1,Ac[1]+=.1,Sr(wc,Ac,o),yr(Pc,wc,Tc);for(let e=0;e<3;e++)Dc[e]/=.05*c[0],Pc[e]/=.05*c[1];let d=s.ptIdx,p=s.cellIdx;Tc[0]=u[3*r],Tc[1]=u[3*r+1],Tc[2]=u[3*r+2],i[0]<-.5?vr(Ac,Dc,i[0]*a-l.width):i[0]>.5?vr(Ac,Dc,i[0]*a):vr(Ac,Dc,i[0]*a-l.width/2),gr(Tc,Tc,Ac),vr(Ac,Pc,i[1]*a-l.height/2),gr(Tc,Tc,Ac),s.points[3*d]=Tc[0],s.points[3*d+1]=Tc[1],s.points[3*d+2]=Tc[2],s.tcoords[2*d]=l.tcoords[0],s.tcoords[2*d+1]=l.tcoords[1],d++,vr(Ac,Dc,l.width),gr(Tc,Tc,Ac),s.points[3*d]=Tc[0],s.points[3*d+1]=Tc[1],s.points[3*d+2]=Tc[2],s.tcoords[2*d]=l.tcoords[2],s.tcoords[2*d+1]=l.tcoords[3],d++,vr(Ac,Pc,l.height),gr(Tc,Tc,Ac),s.points[3*d]=Tc[0],s.points[3*d+1]=Tc[1],s.points[3*d+2]=Tc[2],s.tcoords[2*d]=l.tcoords[4],s.tcoords[2*d+1]=l.tcoords[5],d++,vr(Ac,Dc,l.width),yr(Tc,Tc,Ac),s.points[3*d]=Tc[0],s.points[3*d+1]=Tc[1],s.points[3*d+2]=Tc[2],s.tcoords[2*d]=l.tcoords[6],s.tcoords[2*d+1]=l.tcoords[7],d++,s.polys[4*p]=3,s.polys[4*p+1]=d-4,s.polys[4*p+2]=d-3,s.polys[4*p+3]=d-2,p++,s.polys[4*p]=3,s.polys[4*p+1]=d-4,s.polys[4*p+2]=d-2,s.polys[4*p+3]=d-1,s.ptIdx+=4,s.cellIdx+=2},e.updateTexturePolyData=()=>{const r=t.camera.getCompositeProjectionMatrix(t.lastAspectRatio,-1,1);m(r,r);const n=t.renderable.getTextValues().length,o=4*n,i=2*n,a=new Float64Array(3*o),s=new Uint16Array(4*i),l=new Float32Array(2*o);g(Ic,r);const u={ptIdx:0,cellIdx:0,polys:s,points:a,tcoords:l};let c=0,d=0,p=0;const f=t.renderable.getTextPolyData().getPoints().getData(),h=t.renderable.getTextValues();for(;c{t.lastSize[0]===r[0]&&t.lastSize[1]===r[1]||(t.lastSize[0]=r[0],t.lastSize[1]=r[1],t.lastAspectRatio=r[0]/r[1],t.forceUpdate=!0),t.camera=n,e.updateTexturePolyData()}}(e,t)},"vtkCubeAxesActorHelper");function Rc(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};ss.extend(e,t,function(e,t,r){return{boundsScaleFactor:1.3,camera:null,dataBounds:[...Va.INIT_BOUNDS],faceVisibilityAngle:8,gridLines:!0,axisLabels:null,axisTitlePixelOffset:35,tickLabelPixelOffset:12,generateTicks:Nc,...r,axisTextStyle:{fontColor:"white",fontStyle:"normal",fontSize:18,fontFamily:"serif",...r?.axisTextStyle},tickTextStyle:{fontColor:"white",fontStyle:"normal",fontSize:14,fontFamily:"serif",...r?.tickTextStyle}}}(0,0,r)),t.lastFacesToDraw=[!1,!1,!1,!1,!1,!1],t.axisLabels=["X-Axis","Y-Axis","Z-Axis"],t.tickCounts=[],t.textValues=[],t.lastTickBounds=[],t.tmCanvas=document.createElement("canvas"),t.tmContext=t.tmCanvas.getContext("2d"),t._tmAtlas=new Map,t.tmTexture=vc.newInstance({resizable:!0}),t.tmTexture.setInterpolate(!1),e.getProperty().setDiffuse(0),e.getProperty().setAmbient(1),t.gridMapper=Gl.newInstance(),t.polyData=mc.newInstance(),t.gridMapper.setInputData(t.polyData),t.gridActor=ss.newInstance(),t.gridActor.setMapper(t.gridMapper),t.gridActor.setProperty(e.getProperty()),t.gridActor.setParentProp(e),t.textPolyData=mc.newInstance(),zt.setGet(e,t,["axisTitlePixelOffset","boundsScaleFactor","faceVisibilityAngle","gridLines","tickLabelPixelOffset","generateTicks"]),zt.setGetArray(e,t,["dataBounds"],6),zt.setGetArray(e,t,["axisLabels"],3),zt.get(e,t,["axisTextStyle","tickTextStyle","camera","tmTexture","textValues","textPolyData","tickCounts","gridActor"]),function(e,t){t.classHierarchy.push("vtkCubeAxesActor"),e.setCamera=r=>{t.camera!==r&&(t.cameraModifiedSub&&(t.cameraModifiedSub.unsubscribe(),t.cameraModifiedSub=null),t.camera=r,r&&(t.cameraModifiedSub=r.onModified(e.update)),e.update(),e.modified())},e.computeFacesToDraw=()=>{const e=t.camera.getViewMatrix();m(e,e);let r=!1;const n=Va.getDiagonalLength(t.dataBounds),o=Math.sin(t.faceVisibilityAngle*Math.PI/180);for(let i=0;i<6;i++){let a=!1;const s=Math.floor(i/2),l=(s+1)%3,u=(s+2)%3;t.dataBounds[2*l]!==t.dataBounds[2*l+1]&&t.dataBounds[2*u]!==t.dataBounds[2*u+1]&&(Tc[s]=t.dataBounds[i]-.1*n*bc[i][s],Tc[l]=.5*(t.dataBounds[2*l]+t.dataBounds[2*l+1]),Tc[u]=.5*(t.dataBounds[2*u]+t.dataBounds[2*u+1]),Sr(Ac,Tc,e),Tc[s]=t.dataBounds[i],Sr(Ec,Tc,e),yr(Ac,Ec,Ac),br(Ac,Ac),a=Ac[2]>o,t.camera.getParallelProjection()||(br(Ec,Ec),a=xr(Ec,Ac)>o)),a!==t.lastFacesToDraw[i]&&(t.lastFacesToDraw[i]=a,r=!0)}return r},e.updatePolyData=(e,r,n)=>{let o=0,i=0;o+=8;let a=0;for(let e=0;e<12;e++)r[e]>0&&a++;if(i+=a,t.gridLines)for(let t=0;t<6;t++)e[t]&&(o+=2*n[Cc[t][0]].length+2*n[Cc[t][1]].length,i+=n[Cc[t][0]].length+n[Cc[t][1]].length);const s=new Float64Array(3*o),l=new Uint32Array(3*i);let u=0,c=0;for(let e=0;e<2;e++)for(let r=0;r<2;r++)for(let n=0;n<2;n++)s[3*u]=t.dataBounds[n],s[3*u+1]=t.dataBounds[2+r],s[3*u+2]=t.dataBounds[4+e],u++;for(let e=0;e<12;e++)r[e]>0&&(l[3*c]=2,l[3*c+1]=_c[e][0],l[3*c+2]=_c[e][1],c++);if(t.gridLines)for(let r=0;r<6;r++)if(e[r]){const e=Math.floor(r/2);let o=n[Cc[r][0]];for(let n=0;n{let i=0;for(let e=0;e<12;e++)1===r[e]&&(i+=2,i+=n[Sc[e]].length);const a=t.polyData.getPoints().getData(),s=new Float64Array(3*i);let l=0,u=0,c=0;for(let i=0;i<6;i++)if(e[i])for(let e=0;e<4;e++){const d=xc[i][e];if(1===r[d]){const e=Sc[d],r=3*_c[d][0],p=3*_c[d][1];s[3*l]=.5*(a[r]+a[p]),s[3*l+1]=.5*(a[r+1]+a[p+1]),s[3*l+2]=.5*(a[r+2]+a[p+2]),l++,s[3*l+Math.floor(i/2)]=t.dataBounds[i],s[3*l+Cc[i][0]]=.5*(t.dataBounds[2*Cc[i][0]]+t.dataBounds[2*Cc[i][0]+1]),s[3*l+Cc[i][1]]=.5*(t.dataBounds[2*Cc[i][1]]+t.dataBounds[2*Cc[i][1]+1]),l++,t.textValues[u]=t.axisLabels[e],u++;const f=(e+1)%3,h=(e+2)%3,m=n[e],g=o[e];t.tickCounts[c]=m.length;for(let n=0;n{if(!t.camera)return;const r=e.computeFacesToDraw(),n=t.lastFacesToDraw;let o=!1;for(let e=0;e<6;e++)t.dataBounds[e]!==t.lastTickBounds[e]&&(o=!0,t.lastTickBounds[e]=t.dataBounds[e]);if(r||o||t.forceUpdate){const r=new Array(12).fill(0);for(let e=0;e<6;e++)if(n[e])for(let t=0;t<4;t++)r[xc[e][t]]++;const i=t.generateTicks(t.dataBounds);e.updatePolyData(n,r,i.ticks),e.updateTextData(n,r,i.ticks,i.tickStrings),(o||t.forceUpdate)&&e.updateTextureAtlas(i.tickStrings)}t.forceUpdate=!1},e.updateTextureAtlas=e=>{t.tmContext.textBaseline="bottom",t.tmContext.textAlign="left",t._tmAtlas.clear();let r=0,n=1;for(let o=0;o<3;o++){if(!t._tmAtlas.has(t.axisLabels[o])){Oc(t.tmContext,t.axisTextStyle);const e=t.tmContext.measureText(t.axisLabels[o]),i={height:e.actualBoundingBoxAscent+2,startingHeight:n,width:e.width+2,textStyle:t.axisTextStyle};t._tmAtlas.set(t.axisLabels[o],i),n+=i.height,r{e.tcoords=[0,(n-e.startingHeight-e.height)/n,e.width/r,(n-e.startingHeight-e.height)/n,e.width/r,(n-e.startingHeight)/n,0,(n-e.startingHeight)/n]}),t.tmCanvas.width=r,t.tmCanvas.height=n,t.tmContext.textBaseline="bottom",t.tmContext.textAlign="left",t.tmContext.clearRect(0,0,r,n),t._tmAtlas.forEach((e,r)=>{Oc(t.tmContext,e.textStyle),t.tmContext.fillText(r,1,e.startingHeight+e.height-1)}),t.tmTexture.setCanvas(t.tmCanvas),t.tmTexture.modified()},e.onModified(()=>{t.forceUpdate=!0,e.update()}),e.setTickTextStyle=r=>{t.tickTextStyle={...t.tickTextStyle,...r},e.modified()},e.setAxisTextStyle=r=>{t.axisTextStyle={...t.axisTextStyle,...r},e.modified()},e.get_tmAtlas=()=>t._tmAtlas,e.getBounds=()=>(e.update(),Va.setBounds(t.bounds,t.gridActor.getBounds()),Va.scaleAboutCenter(t.bounds,t.boundsScaleFactor,t.boundsScaleFactor,t.boundsScaleFactor),t.bounds);const r=zt.chain(e.setProperty,t.gridActor.setProperty);e.setProperty=e=>r(e)[0]}(e,t)}var Fc={newInstance:zt.newInstance(Rc,"vtkCubeAxesActor"),extend:Rc,newCubeAxesActorHelper:Mc,defaultGenerateTicks:Nc};const Bc={};const Lc=Pt(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Bc,r),Xt.extend(e,t,r),t.CubeAxesActorHelper=Fc.newCubeAxesActorHelper(),function(e,t){t.classHierarchy.push("vtkOpenGLCubeAxesActor"),e.buildPass=r=>{r&&(t._openGLRenderer=e.getFirstAncestorOfType("vtkOpenGLRenderer"),t._openGLRenderWindow=t._openGLRenderer.getParent(),t.CubeAxesActorHelper.getRenderable()||t.CubeAxesActorHelper.setRenderable(t.renderable),e.prepareNodes(),e.addMissingNode(t.CubeAxesActorHelper.getTmActor()),e.addMissingNode(t.renderable.getGridActor()),e.removeUnusedNodes())},e.opaquePass=(e,r)=>{if(e){const e=t._openGLRenderer?t._openGLRenderer.getRenderable().getActiveCamera():null,r=t._openGLRenderer.getTiledSizeAndOrigin();t.CubeAxesActorHelper.updateAPISpecificData([r.usize,r.vsize],e,t._openGLRenderWindow.getRenderable())}}}(e,t)},"vtkOpenGLCubeAxesActor");Qt("vtkCubeAxesActor",Lc);const kc={ARRAY_BUFFER:0,ELEMENT_ARRAY_BUFFER:1,TEXTURE_BUFFER:2};var Uc={ObjectType:kc};const{ObjectType:Vc}=Uc,Gc={objectType:Vc.ARRAY_BUFFER,context:null,allocatedGPUMemoryInBytes:0};function zc(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Gc,r),zt.obj(e,t),zt.get(e,t,["_openGLRenderWindow","allocatedGPUMemoryInBytes"]),zt.moveToProtected(e,t,["openGLRenderWindow"]),function(e,t){function r(e){switch(e){case Vc.ELEMENT_ARRAY_BUFFER:return t.context.ELEMENT_ARRAY_BUFFER;case Vc.TEXTURE_BUFFER:if("TEXTURE_BUFFER"in t.context)return t.context.TEXTURE_BUFFER;case Vc.ARRAY_BUFFER:default:return t.context.ARRAY_BUFFER}}t.classHierarchy.push("vtkOpenGLBufferObject");let n=null,o=null,i=!0,a="";e.getType=()=>n,e.setType=e=>{n=e},e.getHandle=()=>o,e.isReady=()=>!1===i,e.generateBuffer=e=>{const i=r(e);return null===o&&(o=t.context.createBuffer(),n=e),r(n)===i},e.upload=(s,l)=>e.generateBuffer(l)?(t.context.bindBuffer(r(n),o),t.context.bufferData(r(n),s,t.context.STATIC_DRAW),t.allocatedGPUMemoryInBytes=s.length*s.BYTES_PER_ELEMENT,i=!1,!0):(a="Trying to upload array buffer to incompatible buffer.",!1),e.bind=()=>!!o&&(t.context.bindBuffer(r(n),o),!0),e.release=()=>!!o&&(t.context.bindBuffer(r(n),null),!0),e.releaseGraphicsResources=()=>{null!==o&&(t.context.bindBuffer(r(n),null),t.context.deleteBuffer(o),o=null,t.allocatedGPUMemoryInBytes=0)},e.setOpenGLRenderWindow=r=>{t._openGLRenderWindow!==r&&(e.releaseGraphicsResources(),t._openGLRenderWindow=r,t.context=null,r&&(t.context=t._openGLRenderWindow.getContext()))},e.getError=()=>a}(e,t)}var jc={newInstance:zt.newInstance(zc),extend:zc,...Uc};const{vtkErrorMacro:Wc}=zt;function Hc(e,t){t.classHierarchy.push("vtkOpenGLCellArrayBufferObject"),e.setType(kc.ARRAY_BUFFER),e.createVBO=function(r,n,o,i){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;if(!r.getData()||!r.getData().length)return t.elementCount=0,0;t.blockSize=3,t.vertexOffset=0,t.normalOffset=0,t.tCoordOffset=0,t.tCoordComponents=0,t.colorComponents=0,t.colorOffset=0,t.customData=[];const s=i.points.getData();let l=null,u=null,c=null;const d=i.colors?i.colors.getNumberOfComponents():0,p=i.tcoords?i.tcoords.getNumberOfComponents():0;i.normals&&(t.normalOffset=4*t.blockSize,t.blockSize+=3,l=i.normals.getData()),i.customAttributes&&i.customAttributes.forEach(e=>{e&&(t.customData.push({data:e.getData(),offset:4*t.blockSize,components:e.getNumberOfComponents(),name:e.getName()}),t.blockSize+=e.getNumberOfComponents())}),i.tcoords&&(t.tCoordOffset=4*t.blockSize,t.tCoordComponents=p,t.blockSize+=p,u=i.tcoords.getData()),i.colors?(t.colorComponents=i.colors.getNumberOfComponents(),t.colorOffset=0,c=i.colors.getData(),t.colorBO||(t.colorBO=jc.newInstance()),t.colorBO.setOpenGLRenderWindow(t._openGLRenderWindow)):t.colorBO=null,t.stride=4*t.blockSize;let f,h=0,m=0,g=0,y=0,v=0,b=0;const x={anythingToPoints(e,t,r,n){for(let o=0;o2)for(let o=0;o2){for(let o=0;oe,linesToWireframe:(e,t)=>e>1?2*(e-1):0,polysToWireframe:(e,t)=>e>2?2*e:0,stripsToWireframe:(e,t)=>e>2?4*e-6:0,polysToSurface:(e,t)=>e>2?3*(e-2):0,stripsToSurface:(e,t,r)=>e>2?3*(e-2):0};let S=null,C=null;o===Ja.POINTS||"verts"===n?(S=x.anythingToPoints,C=_.anythingToPoints):o===Ja.WIREFRAME||"lines"===n?(S=x[`${n}ToWireframe`],C=_[`${n}ToWireframe`]):(S=x[`${n}ToSurface`],C=_[`${n}ToSurface`]);const T=r.getData(),w=T.length;let A=0;for(let e=0;e0&&(Math.abs(r)/t>1e6||Math.abs(Math.log10(t))>3||0===t&&r>1e6);if(n){const t=new Float64Array(3),r=new Float64Array(3);for(let n=0;n<3;++n){const o=e.getRange(n),i=o[1]-o[0];t[n]=.5*(o[1]+o[0]),r[n]=i>0?1/i:1}return{useShiftAndScale:n,coordShift:t,coordScale:r}}return{useShiftAndScale:n,coordShift:new Float32Array([0,0,0]),coordScale:new Float32Array([1,1,1])}}(i.points);if(O?e.setCoordShiftAndScale(N,M):!0===t.coordShiftAndScaleEnabled&&e.setCoordShiftAndScale(null,null),a)if(a.points||a.cells){const e=new Int32Array(A+a.points.length);e.set(a.points),a.points=e;const t=new Int32Array(A+a.cells.length);t.set(a.cells),a.cells=t}else a.points=new Int32Array(A),a.cells=new Int32Array(A);let R=i.vertexOffset;f=function(e,r){if(a&&(a.points[R]=e,a.cells[R]=b+i.cellOffset),++R,h=3*e,t.coordShiftAndScaleEnabled?(D[P++]=(s[h++]-t.coordShift[0])*t.coordScale[0],D[P++]=(s[h++]-t.coordShift[1])*t.coordScale[1],D[P++]=(s[h++]-t.coordShift[2])*t.coordScale[2]):(D[P++]=s[h++],D[P++]=s[h++],D[P++]=s[h++]),null!==l&&(m=i.haveCellNormals?3*(b+i.cellOffset):3*e,D[P++]=l[m++],D[P++]=l[m++],D[P++]=l[m++]),t.customData.forEach(t=>{v=e*t.components;for(let e=0;e{null===e||e.constructor===Float64Array&&3===e.length?null===r||r.constructor===Float64Array&&3===r.length?(null!==t.coordShift&&null!==e&&Tr(e,t.coordShift)||(t.coordShift=e),null!==t.coordScale&&null!==r&&Tr(r,t.coordScale)||(t.coordScale=r),t.coordShiftAndScaleEnabled=function(e,t){return null!==e&&null!==t&&!(Cr(e,[0,0,0])&&Cr(t,[1,1,1]))}(t.coordShift,t.coordScale),t.coordShiftAndScaleEnabled?t.inverseShiftAndScaleMatrix=function(e,t){const r=new Float64Array(3);var n,o;o=t,(n=r)[0]=1/o[0],n[1]=1/o[1],n[2]=1/o[2];const i=new Float64Array(16);return L(i,Mi(),e,r),i}(t.coordShift,t.coordScale):t.inverseShiftAndScaleMatrix=null):Wc("Wrong type for coordScale, expected vec3 or null"):Wc("Wrong type for coordShift, expected vec3 or null")}}const Kc={elementCount:0,stride:0,colorBOStride:0,vertexOffset:0,normalOffset:0,tCoordOffset:0,tCoordComponents:0,colorOffset:0,colorComponents:0,tcoordBO:null,customData:[],coordShift:null,coordScale:null,coordShiftAndScaleEnabled:!1,inverseShiftAndScaleMatrix:null};function Xc(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Kc,r),jc.extend(e,t,r),zt.setGet(e,t,["colorBO","elementCount","stride","colorBOStride","vertexOffset","normalOffset","tCoordOffset","tCoordComponents","colorOffset","colorComponents","customData"]),zt.get(e,t,["coordShift","coordScale","coordShiftAndScaleEnabled","inverseShiftAndScaleMatrix"]),Hc(e,t)}var $c={newInstance:zt.newInstance(Xc),extend:Xc};const{vtkErrorMacro:qc}=zt,Yc={shaderType:"Unknown",source:"",error:"",handle:0,dirty:!1,context:null};function Jc(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Yc,r),zt.obj(e,t),zt.setGet(e,t,["shaderType","source","error","handle","context"]),function(e,t){t.classHierarchy.push("vtkShader"),e.compile=()=>{let e=t.context.VERTEX_SHADER;if(!t.source||!t.source.length||"Unknown"===t.shaderType)return!1;if(0!==t.handle&&(t.context.deleteShader(t.handle),t.handle=0),e="Fragment"===t.shaderType?t.context.FRAGMENT_SHADER:t.context.VERTEX_SHADER,t.handle=t.context.createShader(e),t.context.shaderSource(t.handle,t.source),t.context.compileShader(t.handle),!t.context.getShaderParameter(t.handle,t.context.COMPILE_STATUS)){const e=t.context.getShaderInfoLog(t.handle);return qc(`Error compiling shader '${t.source}': ${e}`),t.context.deleteShader(t.handle),t.handle=0,!1}return!0},e.cleanup=()=>{"Unknown"!==t.shaderType&&0!==t.handle&&(t.context.deleteShader(t.handle),t.handle=0,t.dirty=!0)}}(e,t)}var Qc={newInstance:zt.newInstance(Jc,"vtkShader"),extend:Jc};const{vtkErrorMacro:Zc}=zt,ed={vertexShaderHandle:0,fragmentShaderHandle:0,geometryShaderHandle:0,vertexShader:null,fragmentShader:null,geometryShader:null,linked:!1,bound:!1,compiled:!1,error:"",handle:0,numberOfOutputs:0,attributesLocs:null,uniformLocs:null,md5Hash:0,context:null,lastCameraMTime:null};function td(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,ed,r),t.attributesLocs={},t.uniformLocs={},t.vertexShader=Qc.newInstance(),t.vertexShader.setShaderType("Vertex"),t.fragmentShader=Qc.newInstance(),t.fragmentShader.setShaderType("Fragment"),t.geometryShader=Qc.newInstance(),t.geometryShader.setShaderType("Geometry"),zt.obj(e,t),zt.get(e,t,["lastCameraMTime"]),zt.setGet(e,t,["error","handle","compiled","bound","md5Hash","vertexShader","fragmentShader","geometryShader","linked"]),function(e,t){t.classHierarchy.push("vtkShaderProgram"),e.compileShader=()=>t.vertexShader.compile()?t.fragmentShader.compile()?e.attachShader(t.vertexShader)&&e.attachShader(t.fragmentShader)?e.link()?(e.setCompiled(!0),1):(Zc(`Links failed: ${t.error}`),0):(Zc(t.error),0):(Zc(t.fragmentShader.getSource().split("\n").map((e,t)=>`${t}: ${e}`).join("\n")),Zc(t.fragmentShader.getError()),0):(Zc(t.vertexShader.getSource().split("\n").map((e,t)=>`${t}: ${e}`).join("\n")),Zc(t.vertexShader.getError()),0),e.cleanup=()=>{"Unknown"!==t.shaderType&&0!==t.handle&&(e.release(),0!==t.vertexShaderHandle&&(t.context.detachShader(t.handle,t.vertexShaderHandle),t.vertexShaderHandle=0),0!==t.fragmentShaderHandle&&(t.context.detachShader(t.handle,t.fragmentShaderHandle),t.fragmentShaderHandle=0),t.context.deleteProgram(t.handle),t.handle=0,e.setCompiled(!1))},e.bind=()=>!(!t.linked&&!e.link()||(t.context.useProgram(t.handle),e.setBound(!0),0)),e.isBound=()=>!!t.bound,e.release=()=>{t.context.useProgram(null),e.setBound(!1)},e.setContext=e=>{t.vertexShader.setContext(e),t.fragmentShader.setContext(e),t.geometryShader.setContext(e)},e.link=()=>{if(t.linked)return!0;if(0===t.handle)return t.error="Program has not been initialized, and/or does not have shaders.",!1;if(t.uniformLocs={},t.context.linkProgram(t.handle),!t.context.getProgramParameter(t.handle,t.context.LINK_STATUS)){const e=t.context.getProgramInfoLog(t.handle);return Zc(`Error linking shader ${e}`),t.handle=0,!1}return e.setLinked(!0),t.attributeLocs={},!0},e.setUniformMatrix=(r,n)=>{const o=e.findUniform(r);if(-1===o)return t.error=`Could not set uniform ${r} . No such uniform.`,!1;const i=new Float32Array(n);return t.context.uniformMatrix4fv(o,!1,i),!0},e.setUniformMatrix3x3=(r,n)=>{const o=e.findUniform(r);if(-1===o)return t.error=`Could not set uniform ${r} . No such uniform.`,!1;const i=new Float32Array(n);return t.context.uniformMatrix3fv(o,!1,i),!0},e.setUniformf=(r,n)=>{const o=e.findUniform(r);return-1===o?(t.error=`Could not set uniform ${r} . No such uniform.`,!1):(t.context.uniform1f(o,n),!0)},e.setUniformfv=(r,n)=>{const o=e.findUniform(r);return-1===o?(t.error=`Could not set uniform ${r} . No such uniform.`,!1):(t.context.uniform1fv(o,n),!0)},e.setUniformi=(r,n)=>{const o=e.findUniform(r);return-1===o?(t.error=`Could not set uniform ${r} . No such uniform.`,!1):(t.context.uniform1i(o,n),!0)},e.setUniformiv=(r,n)=>{const o=e.findUniform(r);return-1===o?(t.error=`Could not set uniform ${r} . No such uniform.`,!1):(t.context.uniform1iv(o,n),!0)},e.setUniform2f=(r,n,o)=>{const i=e.findUniform(r);if(-1===i)return t.error=`Could not set uniform ${r} . No such uniform.`,!1;if(void 0===o)throw new RangeError("Invalid number of values for array");return t.context.uniform2f(i,n,o),!0},e.setUniform2fv=(r,n)=>{const o=e.findUniform(r);return-1===o?(t.error=`Could not set uniform ${r} . No such uniform.`,!1):(t.context.uniform2fv(o,n),!0)},e.setUniform2i=(r,n,o)=>{const i=e.findUniform(r);if(-1===i)return t.error=`Could not set uniform ${r} . No such uniform.`,!1;if(void 0===o)throw new RangeError("Invalid number of values for array");return t.context.uniform2i(i,n,o),!0},e.setUniform2iv=(r,n)=>{const o=e.findUniform(r);return-1===o?(t.error=`Could not set uniform ${r} . No such uniform.`,!1):(t.context.uniform2iv(o,n),!0)},e.setUniform3f=(r,n,o,i)=>{const a=e.findUniform(r);if(-1===a)return t.error=`Could not set uniform ${r} . No such uniform.`,!1;if(void 0===i)throw new RangeError("Invalid number of values for array");return t.context.uniform3f(a,n,o,i),!0},e.setUniform3fArray=(r,n)=>{const o=e.findUniform(r);if(-1===o)return t.error=`Could not set uniform ${r} . No such uniform.`,!1;if(!Array.isArray(n)||3!==n.length)throw new RangeError("Invalid number of values for array");return t.context.uniform3f(o,n[0],n[1],n[2]),!0},e.setUniform3fv=(r,n)=>{const o=e.findUniform(r);return-1===o?(t.error=`Could not set uniform ${r} . No such uniform.`,!1):(t.context.uniform3fv(o,n),!0)},e.setUniform3i=function(r){const n=e.findUniform(r);if(-1===n)return t.error=`Could not set uniform ${r} . No such uniform.`,!1;for(var o=arguments.length,i=new Array(o>1?o-1:0),a=1;a{const o=e.findUniform(r);return-1===o?(t.error=`Could not set uniform ${r} . No such uniform.`,!1):(t.context.uniform3iv(o,n),!0)},e.setUniform4f=function(r){const n=e.findUniform(r);if(-1===n)return t.error=`Could not set uniform ${r} . No such uniform.`,!1;for(var o=arguments.length,i=new Array(o>1?o-1:0),a=1;a{const o=e.findUniform(r);return-1===o?(t.error=`Could not set uniform ${r} . No such uniform.`,!1):(t.context.uniform4fv(o,n),!0)},e.setUniform4i=function(r){const n=e.findUniform(r);if(-1===n)return t.error=`Could not set uniform ${r} . No such uniform.`,!1;for(var o=arguments.length,i=new Array(o>1?o-1:0),a=1;a{const o=e.findUniform(r);return-1===o?(t.error=`Could not set uniform ${r} . No such uniform.`,!1):(t.context.uniform4iv(o,n),!0)},e.findUniform=e=>{if(!e||!t.linked)return-1;let r=t.uniformLocs[e];return void 0!==r?r:(r=t.context.getUniformLocation(t.handle,e),null===r?(t.error=`Uniform ${e} not found in current shader program.`,t.uniformLocs[e]=-1,-1):(t.uniformLocs[e]=r,r))},e.isUniformUsed=e=>{if(!e)return!1;let r=t.uniformLocs[e];return void 0!==r?null!==r:t.linked?(r=t.context.getUniformLocation(t.handle,e),t.uniformLocs[e]=r,null!==r):(Zc("attempt to find uniform when the shader program is not linked"),!1)},e.isAttributeUsed=e=>{if(!e)return!1;if(e in t.attributeLocs)return!0;if(!t.linked)return Zc("attempt to find uniform when the shader program is not linked"),!1;const r=t.context.getAttribLocation(t.handle,e);return-1!==r&&(t.attributeLocs[e]=r,!0)},e.attachShader=r=>{if(0===r.getHandle())return t.error="Shader object was not initialized, cannot attach it.",!1;if("Unknown"===r.getShaderType())return t.error="Shader object is of type Unknown and cannot be used.",!1;if(0===t.handle){const e=t.context.createProgram();if(0===e)return t.error="Could not create shader program.",!1;t.handle=e,t.linked=!1}return"Vertex"===r.getShaderType()&&(0!==t.vertexShaderHandle&&t.context.detachShader(t.handle,t.vertexShaderHandle),t.vertexShaderHandle=r.getHandle()),"Fragment"===r.getShaderType()&&(0!==t.fragmentShaderHandle&&t.context.detachShader(t.handle,t.fragmentShaderHandle),t.fragmentShaderHandle=r.getHandle()),t.context.attachShader(t.handle,r.getHandle()),e.setLinked(!1),!0},e.detachShader=e=>{if(0===e.getHandle())return t.error="shader object was not initialized, cannot attach it.",!1;if("Unknown"===e.getShaderType())return t.error="Shader object is of type Unknown and cannot be used.",!1;switch(0===t.handle&&(t.error="This shader program has not been initialized yet."),e.getShaderType()){case"Vertex":return t.vertexShaderHandle!==e.getHandle()?(t.error="The supplied shader was not attached to this program.",!1):(t.context.detachShader(t.handle,e.getHandle()),t.vertexShaderHandle=0,t.linked=!1,!0);case"Fragment":return t.fragmentShaderHandle!==e.getHandle()?(t.error="The supplied shader was not attached to this program.",!1):(t.context.detachShader(t.handle,e.getHandle()),t.fragmentShaderHandle=0,t.linked=!1,!0);default:return!1}},e.setContext=e=>{t.context=e,t.vertexShader.setContext(e),t.fragmentShader.setContext(e),t.geometryShader.setContext(e)},e.setLastCameraMTime=e=>{t.lastCameraMTime=e}}(e,t)}var rd={newInstance:zt.newInstance(td,"vtkShaderProgram"),extend:td,substitute:function(e,t,r,n){const o="string"==typeof r?r:r.join("\n"),i=!1===n?t:new RegExp(t,"g"),a=e.replace(i,o);return{replace:a!==o,result:a}}};const nd={forceEmulation:!1,handleVAO:0,handleProgram:0,supported:!0,buffers:null,context:null};function od(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,nd,r),t.buffers=[],zt.obj(e,t),zt.get(e,t,["supported"]),zt.setGet(e,t,["forceEmulation"]),function(e,t){t.classHierarchy.push("vtkOpenGLVertexArrayObject"),e.exposedMethod=()=>{},e.initialize=()=>{t.instancingExtension=null,t._openGLRenderWindow.getWebgl2()||(t.instancingExtension=t.context.getExtension("ANGLE_instanced_arrays")),!t.forceEmulation&&t._openGLRenderWindow&&t._openGLRenderWindow.getWebgl2()?(t.extension=null,t.supported=!0,t.handleVAO=t.context.createVertexArray()):(t.extension=t.context.getExtension("OES_vertex_array_object"),!t.forceEmulation&&t.extension?(t.supported=!0,t.handleVAO=t.extension.createVertexArrayOES()):t.supported=!1)},e.isReady=()=>0!==t.handleVAO||!1===t.supported,e.bind=()=>{if(e.isReady()||e.initialize(),e.isReady()&&t.supported)t.extension?t.extension.bindVertexArrayOES(t.handleVAO):t.context.bindVertexArray(t.handleVAO);else if(e.isReady()){const e=t.context;for(let r=0;r0&&(t.instancingExtension?t.instancingExtension.vertexAttribDivisorANGLE(o.index+r,1):e.vertexAttribDivisor(o.index+r,1))}}}},e.release=()=>{if(e.isReady()&&t.supported)t.extension?t.extension.bindVertexArrayOES(null):t.context.bindVertexArray(null);else if(e.isReady()){const e=t.context;for(let r=0;r0&&(t.instancingExtension?t.instancingExtension.vertexAttribDivisorANGLE(o.index+r,0):e.vertexAttribDivisor(o.index+r,0)),e.disableVertexAttribArray(o.index+r)}}}},e.shaderProgramChanged=()=>{e.release(),t.handleVAO&&(t.extension?t.extension.deleteVertexArrayOES(t.handleVAO):t.context.deleteVertexArray(t.handleVAO)),t.handleVAO=0,t.handleProgram=0},e.releaseGraphicsResources=()=>{e.shaderProgramChanged(),t.handleVAO&&(t.extension?t.extension.deleteVertexArrayOES(t.handleVAO):t.context.deleteVertexArray(t.handleVAO)),t.handleVAO=0,t.supported=!0,t.handleProgram=0},e.addAttributeArray=(t,r,n,o,i,a,s,l)=>e.addAttributeArrayWithDivisor(t,r,n,o,i,a,s,l,0,!1),e.addAttributeArrayWithDivisor=(r,n,o,i,a,s,l,u,c,d)=>{if(!r)return!1;if(!r.isBound()||0===n.getHandle()||n.getType()!==kc.ARRAY_BUFFER)return!1;if(0===t.handleProgram&&(t.handleProgram=r.getHandle()),e.isReady()||e.initialize(),!e.isReady()||t.handleProgram!==r.getHandle())return!1;const p=t.context,f={};if(f.name=o,f.index=p.getAttribLocation(t.handleProgram,o),f.offset=i,f.stride=a,f.type=s,f.size=l,f.normalize=u,f.isMatrix=d,f.divisor=c,-1===f.Index)return!1;if(n.bind(),p.enableVertexAttribArray(f.index),p.vertexAttribPointer(f.index,f.size,f.type,f.normalize,f.stride,f.offset),c>0&&(t.instancingExtension?t.instancingExtension.vertexAttribDivisorANGLE(f.index,1):p.vertexAttribDivisor(f.index,1)),f.buffer=n.getHandle(),!t.supported){let e=!1;for(let r=0;r{const d=e.addAttributeArrayWithDivisor(r,n,o,i,a,s,l,u,c,!0);if(!d)return d;const p=t.context,f=p.getAttribLocation(t.handleProgram,o);for(let e=1;e0&&(t.instancingExtension?t.instancingExtension.vertexAttribDivisorANGLE(f+e,1):p.vertexAttribDivisor(f+e,1));return!0},e.removeAttributeArray=r=>{if(!e.isReady()||0===t.handleProgram)return!1;if(!t.supported)for(let e=0;e{t._openGLRenderWindow!==r&&(e.releaseGraphicsResources(),t._openGLRenderWindow=r,t.context=null,r&&(t.context=t._openGLRenderWindow.getContext()))}}(e,t)}var id={newInstance:zt.newInstance(od,"vtkOpenGLVertexArrayObject"),extend:od};const ad={Start:0,Points:0,Lines:1,Tris:2,TriStrips:3,TrisEdges:4,TriStripsEdges:5,End:6},sd={context:null,program:null,shaderSourceTime:null,VAO:null,attributeUpdateTime:null,CABO:null,primitiveType:0,pointPicking:!1};function ld(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,sd,r),zt.obj(e,t),t.shaderSourceTime={},zt.obj(t.shaderSourceTime),t.attributeUpdateTime={},zt.obj(t.attributeUpdateTime),zt.setGet(e,t,["program","shaderSourceTime","VAO","attributeUpdateTime","CABO","primitiveType","pointPicking"]),t.program=rd.newInstance(),t.VAO=id.newInstance(),t.CABO=$c.newInstance(),function(e,t){t.classHierarchy.push("vtkOpenGLHelper"),e.setOpenGLRenderWindow=e=>{t.context=e.getContext(),t.program.setContext(t.context),t.VAO.setOpenGLRenderWindow(e),t.CABO.setOpenGLRenderWindow(e)},e.releaseGraphicsResources=e=>{t.VAO.releaseGraphicsResources(),t.CABO.releaseGraphicsResources(),t.CABO.setElementCount(0)},e.drawArrays=(r,n,o,i)=>{if(t.CABO.getElementCount()){const a=e.getOpenGLMode(o),s=e.haveWideLines(r,n),l=t.context,u=l.getParameter(l.DEPTH_WRITEMASK);t.pointPicking&&l.depthMask(!1),a===l.LINES&&s?(e.updateShaders(r,n,i),l.drawArraysInstanced(a,0,t.CABO.getElementCount(),2*Math.ceil(n.getProperty().getLineWidth()))):(l.lineWidth(n.getProperty().getLineWidth()),e.updateShaders(r,n,i),l.drawArrays(a,0,t.CABO.getElementCount()),l.lineWidth(1));const c=(a===l.POINTS?1:0)||(a===l.LINES?2:3);return t.pointPicking&&l.depthMask(u),t.CABO.getElementCount()/c}return 0},e.getOpenGLMode=e=>{if(t.pointPicking)return t.context.POINTS;const r=t.primitiveType;return e===Ja.POINTS||r===ad.Points?t.context.POINTS:e===Ja.WIREFRAME||r===ad.Lines||r===ad.TrisEdges||r===ad.TriStripsEdges?t.context.LINES:t.context.TRIANGLES},e.haveWideLines=(e,r)=>r.getProperty().getLineWidth()>1&&!(t.CABO.getOpenGLRenderWindow()&&t.CABO.getOpenGLRenderWindow().getHardwareMaximumLineWidth()>=r.getProperty().getLineWidth()),e.getNeedToRebuildShaders=(t,r,n)=>!!(n.getNeedToRebuildShaders(e,t,r)||0===e.getProgram()||e.getShaderSourceTime().getMTime(){if(e.getNeedToRebuildShaders(r,n,o)){const i={Vertex:null,Fragment:null,Geometry:null};o.buildShaders(i,r,n);const a=t.CABO.getOpenGLRenderWindow().getShaderCache().readyShaderProgramArray(i.Vertex,i.Fragment,i.Geometry);a!==e.getProgram()&&(e.setProgram(a),e.getVAO().releaseGraphicsResources()),e.getShaderSourceTime().modified()}else t.CABO.getOpenGLRenderWindow().getShaderCache().readyShaderProgram(e.getProgram());e.getVAO().bind(),o.setMapperShaderParameters(e,r,n),o.setPropertyShaderParameters(e,r,n),o.setCameraShaderParameters(e,r,n),o.setLightingShaderParameters(e,r,n),o.invokeShaderCallbacks(e,r,n)},e.setMapperShaderParameters=(r,n,o)=>{if(e.haveWideLines(r,n)){e.getProgram().setUniform2f("viewportSize",o.usize,o.vsize);const t=parseFloat(n.getProperty().getLineWidth()),r=t/2;e.getProgram().setUniformf("lineWidthStepSize",t/Math.ceil(t)),e.getProgram().setUniformf("halfLineWidth",r)}t.primitiveType===ad.Points||n.getProperty().getRepresentation()===Ja.POINTS?e.getProgram().setUniformf("pointSize",n.getProperty().getPointSize()):t.pointPicking&&e.getProgram().setUniformf("pointSize",e.getPointPickingPrimitiveSize())},e.replaceShaderPositionVC=(r,n,o)=>{let i=r.Vertex;i=rd.substitute(i,"//VTK::PositionVC::Dec",["//VTK::PositionVC::Dec","uniform float pointSize;"]).result,i=rd.substitute(i,"//VTK::PositionVC::Impl",["//VTK::PositionVC::Impl"," gl_PointSize = pointSize;"],!1).result,e.getOpenGLMode(o.getProperty().getRepresentation())===t.context.LINES&&e.haveWideLines(n,o)&&(i=rd.substitute(i,"//VTK::PositionVC::Dec",["//VTK::PositionVC::Dec","uniform vec2 viewportSize;","uniform float lineWidthStepSize;","uniform float halfLineWidth;"]).result,i=rd.substitute(i,"//VTK::PositionVC::Impl",["//VTK::PositionVC::Impl"," if (halfLineWidth > 0.0)"," {"," float offset = float(gl_InstanceID / 2) * lineWidthStepSize - halfLineWidth;"," vec4 tmpPos = gl_Position;"," vec3 tmpPos2 = tmpPos.xyz / tmpPos.w;"," tmpPos2.x = tmpPos2.x + 2.0 * mod(float(gl_InstanceID), 2.0) * offset / viewportSize[0];"," tmpPos2.y = tmpPos2.y + 2.0 * mod(float(gl_InstanceID + 1), 2.0) * offset / viewportSize[1];"," gl_Position = vec4(tmpPos2.xyz * tmpPos.w, tmpPos.w);"," }"]).result),r.Vertex=i},e.getPointPickingPrimitiveSize=()=>t.primitiveType===ad.Points?2:t.primitiveType===ad.Lines?4:6,e.getAllocatedGPUMemoryInBytes=()=>e.getCABO().getAllocatedGPUMemoryInBytes()}(e,t)}var ud={newInstance:zt.newInstance(ld),extend:ld,primTypes:ad};const cd={NEAREST:0,LINEAR:1,NEAREST_MIPMAP_NEAREST:2,NEAREST_MIPMAP_LINEAR:3,LINEAR_MIPMAP_NEAREST:4,LINEAR_MIPMAP_LINEAR:5};var dd={Wrap:{CLAMP_TO_EDGE:0,REPEAT:1,MIRRORED_REPEAT:2},Filter:cd};const pd=new Float32Array(1),fd=new Int32Array(pd.buffer);var hd={fromHalf:function(e){const t=(32768&e)>>15,r=(31744&e)>>10,n=1023&e;return 0===r?(t?-1:1)*2**-14*(n/1024):31===r?n?NaN:1/0*(t?-1:1):(t?-1:1)*2**(r-15)*(1+n/1024)},toHalf:function(e){pd[0]=e;const t=fd[0];let r=t>>16&32768,n=t>>12&2047;const o=t>>23&255;return o<103?r:o>142?(r|=31744,r|=(255===o?0:1)&&8388607&t,r):o<113?(n|=2048,r|=(n>>114-o)+(n>>113-o&1),r):(r|=o-112<<10|n>>1,r+=1&n,r)}};let md;const{Wrap:gd,Filter:yd}=dd,{VtkDataTypes:vd}=_s,{vtkDebugMacro:bd,vtkErrorMacro:xd,vtkWarningMacro:_d,requiredParam:Sd}=jt,{toHalf:Cd}=hd;function Td(e,t){function r(){return{internalFormat:t.internalFormat,format:t.format,openGLDataType:t.openGLDataType,width:t.width,height:t.height}}t.classHierarchy.push("vtkOpenGLTexture"),e.render=function(){let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;if(r?t._openGLRenderWindow=r:(t._openGLRenderer=e.getFirstAncestorOfType("vtkOpenGLRenderer"),t._openGLRenderWindow=t._openGLRenderer.getLastAncestorOfType("vtkOpenGLRenderWindow")),t.context=t._openGLRenderWindow.getContext(),t.renderable.getInterpolate()?(t.generateMipmap?e.setMinificationFilter(yd.LINEAR_MIPMAP_LINEAR):e.setMinificationFilter(yd.LINEAR),e.setMagnificationFilter(yd.LINEAR)):(e.setMinificationFilter(yd.NEAREST),e.setMagnificationFilter(yd.NEAREST)),t.renderable.getRepeat()&&(e.setWrapR(gd.REPEAT),e.setWrapS(gd.REPEAT),e.setWrapT(gd.REPEAT)),t.renderable.getInputData()&&t.renderable.setImage(null),!t.handle||t.renderable.getMTime()>t.textureBuildTime.getMTime()){if(null!==t.renderable.getImageBitmap()&&(t.renderable.getInterpolate()&&(t.generateMipmap=!0,e.setMinificationFilter(yd.LINEAR_MIPMAP_LINEAR)),t.renderable.getImageBitmap()&&t.renderable.getImageLoaded()&&(e.create2DFromImageBitmap(t.renderable.getImageBitmap()),e.activate(),e.sendParameters(),t.textureBuildTime.modified())),null!==t.renderable.getImage()&&(t.renderable.getInterpolate()&&(t.generateMipmap=!0,e.setMinificationFilter(yd.LINEAR_MIPMAP_LINEAR)),t.renderable.getImage()&&t.renderable.getImageLoaded()&&(e.create2DFromImage(t.renderable.getImage()),e.activate(),e.sendParameters(),t.textureBuildTime.modified())),null!==t.renderable.getCanvas()){t.renderable.getInterpolate()&&(t.generateMipmap=!0,e.setMinificationFilter(yd.LINEAR_MIPMAP_LINEAR));const r=t.renderable.getCanvas();e.create2DFromRaw({width:r.width,height:r.height,numComps:4,dataType:vd.UNSIGNED_CHAR,data:r,flip:!0}),e.activate(),e.sendParameters(),t.textureBuildTime.modified()}if(null!==t.renderable.getJsImageData()){const r=t.renderable.getJsImageData();t.renderable.getInterpolate()&&(t.generateMipmap=!0,e.setMinificationFilter(yd.LINEAR_MIPMAP_LINEAR)),e.create2DFromRaw({width:r.width,height:r.height,numComps:4,dataType:vd.UNSIGNED_CHAR,data:r.data,flip:!0}),e.activate(),e.sendParameters(),t.textureBuildTime.modified()}const r=t.renderable.getInputData(0);if(r&&r.getPointData().getScalars()){const n=r.getExtent(),o=r.getPointData().getScalars(),i=[];for(let e=0;e{if(t.minificationFilter!==yd.LINEAR&&t.magnificationFilter!==yd.LINEAR||(void 0===md&&(md=function(){try{const e=4,t=2,r=1,n=new Int16Array([0,32767]),o=[1,1],i=document.createElement("canvas");i.width=e,i.height=e;const a=i.getContext("webgl2");if(!a)return!1;const s=a.getExtension("EXT_texture_norm16");if(!s)return!1;const l=`#version 300 es\n void main() {\n gl_PointSize = ${e.toFixed(1)};\n gl_Position = vec4(0, 0, 0, 1);\n }\n `,u="#version 300 es\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n\n uniform sampler2D u_image;\n\n out vec4 color;\n\n void main() {\n vec4 intColor = texture(u_image, gl_PointCoord.xy);\n color = vec4(vec3(intColor.rrr), 1);\n }\n ",c=a.createShader(a.VERTEX_SHADER);if(a.shaderSource(c,l),a.compileShader(c),!a.getShaderParameter(c,a.COMPILE_STATUS))return!1;const d=a.createShader(a.FRAGMENT_SHADER);if(a.shaderSource(d,u),a.compileShader(d),!a.getShaderParameter(d,a.COMPILE_STATUS))return!1;const p=a.createProgram();if(a.attachShader(p,c),a.attachShader(p,d),a.linkProgram(p),!a.getProgramParameter(p,a.LINK_STATUS))return!1;const f=a.createTexture();a.bindTexture(a.TEXTURE_2D,f),a.texImage2D(a.TEXTURE_2D,0,s.R16_SNORM_EXT,t,r,0,a.RED,a.SHORT,n),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.useProgram(p),a.drawArrays(a.POINTS,0,1);const h=new Uint8Array(4);a.readPixels(o[0],o[1],1,1,a.RGBA,a.UNSIGNED_BYTE,h);const[m,g,y]=h,v=a.getExtension("WEBGL_lose_context");return v&&v.loseContext(),m===g&&g===y&&0!==m}catch(e){return!1}}()),md))return t.oglNorm16Ext};function o(e){const[t,r,n,o,i,a]=e;return[r-t+1,o-n+1,a-i+1]}function i(e){const[t,r,n]=o(e);return t*r*n}function a(e,r){const n=new((arguments.length>2&&void 0!==arguments[2]?arguments[2]:null)||e.constructor)(r.reduce((e,t)=>e+i(t),0)),o=[t.width,t.height,t.depth];let a=0;return r.forEach(t=>{!function(e,t,r,n,o){const[i,a,s,l,u,c]=r,[d,p]=t,f=d*p;let h=o;for(let t=u;t<=c;t++){const r=t*f;for(let t=s;t<=l;t++){const o=r+t*d;for(let t=o+i,r=o+a;t<=r;t++,h++)n[h]=e[t]}}}(e,o,t,n,a),a+=i(t)}),n}function s(e){if(t._openGLRenderWindow.getWebgl2())return e;const r=[],n=t.width,o=t.height,i=t.components;if(e&&(!Eo(n)||!Eo(o))){const a=t.context.getExtension("OES_texture_half_float"),s=Ao(n),l=Ao(o),u=s*l*t.components;for(let c=0;c=o&&(u=o-1);const m=a-l,g=1-m;l=l*n*i,u=u*n*i;for(let t=0;t=n&&(p=n-1);const y=a-s;s*=i,p*=i;for(let t=0;t2048||o<-2048||o>2048)return!1}return!0}(n,o)||i;let s=!1;if(t._openGLRenderWindow.getWebgl2())s=t.openGLDataType===t.context.FLOAT&&null===t.context.getExtension("OES_texture_float_linear")&&a||t.openGLDataType===t.context.HALF_FLOAT;else{const e=t.context.getExtension("OES_texture_half_float");s=e&&t.openGLDataType===e.HALF_FLOAT_OES}t.canUseHalfFloat=s&&a}(i,u.offset,u.scale,n),e.useHalfFloat()||e.getOpenGLDataType(i,!0),{numComps:o,dataType:i,data:a,scaleOffsets:u}}e.destroyTexture=()=>{e.deactivate(),t.context&&t.handle&&t.context.deleteTexture(t.handle),t._prevTexParams=null,t.handle=0,t.numberOfDimensions=0,t.target=0,t.components=0,t.width=0,t.height=0,t.depth=0,e.resetFormatAndType()},e.createTexture=()=>{t.handle||(t.handle=t.context.createTexture(),t.target&&(t.context.bindTexture(t.target,t.handle),t.context.texParameteri(t.target,t.context.TEXTURE_MIN_FILTER,e.getOpenGLFilterMode(t.minificationFilter)),t.context.texParameteri(t.target,t.context.TEXTURE_MAG_FILTER,e.getOpenGLFilterMode(t.magnificationFilter)),t.context.texParameteri(t.target,t.context.TEXTURE_WRAP_S,e.getOpenGLWrapMode(t.wrapS)),t.context.texParameteri(t.target,t.context.TEXTURE_WRAP_T,e.getOpenGLWrapMode(t.wrapT)),t._openGLRenderWindow.getWebgl2()&&t.context.texParameteri(t.target,t.context.TEXTURE_WRAP_R,e.getOpenGLWrapMode(t.wrapR)),t.context.bindTexture(t.target,null)))},e.getTextureUnit=()=>t._openGLRenderWindow?t._openGLRenderWindow.getTextureUnitForTexture(e):-1,e.activate=()=>{t._openGLRenderWindow.activateTexture(e),e.bind()},e.deactivate=()=>{t._openGLRenderWindow&&t._openGLRenderWindow.deactivateTexture(e)},e.releaseGraphicsResources=r=>{r&&t.handle&&(r.activateTexture(e),r.deactivateTexture(e),t.context.deleteTexture(t.handle),t._prevTexParams=null,t.handle=0,t.numberOfDimensions=0,t.target=0,t.internalFormat=0,t.format=0,t.openGLDataType=0,t.components=0,t.width=0,t.height=0,t.depth=0,t.allocatedGPUMemoryInBytes=0),t.shaderProgram&&(t.shaderProgram.releaseGraphicsResources(r),t.shaderProgram=null)},e.bind=()=>{t.context.bindTexture(t.target,t.handle),t.autoParameters&&e.getMTime()>t.sendParametersTime.getMTime()&&e.sendParameters()},e.isBound=()=>{let e=!1;if(t.context&&t.handle){let r=0;t.target===t.context.TEXTURE_2D?r=t.context.TEXTURE_BINDING_2D:_d("impossible case"),e=t.context.getIntegerv(r)===t.handle}return e},e.sendParameters=()=>{t.context.texParameteri(t.target,t.context.TEXTURE_WRAP_S,e.getOpenGLWrapMode(t.wrapS)),t.context.texParameteri(t.target,t.context.TEXTURE_WRAP_T,e.getOpenGLWrapMode(t.wrapT)),t._openGLRenderWindow.getWebgl2()&&t.context.texParameteri(t.target,t.context.TEXTURE_WRAP_R,e.getOpenGLWrapMode(t.wrapR)),t.context.texParameteri(t.target,t.context.TEXTURE_MIN_FILTER,e.getOpenGLFilterMode(t.minificationFilter)),t.context.texParameteri(t.target,t.context.TEXTURE_MAG_FILTER,e.getOpenGLFilterMode(t.magnificationFilter)),t._openGLRenderWindow.getWebgl2()&&(t.context.texParameteri(t.target,t.context.TEXTURE_BASE_LEVEL,t.baseLevel),t.context.texParameteri(t.target,t.context.TEXTURE_MAX_LEVEL,t.maxLevel)),t.sendParametersTime.modified()},e.getInternalFormat=(r,n)=>(t._forceInternalFormat||(t.internalFormat=e.getDefaultInternalFormat(r,n)),t.internalFormat||bd(`Unable to find suitable internal format for T=${r} NC= ${n}`),[t.context.R32F,t.context.RG32F,t.context.RGB32F,t.context.RGBA32F].includes(t.internalFormat)&&!t.context.getExtension("OES_texture_float_linear")&&_d("Failed to load OES_texture_float_linear. Texture filtering is not available for *32F internal formats."),t.internalFormat),e.getDefaultInternalFormat=(r,o)=>{let i=0;return i=t._openGLRenderWindow.getDefaultTextureInternalFormat(r,o,n(),e.useHalfFloat()),i||(i||(bd("Unsupported internal texture type!"),bd(`Unable to find suitable internal format for T=${r} NC= ${o}`)),i)},e.useHalfFloat=()=>t.enableUseHalfFloat&&t.canUseHalfFloat,e.setInternalFormat=r=>{t._forceInternalFormat=!0,r!==t.internalFormat&&(t.internalFormat=r,e.modified())},e.getFormat=(r,n)=>(t.format=e.getDefaultFormat(r,n),t.format),e.getDefaultFormat=(e,r)=>{if(t._openGLRenderWindow.getWebgl2())switch(r){case 1:return t.context.RED;case 2:return t.context.RG;case 3:default:return t.context.RGB;case 4:return t.context.RGBA}else switch(r){case 1:return t.context.LUMINANCE;case 2:return t.context.LUMINANCE_ALPHA;case 3:default:return t.context.RGB;case 4:return t.context.RGBA}},e.resetFormatAndType=()=>{t._prevTexParams=null,t.format=0,t.internalFormat=0,t._forceInternalFormat=!1,t.openGLDataType=0},e.getDefaultDataType=r=>{const o=e.useHalfFloat();if(t._openGLRenderWindow.getWebgl2())switch(r){case vd.UNSIGNED_CHAR:return t.context.UNSIGNED_BYTE;case n()&&!o&&vd.SHORT:return t.context.SHORT;case n()&&!o&&vd.UNSIGNED_SHORT:return t.context.UNSIGNED_SHORT;case o&&vd.SHORT:case o&&vd.UNSIGNED_SHORT:return t.context.HALF_FLOAT;case vd.FLOAT:case vd.VOID:default:return t.context.FLOAT}switch(r){case vd.UNSIGNED_CHAR:return t.context.UNSIGNED_BYTE;case vd.FLOAT:case vd.VOID:default:if(t.context.getExtension("OES_texture_float")&&t.context.getExtension("OES_texture_float_linear"))return t.context.FLOAT;{const e=t.context.getExtension("OES_texture_half_float");if(e&&t.context.getExtension("OES_texture_half_float_linear"))return e.HALF_FLOAT_OES}return t.context.UNSIGNED_BYTE}},e.getOpenGLDataType=function(r){let n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return t.openGLDataType&&!n||(t.openGLDataType=e.getDefaultDataType(r)),t.openGLDataType},e.getShiftAndScale=()=>{let e=0,r=1;switch(t.openGLDataType){case t.context.BYTE:r=127.5,e=r-128;break;case t.context.UNSIGNED_BYTE:r=255,e=0;break;case t.context.SHORT:r=32767.5,e=r-32768;break;case t.context.UNSIGNED_SHORT:r=65536,e=0;break;case t.context.INT:r=2147483647.5,e=r-2147483648;break;case t.context.UNSIGNED_INT:r=4294967295,e=0;case t.context.FLOAT:}return{shift:e,scale:r}},e.getOpenGLFilterMode=e=>{switch(e){case yd.NEAREST:return t.context.NEAREST;case yd.LINEAR:return t.context.LINEAR;case yd.NEAREST_MIPMAP_NEAREST:return t.context.NEAREST_MIPMAP_NEAREST;case yd.NEAREST_MIPMAP_LINEAR:return t.context.NEAREST_MIPMAP_LINEAR;case yd.LINEAR_MIPMAP_NEAREST:return t.context.LINEAR_MIPMAP_NEAREST;case yd.LINEAR_MIPMAP_LINEAR:return t.context.LINEAR_MIPMAP_LINEAR;default:return t.context.NEAREST}},e.getOpenGLWrapMode=e=>{switch(e){case gd.CLAMP_TO_EDGE:return t.context.CLAMP_TO_EDGE;case gd.REPEAT:return t.context.REPEAT;case gd.MIRRORED_REPEAT:return t.context.MIRRORED_REPEAT;default:return t.context.CLAMP_TO_EDGE}},e.updateArrayDataTypeForGL=function(e,r){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[];const i=[];let s=t.width*t.height*t.components;n&&(s*=t.depth);const l=!!o.length;if(e!==vd.FLOAT&&t.openGLDataType===t.context.FLOAT)for(let e=0;es?r[e].subarray(0,s):r[e];i.push(new Float32Array(t))}else i.push(null);if(e!==vd.UNSIGNED_CHAR&&t.openGLDataType===t.context.UNSIGNED_BYTE)for(let e=0;es?r[e].subarray(0,s):r[e];i.push(new Uint8Array(t))}else i.push(null);let u=!1;if(t._openGLRenderWindow.getWebgl2())u=t.openGLDataType===t.context.HALF_FLOAT;else{const e=t.context.getExtension("OES_texture_half_float");u=e&&t.openGLDataType===e.HALF_FLOAT_OES}if(u)for(let e=0;e0&&void 0!==arguments[0]?arguments[0]:{};if(e.getOpenGLDataType(a,!0),e.getInternalFormat(a,i),e.getFormat(a,i),!t.internalFormat||!t.format||!t.openGLDataType)return xd("Failed to determine texture parameters."),!1;t.target=t.context.TEXTURE_2D,t.components=i,t.width=r,t.height=o,t.depth=1,t.numberOfDimensions=2,t._openGLRenderWindow.activateTexture(e),e.createTexture(),e.bind();const d=[u],p=s(e.updateArrayDataTypeForGL(a,d));return t.context.pixelStorei(t.context.UNPACK_FLIP_Y_WEBGL,c),t.context.pixelStorei(t.context.UNPACK_ALIGNMENT,1),l(a)?(t.context.texStorage2D(t.target,1,t.internalFormat,t.width,t.height),null!=p[0]&&t.context.texSubImage2D(t.target,0,0,0,t.width,t.height,t.format,t.openGLDataType,p[0])):t.context.texImage2D(t.target,0,t.internalFormat,t.width,t.height,0,t.format,t.openGLDataType,p[0]),t.generateMipmap&&t.context.generateMipmap(t.target),c&&t.context.pixelStorei(t.context.UNPACK_FLIP_Y_WEBGL,!1),t.allocatedGPUMemoryInBytes=t.width*t.height*t.depth*i*t._openGLRenderWindow.getDefaultTextureByteSize(a,n(),e.useHalfFloat()),e.deactivate(),!0},e.createCubeFromRaw=function(){let{width:r=Sd("width"),height:o=Sd("height"),numComps:i=Sd("numComps"),dataType:a=Sd("dataType"),data:u=Sd("data")}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(e.getOpenGLDataType(a),e.getInternalFormat(a,i),e.getFormat(a,i),!t.internalFormat||!t.format||!t.openGLDataType)return xd("Failed to determine texture parameters."),!1;t.target=t.context.TEXTURE_CUBE_MAP,t.components=i,t.width=r,t.height=o,t.depth=1,t.numberOfDimensions=2,t._openGLRenderWindow.activateTexture(e),t.maxLevel=u.length/6-1,e.createTexture(),e.bind();const c=s(e.updateArrayDataTypeForGL(a,u)),d=[];let p=t.width,f=t.height;for(let e=0;e=1&&o>=1;){let i=null;r<=t.maxLevel&&(i=d[6*r+e]),l(a)?null!=i&&t.context.texSubImage2D(t.context.TEXTURE_CUBE_MAP_POSITIVE_X+e,r,0,0,n,o,t.format,t.openGLDataType,i):t.context.texImage2D(t.context.TEXTURE_CUBE_MAP_POSITIVE_X+e,r,t.internalFormat,n,o,0,t.format,t.openGLDataType,i),r++,n/=2,o/=2}}return t.allocatedGPUMemoryInBytes=t.width*t.height*t.depth*i*t._openGLRenderWindow.getDefaultTextureByteSize(a,n(),e.useHalfFloat()),e.deactivate(),!0},e.createDepthFromRaw=function(){let{width:r=Sd("width"),height:o=Sd("height"),dataType:i=Sd("dataType"),data:a=Sd("data")}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return e.getOpenGLDataType(i),t.format=t.context.DEPTH_COMPONENT,t._openGLRenderWindow.getWebgl2()?i===vd.FLOAT?t.internalFormat=t.context.DEPTH_COMPONENT32F:t.internalFormat=t.context.DEPTH_COMPONENT16:t.internalFormat=t.context.DEPTH_COMPONENT,t.internalFormat&&t.format&&t.openGLDataType?(t.target=t.context.TEXTURE_2D,t.components=1,t.width=r,t.height=o,t.depth=1,t.numberOfDimensions=2,t._openGLRenderWindow.activateTexture(e),e.createTexture(),e.bind(),t.context.pixelStorei(t.context.UNPACK_ALIGNMENT,1),l(i)?(t.context.texStorage2D(t.target,1,t.internalFormat,t.width,t.height),null!=a&&t.context.texSubImage2D(t.target,0,0,0,t.width,t.height,t.format,t.openGLDataType,a)):t.context.texImage2D(t.target,0,t.internalFormat,t.width,t.height,0,t.format,t.openGLDataType,a),t.generateMipmap&&t.context.generateMipmap(t.target),t.allocatedGPUMemoryInBytes=t.width*t.height*t.depth*t.components*t._openGLRenderWindow.getDefaultTextureByteSize(i,n(),e.useHalfFloat()),e.deactivate(),!0):(xd("Failed to determine texture parameters."),!1)},e.create2DFromImage=r=>{if(e.getOpenGLDataType(vd.UNSIGNED_CHAR),e.getInternalFormat(vd.UNSIGNED_CHAR,4),e.getFormat(vd.UNSIGNED_CHAR,4),!t.internalFormat||!t.format||!t.openGLDataType)return xd("Failed to determine texture parameters."),!1;t.target=t.context.TEXTURE_2D,t.components=4,t.depth=1,t.numberOfDimensions=2,t._openGLRenderWindow.activateTexture(e),e.createTexture(),e.bind();const o=!(t._openGLRenderWindow.getWebgl2()||Eo(r.width)&&Eo(r.height));let i=r,a=r.width,s=r.height,u=!0;const c=window.chrome;if(o||c){const e=new OffscreenCanvas(Ao(r.width),Ao(r.height));a=e.width,s=e.height;const t=e.getContext("2d");t.translate(0,e.height),t.scale(1,-1),t.drawImage(r,0,0,r.width,r.height,0,0,e.width,e.height),i=e,u=!1}return t.width=a,t.height=s,t.context.pixelStorei(t.context.UNPACK_FLIP_Y_WEBGL,u),t.context.pixelStorei(t.context.UNPACK_ALIGNMENT,1),l(vd.UNSIGNED_CHAR)?(t.context.texStorage2D(t.target,1,t.internalFormat,t.width,t.height),t.context.texSubImage2D(t.target,0,0,0,t.width,t.height,t.format,t.openGLDataType,i)):t.context.texImage2D(t.target,0,t.internalFormat,t.width,t.height,0,t.format,t.openGLDataType,i),t.generateMipmap&&t.context.generateMipmap(t.target),t.allocatedGPUMemoryInBytes=t.width*t.height*t.depth*t.components*t._openGLRenderWindow.getDefaultTextureByteSize(vd.UNSIGNED_CHAR,n(),e.useHalfFloat()),e.deactivate(),!0},e.create2DFromImageBitmap=r=>(e.getOpenGLDataType(vd.UNSIGNED_CHAR),e.getInternalFormat(vd.UNSIGNED_CHAR,4),e.getFormat(vd.UNSIGNED_CHAR,4),t.internalFormat&&t.format&&t.openGLDataType?(t.target=t.context.TEXTURE_2D,t.components=4,t.depth=1,t.numberOfDimensions=2,t._openGLRenderWindow.activateTexture(e),e.createTexture(),e.bind(),t.context.pixelStorei(t.context.UNPACK_ALIGNMENT,1),t.width=r.width,t.height=r.height,l(vd.UNSIGNED_CHAR)?(t.context.texStorage2D(t.target,1,t.internalFormat,t.width,t.height),t.context.texSubImage2D(t.target,0,0,0,t.width,t.height,t.format,t.openGLDataType,r)):t.context.texImage2D(t.target,0,t.internalFormat,t.width,t.height,0,t.format,t.openGLDataType,r),t.generateMipmap&&t.context.generateMipmap(t.target),t.allocatedGPUMemoryInBytes=t.width*t.height*t.depth*t.components*t._openGLRenderWindow.getDefaultTextureByteSize(vd.UNSIGNED_CHAR,n(),e.useHalfFloat()),e.deactivate(),!0):(xd("Failed to determine texture parameters."),!1)),e.create2DFilterableFromRaw=function(){let{width:t=Sd("width"),height:r=Sd("height"),numComps:n=Sd("numComps"),dataType:o=Sd("dataType"),data:i=Sd("data"),preferSizeOverAccuracy:a=!1,ranges:s}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return e.create2DFilterableFromDataArray({width:t,height:r,dataArray:_s.newInstance({numberOfComponents:n,dataType:o,values:i,ranges:s}),preferSizeOverAccuracy:a})},e.create2DFilterableFromDataArray=function(){let{width:t=Sd("width"),height:r=Sd("height"),dataArray:n=Sd("dataArray"),preferSizeOverAccuracy:o=!1}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{numComps:i,dataType:a,data:s}=u(n,o);e.create2DFromRaw({width:t,height:r,numComps:i,dataType:a,data:s})},e.updateVolumeInfoForGL=(r,o)=>{let i=!1;const a=e.useHalfFloat();t.volumeInfo?.scale&&t.volumeInfo?.offset||(t.volumeInfo={scale:new Array(o),offset:new Array(o)});for(let e=0;e0&&void 0!==arguments[0]?arguments[0]:{},m=p,g=f;if(!e.updateVolumeInfoForGL(m,d)&&g){const e=a*u*c,r=structuredClone(t.volumeInfo),n=new Float32Array(e*d);t.volumeInfo.offset=r.offset,t.volumeInfo.scale=r.scale;let o=0;const i=r.scale.map(e=>1/e);for(let t=0;t0,v=!y||!ke(t._prevTexParams,r()),b=[g],x=s(e.updateArrayDataTypeForGL(m,b,!0,v?[]:h));if(t.context.pixelStorei(t.context.UNPACK_ALIGNMENT,1),v)l(m)?(t.context.texStorage3D(t.target,1,t.internalFormat,t.width,t.height,t.depth),null!=x[0]&&t.context.texSubImage3D(t.target,0,0,0,0,t.width,t.height,t.depth,t.format,t.openGLDataType,x[0])):t.context.texImage3D(t.target,0,t.internalFormat,t.width,t.height,t.depth,0,t.format,t.openGLDataType,x[0]),t._prevTexParams=r();else if(y){const e=x[0];let r=0;for(let n=0;n0&&void 0!==arguments[0]?arguments[0]:{};return e.create3DFilterableFromDataArray({width:t,height:r,depth:n,dataArray:_s.newInstance({numberOfComponents:o,dataType:i,values:a,ranges:l}),preferSizeOverAccuracy:s,updatedExtents:u})},e.create3DFilterableFromDataArray=function(){let{width:r=Sd("width"),height:n=Sd("height"),depth:o=Sd("depth"),dataArray:i=Sd("dataArray"),preferSizeOverAccuracy:a=!1,updatedExtents:s=[]}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{numComps:c,dataType:d,data:p,scaleOffsets:f}=u(i,a),h=[],m=[];for(let e=0;e{e[t]=r},b=vd.UNSIGNED_CHAR;if(d===vd.UNSIGNED_CHAR)for(let e=0;e{e[t]=(r-n)/o}):(b=vd.UNSIGNED_CHAR,v=(e,t,r,n,o)=>{e[t]=255*(r-n)/o});if(e.getOpenGLDataType(b),e.getInternalFormat(b,c),e.getFormat(b,c),!t.internalFormat||!t.format||!t.openGLDataType)return xd("Failed to determine texture parameters."),!1;t.target=t.context.TEXTURE_2D,t.components=c,t.depth=1,t.numberOfDimensions=2;let x=t.context.getParameter(t.context.MAX_TEXTURE_SIZE);x>4096&&(b===vd.FLOAT||c>=3)&&(x=4096);let _=1,S=1;g>x*x&&(_=Math.ceil(Math.sqrt(g/(x*x))),S=_);let C=Math.sqrt(g)/_;C=Ao(C);const T=Math.floor(C*_/r),w=Math.ceil(o/T),A=Ao(n*w/S);let E;t.width=C,t.height=A,t._openGLRenderWindow.activateTexture(e),e.createTexture(),e.bind(),t.volumeInfo.xreps=T,t.volumeInfo.yreps=w,t.volumeInfo.xstride=_,t.volumeInfo.ystride=S,t.volumeInfo.offset=y.offset,t.volumeInfo.scale=y.scale;const D=C*A*c;E=b===vd.FLOAT?new Float32Array(D):new Uint8Array(D);let P=0;const I=Math.floor(r/_),O=Math.floor(n/S);for(let e=0;e{t._openGLRenderWindow!==r&&(e.releaseGraphicsResources(),t._openGLRenderWindow=r,t.context=null,r&&(t.context=t._openGLRenderWindow.getContext()))},e.getMaximumTextureSize=e=>e&&e.isCurrent()?e.getIntegerv(e.MAX_TEXTURE_SIZE):-1,e.enableUseHalfFloat=e=>{t.enableUseHalfFloat=e}}const wd={_openGLRenderWindow:null,_forceInternalFormat:!1,_prevTexParams:null,context:null,handle:0,sendParametersTime:null,textureBuildTime:null,numberOfDimensions:0,target:0,format:0,openGLDataType:0,components:0,width:0,height:0,depth:0,autoParameters:!0,wrapS:gd.CLAMP_TO_EDGE,wrapT:gd.CLAMP_TO_EDGE,wrapR:gd.CLAMP_TO_EDGE,minificationFilter:yd.NEAREST,magnificationFilter:yd.NEAREST,minLOD:-1e3,maxLOD:1e3,baseLevel:0,maxLevel:1e3,generateMipmap:!1,oglNorm16Ext:null,allocatedGPUMemoryInBytes:0,enableUseHalfFloat:!0,canUseHalfFloat:!1};function Ad(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,wd,r),Xt.extend(e,t,r),t.sendParametersTime={},mt(t.sendParametersTime,{mtime:0}),t.textureBuildTime={},mt(t.textureBuildTime,{mtime:0}),xt(e,t,["format","openGLDataType"]),_t(e,t,["keyMatrixTime","minificationFilter","magnificationFilter","wrapS","wrapT","wrapR","generateMipmap","oglNorm16Ext"]),yt(e,t,["width","height","volumeInfo","components","handle","target","allocatedGPUMemoryInBytes"]),wt(0,t,["openGLRenderWindow"]),Td(e,t)}const Ed=Pt(Ad,"vtkOpenGLTexture");var Dd={newInstance:Ed,extend:Ad,...dd};Qt("vtkTexture",Ed);var Pd=function(e,t){e.replaceShaderCoincidentOffset=(r,n,o)=>{const i=e.getCoincidentParameters(n,o);if(i&&(0!==i.factor||0!==i.offset)){let e=r.Fragment;e=rd.substitute(e,"//VTK::Coincident::Dec",["uniform float cfactor;","uniform float coffset;"]).result,t.context.getExtension("EXT_frag_depth")&&(0!==i.factor?(e=rd.substitute(e,"//VTK::UniformFlow::Impl",["float cscale = length(vec2(dFdx(gl_FragCoord.z),dFdy(gl_FragCoord.z)));","//VTK::UniformFlow::Impl"],!1).result,e=rd.substitute(e,"//VTK::Depth::Impl","gl_FragDepthEXT = gl_FragCoord.z + cfactor*cscale + 0.000016*coffset;").result):e=rd.substitute(e,"//VTK::Depth::Impl","gl_FragDepthEXT = gl_FragCoord.z + 0.000016*coffset;").result),t._openGLRenderWindow.getWebgl2()&&(0!==i.factor?(e=rd.substitute(e,"//VTK::UniformFlow::Impl",["float cscale = length(vec2(dFdx(gl_FragCoord.z),dFdy(gl_FragCoord.z)));","//VTK::UniformFlow::Impl"],!1).result,e=rd.substitute(e,"//VTK::Depth::Impl","gl_FragDepth = gl_FragCoord.z + cfactor*cscale + 0.000016*coffset;").result):e=rd.substitute(e,"//VTK::Depth::Impl","gl_FragDepth = gl_FragCoord.z + 0.000016*coffset;").result),r.Fragment=e}}},Id=function(e,t){e.applyShaderReplacements=(e,t,r)=>{let n=null;if(t&&(n=t.ShaderReplacements),n)for(let t=0;t{e.getReplacedShaderTemplate(r,n,o),t.lastRenderPassShaderReplacement=t.currentRenderPass?t.currentRenderPass.getShaderReplacement():null,t.lastRenderPassShaderReplacement&&t.lastRenderPassShaderReplacement(r);const i=t.renderable.getViewSpecificProperties().OpenGL;e.applyShaderReplacements(r,i,!0),e.replaceShaderValues(r,n,o),e.applyShaderReplacements(r,i)},e.getReplacedShaderTemplate=(r,n,o)=>{const i=t.renderable.getViewSpecificProperties().OpenGL;e.getShaderTemplate(r,n,o);let a=r.Vertex;if(i){const e=i.VertexShaderCode;void 0!==e&&""!==e&&(a=e)}r.Vertex=a;let s=r.Fragment;if(i){const e=i.FragmentShaderCode;void 0!==e&&""!==e&&(s=e)}r.Fragment=s;let l=r.Geometry;if(i){const e=i.GeometryShaderCode;void 0!==e&&(l=e)}r.Geometry=l}};const{FieldAssociations:Od}=Gs,{primTypes:Nd}=ud,{Representation:Md,Shading:Rd}=os,{ScalarMode:Fd}=Gl,{Filter:Bd,Wrap:Ld}=Dd,{vtkErrorMacro:kd}=jt,Ud={type:"StartEvent"},Vd={type:"EndEvent"},{CoordinateSystem:Gd}=Ka;const zd={context:null,VBOBuildTime:0,VBOBuildString:null,primitives:null,primTypes:null,shaderRebuildString:null,tmpMat4:null,ambientColor:[],diffuseColor:[],specularColor:[],lightColor:[],lightDirection:[],lastHaveSeenDepthRequest:!1,haveSeenDepthRequest:!1,lastSelectionState:Tl.MIN_KNOWN_PASS-1,selectionStateChanged:null,selectionWebGLIdsToVTKIds:null,pointPicking:!1};const jd=Pt(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,zd,r),Xt.extend(e,t,r),Pd(e,t,r),Id(e,t,r),t.primitives=[],t.primTypes=Nd,t.tmpMat3=pe(new Float64Array(9)),t.tmpMat4=h(new Float64Array(16));for(let e=Nd.Start;e0===n?r?t.copy(e,r):t.identity(e):r?t.multiply(e,e,r):e,r)}t.classHierarchy.push("vtkOpenGLPolyDataMapper"),e.buildPass=r=>{r&&(t.currentRenderPass=null,t.openGLActor=e.getFirstAncestorOfType("vtkOpenGLActor"),t._openGLRenderer=t.openGLActor.getFirstAncestorOfType("vtkOpenGLRenderer"),t._openGLRenderWindow=t._openGLRenderer.getLastAncestorOfType("vtkOpenGLRenderWindow"),t.openGLCamera=t._openGLRenderer.getViewNodeFor(t._openGLRenderer.getRenderable().getActiveCamera(),t.openGLCamera))},e.translucentPass=(r,n)=>{r&&(t.currentRenderPass=n,e.render())},e.zBufferPass=r=>{r&&(t.haveSeenDepthRequest=!0,t.renderDepth=!0,e.render(),t.renderDepth=!1)},e.opaqueZBufferPass=t=>e.zBufferPass(t),e.opaquePass=t=>{t&&e.render()},e.render=()=>{const r=t._openGLRenderWindow.getContext();if(t.context!==r){t.context=r;for(let e=Nd.Start;e{e.Vertex="//VTK::System::Dec\n\n/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkPolyDataVS.glsl\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*/\n\nattribute vec4 vertexMC;\n\n// frag position in VC\n//VTK::PositionVC::Dec\n\n// optional normal declaration\n//VTK::Normal::Dec\n\n// extra lighting parameters\n//VTK::Light::Dec\n\n// Texture coordinates\n//VTK::TCoord::Dec\n\n// material property values\n//VTK::Color::Dec\n\n// clipping plane vars\n//VTK::Clip::Dec\n\n// camera and actor matrix values\n//VTK::Camera::Dec\n\n// Apple Bug\n//VTK::PrimID::Dec\n\n// picking support\n//VTK::Picking::Dec\n\nvoid main()\n{\n //VTK::Color::Impl\n\n //VTK::Normal::Impl\n\n //VTK::TCoord::Impl\n\n //VTK::Clip::Impl\n\n //VTK::PrimID::Impl\n\n //VTK::PositionVC::Impl\n\n //VTK::Light::Impl\n\n //VTK::Picking::Impl\n}\n",e.Fragment="//VTK::System::Dec\n\n/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkPolyDataFS.glsl\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*/\n// Template for the polydata mappers fragment shader\n\nuniform int PrimitiveIDOffset;\n\n// VC position of this fragment\n//VTK::PositionVC::Dec\n\n// optional color passed in from the vertex shader, vertexColor\n//VTK::Color::Dec\n\n// optional surface normal declaration\n//VTK::Normal::Dec\n\n// extra lighting parameters\n//VTK::Light::Dec\n\n// define vtkImageLabelOutlineOn\n//VTK::ImageLabelOutlineOn\n\n// Texture coordinates\n//VTK::TCoord::Dec\n\n// picking support\n//VTK::Picking::Dec\n\n// Depth Peeling Support\n//VTK::DepthPeeling::Dec\n\n// clipping plane vars\n//VTK::Clip::Dec\n\n// label outline \n//VTK::LabelOutline::Dec\n\n// the output of this shader\n//VTK::Output::Dec\n\n// Apple Bug\n//VTK::PrimID::Dec\n\n// handle coincident offsets\n//VTK::Coincident::Dec\n\n//VTK::ZBuffer::Dec\n\n//VTK::LabelOutlineHelperFunction\n\nvoid main()\n{\n // VC position of this fragment. This should not branch/return/discard.\n //VTK::PositionVC::Impl\n\n // Place any calls that require uniform flow (e.g. dFdx) here.\n //VTK::UniformFlow::Impl\n\n // Set gl_FragDepth here (gl_FragCoord.z by default)\n //VTK::Depth::Impl\n\n // Early depth peeling abort:\n //VTK::DepthPeeling::PreColor\n\n // Apple Bug\n //VTK::PrimID::Impl\n\n //VTK::Clip::Impl\n\n //VTK::Color::Impl\n\n // Generate the normal if we are not passed in one\n //VTK::Normal::Impl\n\n //VTK::TCoord::Impl\n\n //VTK::Light::Impl\n\n if (gl_FragData[0].a <= 0.0)\n {\n discard;\n }\n\n //VTK::DepthPeeling::Impl\n\n //VTK::Picking::Impl\n\n // handle coincident offsets\n //VTK::Coincident::Impl\n\n //VTK::ZBuffer::Impl\n\n //VTK::RenderPassFragmentShader::Impl\n}\n",e.Geometry=""},e.replaceShaderColor=(e,r,n)=>{let o=e.Vertex,i=e.Geometry,a=e.Fragment;const s=t.lastBoundBO.getReferenceByName("lastLightComplexity");let l=["uniform float ambient;","uniform float diffuse;","uniform float specular;","uniform float opacityUniform; // the fragment opacity","uniform vec3 ambientColorUniform;","uniform vec3 diffuseColorUniform;"];s&&(l=l.concat(["uniform vec3 specularColorUniform;","uniform float specularPowerUniform;"]));let u=["vec3 ambientColor;"," vec3 diffuseColor;"," float opacity;"];s&&(u=u.concat([" vec3 specularColor;"," float specularPower;"])),u=u.concat([" ambientColor = ambientColorUniform;"," diffuseColor = diffuseColorUniform;"," opacity = opacityUniform;"]),s&&(u=u.concat([" specularColor = specularColorUniform;"," specularPower = specularPowerUniform;"])),0===t.lastBoundBO.getCABO().getColorComponents()||t.drawingEdges||(l=l.concat(["varying vec4 vertexColorVSOutput;"]),o=rd.substitute(o,"//VTK::Color::Dec",["attribute vec4 scalarColor;","varying vec4 vertexColorVSOutput;"]).result,o=rd.substitute(o,"//VTK::Color::Impl",["vertexColorVSOutput = scalarColor;"]).result,i=rd.substitute(i,"//VTK::Color::Dec",["in vec4 vertexColorVSOutput[];","out vec4 vertexColorGSOutput;"]).result,i=rd.substitute(i,"//VTK::Color::Impl",["vertexColorGSOutput = vertexColorVSOutput[i];"]).result),0===t.lastBoundBO.getCABO().getColorComponents()||t.drawingEdges?(t.renderable.getAreScalarsMappedFromCells()||t.renderable.getInterpolateScalarsBeforeMapping())&&t.renderable.getColorCoordinates()&&!t.drawingEdges?a=rd.substitute(a,"//VTK::Color::Impl",u.concat([" vec4 texColor = texture2D(texture1, tcoordVCVSOutput.st);"," diffuseColor = texColor.rgb;"," ambientColor = texColor.rgb;"," opacity = opacity*texColor.a;"])).result:(n.getBackfaceProperty()&&!t.drawingEdges&&(l=l.concat(["uniform float opacityUniformBF; // the fragment opacity","uniform float ambientIntensityBF; // the material ambient","uniform float diffuseIntensityBF; // the material diffuse","uniform vec3 ambientColorUniformBF; // ambient material color","uniform vec3 diffuseColorUniformBF; // diffuse material color"]),s?(l=l.concat(["uniform float specularIntensityBF; // the material specular intensity","uniform vec3 specularColorUniformBF; // intensity weighted color","uniform float specularPowerUniformBF;"]),u=u.concat(["if (gl_FrontFacing == false) {"," ambientColor = ambientIntensityBF * ambientColorUniformBF;"," diffuseColor = diffuseIntensityBF * diffuseColorUniformBF;"," specularColor = specularIntensityBF * specularColorUniformBF;"," specularPower = specularPowerUniformBF;"," opacity = opacityUniformBF; }"])):u=u.concat(["if (gl_FrontFacing == false) {"," ambientColor = ambientIntensityBF * ambientColorUniformBF;"," diffuseColor = diffuseIntensityBF * diffuseColorUniformBF;"," opacity = opacityUniformBF; }"])),t.haveCellScalars&&!t.drawingEdges&&(l=l.concat(["uniform samplerBuffer texture1;"])),a=rd.substitute(a,"//VTK::Color::Impl",u).result):a=rd.substitute(a,"//VTK::Color::Impl",u.concat([" diffuseColor = vertexColorVSOutput.rgb;"," ambientColor = vertexColorVSOutput.rgb;"," opacity = opacity*vertexColorVSOutput.a;"])).result,a=rd.substitute(a,"//VTK::Color::Dec",l).result,e.Vertex=o,e.Geometry=i,e.Fragment=a},e.replaceShaderLight=(e,r,n)=>{let o=e.Fragment;const i=t.lastBoundBO.getReferenceByName("lastLightComplexity"),a=t.lastBoundBO.getReferenceByName("lastLightCount");let s=[];switch(i){case 0:o=rd.substitute(o,"//VTK::Light::Impl",[" gl_FragData[0] = vec4(ambientColor * ambient + diffuseColor * diffuse, opacity);"," //VTK::Light::Impl"],!1).result;break;case 1:o=rd.substitute(o,"//VTK::Light::Impl",[" float df = max(0.0, normalVCVSOutput.z);"," float sf = pow(df, specularPower);"," vec3 diffuseL = df * diffuseColor;"," vec3 specularL = sf * specularColor;"," gl_FragData[0] = vec4(ambientColor * ambient + diffuseL * diffuse + specularL * specular, opacity);"," //VTK::Light::Impl"],!1).result;break;case 2:for(let e=0;e= cos(radians(lightConeAngle${e})))`," {",` attenuation = attenuation * pow(coneDot, lightExponent${e});`," }"," else"," {"," attenuation = 0.0;"," }"," }"," }"," df = max(0.0, attenuation*dot(normalVCVSOutput, -vertLightDirectionVC));",` diffuseL += ((df) * lightColor${e});`," if (dot(normalVCVSOutput, vertLightDirectionVC) < 0.0)"," {",` float sf = sign(df)*attenuation*pow(max(1e-5,\n dot(reflect(lightDirectionVC${e},\n normalVCVSOutput),\n normalize(-vertexVC.xyz))),\n specularPower);`,` specularL += ((sf) * lightColor${e});`," }"]);s=s.concat([" diffuseL = diffuseL * diffuseColor;"," specularL = specularL * specularColor;"," gl_FragData[0] = vec4(ambientColor * ambient + diffuseL * diffuse + specularL * specular, opacity);"," //VTK::Light::Impl"]),o=rd.substitute(o,"//VTK::Light::Impl",s,!1).result;break;default:kd("bad light complexity")}e.Fragment=o},e.replaceShaderNormal=(e,r,n)=>{if(t.lastBoundBO.getReferenceByName("lastLightComplexity")>0){let r=e.Vertex,o=e.Geometry,i=e.Fragment;t.lastBoundBO.getCABO().getNormalOffset()?(r=rd.substitute(r,"//VTK::Normal::Dec",["attribute vec3 normalMC;","uniform mat3 normalMatrix;","varying vec3 normalVCVSOutput;"]).result,r=rd.substitute(r,"//VTK::Normal::Impl",["normalVCVSOutput = normalMatrix * normalMC;"]).result,o=rd.substitute(o,"//VTK::Normal::Dec",["in vec3 normalVCVSOutput[];","out vec3 normalVCGSOutput;"]).result,o=rd.substitute(o,"//VTK::Normal::Impl",["normalVCGSOutput = normalVCVSOutput[i];"]).result,i=rd.substitute(i,"//VTK::Normal::Dec",["varying vec3 normalVCVSOutput;"]).result,i=rd.substitute(i,"//VTK::Normal::Impl",["vec3 normalVCVSOutput = normalize(normalVCVSOutput);"," if (gl_FrontFacing == false) { normalVCVSOutput = -normalVCVSOutput; }"]).result):t.haveCellNormals?(i=rd.substitute(i,"//VTK::Normal::Dec",["uniform mat3 normalMatrix;","uniform samplerBuffer textureN;"]).result,i=rd.substitute(i,"//VTK::Normal::Impl",["vec3 normalVCVSOutput = normalize(normalMatrix *"," texelFetchBuffer(textureN, gl_PrimitiveID + PrimitiveIDOffset).xyz);"," if (gl_FrontFacing == false) { normalVCVSOutput = -normalVCVSOutput; }"]).result):t.lastBoundBO.getOpenGLMode(n.getProperty().getRepresentation())===t.context.LINES?(i=rd.substitute(i,"//VTK::UniformFlow::Impl",[" vec3 fdx = dFdx(vertexVC.xyz);"," vec3 fdy = dFdy(vertexVC.xyz);"," //VTK::UniformFlow::Impl"]).result,i=rd.substitute(i,"//VTK::Normal::Impl",["vec3 normalVCVSOutput;"," if (abs(fdx.x) > 0.0)"," { fdx = normalize(fdx); normalVCVSOutput = normalize(cross(vec3(fdx.y, -fdx.x, 0.0), fdx)); }"," else { fdy = normalize(fdy); normalVCVSOutput = normalize(cross(vec3(fdy.y, -fdy.x, 0.0), fdy));}"]).result):(i=rd.substitute(i,"//VTK::Normal::Dec",["uniform int cameraParallel;"]).result,i=rd.substitute(i,"//VTK::UniformFlow::Impl",[" vec3 fdx = dFdx(vertexVC.xyz);"," vec3 fdy = dFdy(vertexVC.xyz);"," //VTK::UniformFlow::Impl"]).result,i=rd.substitute(i,"//VTK::Normal::Impl",[" fdx = normalize(fdx);"," fdy = normalize(fdy);"," vec3 normalVCVSOutput = normalize(cross(fdx,fdy));"," if (cameraParallel == 1 && normalVCVSOutput.z < 0.0) { normalVCVSOutput = -1.0*normalVCVSOutput; }"," if (cameraParallel == 0 && dot(normalVCVSOutput,vertexVC.xyz) > 0.0) { normalVCVSOutput = -1.0*normalVCVSOutput; }"]).result),e.Vertex=r,e.Geometry=o,e.Fragment=i}},e.replaceShaderPositionVC=(e,r,n)=>{t.lastBoundBO.replaceShaderPositionVC(e,r,n);let o=e.Vertex,i=e.Geometry,a=e.Fragment;t.lastBoundBO.getReferenceByName("lastLightComplexity")>0?(o=rd.substitute(o,"//VTK::PositionVC::Dec",["varying vec4 vertexVCVSOutput;"]).result,o=rd.substitute(o,"//VTK::PositionVC::Impl",["vertexVCVSOutput = MCVCMatrix * vertexMC;"," gl_Position = MCPCMatrix * vertexMC;"]).result,o=rd.substitute(o,"//VTK::Camera::Dec",["uniform mat4 MCPCMatrix;","uniform mat4 MCVCMatrix;"]).result,i=rd.substitute(i,"//VTK::PositionVC::Dec",["in vec4 vertexVCVSOutput[];","out vec4 vertexVCGSOutput;"]).result,i=rd.substitute(i,"//VTK::PositionVC::Impl",["vertexVCGSOutput = vertexVCVSOutput[i];"]).result,a=rd.substitute(a,"//VTK::PositionVC::Dec",["varying vec4 vertexVCVSOutput;"]).result,a=rd.substitute(a,"//VTK::PositionVC::Impl",["vec4 vertexVC = vertexVCVSOutput;"]).result):(o=rd.substitute(o,"//VTK::Camera::Dec",["uniform mat4 MCPCMatrix;"]).result,o=rd.substitute(o,"//VTK::PositionVC::Impl",[" gl_Position = MCPCMatrix * vertexMC;"]).result),e.Vertex=o,e.Geometry=i,e.Fragment=a},e.replaceShaderTCoord=(e,r,n)=>{if(t.lastBoundBO.getCABO().getTCoordOffset()){let r=e.Vertex,n=e.Geometry,o=e.Fragment;if(t.drawingEdges)return;r=rd.substitute(r,"//VTK::TCoord::Impl","tcoordVCVSOutput = tcoordMC;").result;const i=t.openGLActor.getActiveTextures();let a=2,s=2;if(i&&i.length>0&&(a=i[0].getComponents(),i[0].getTarget()===t.context.TEXTURE_CUBE_MAP&&(s=3)),t.renderable.getColorTextureMap()&&(a=t.renderable.getColorTextureMap().getPointData().getScalars().getNumberOfComponents(),s=2),2===s){if(r=rd.substitute(r,"//VTK::TCoord::Dec","attribute vec2 tcoordMC; varying vec2 tcoordVCVSOutput;").result,n=rd.substitute(n,"//VTK::TCoord::Dec",["in vec2 tcoordVCVSOutput[];","out vec2 tcoordVCGSOutput;"]).result,n=rd.substitute(n,"//VTK::TCoord::Impl","tcoordVCGSOutput = tcoordVCVSOutput[i];").result,o=rd.substitute(o,"//VTK::TCoord::Dec",["varying vec2 tcoordVCVSOutput;","uniform sampler2D texture1;"]).result,i&&i.length>=1)switch(a){case 1:o=rd.substitute(o,"//VTK::TCoord::Impl",[" vec4 tcolor = texture2D(texture1, tcoordVCVSOutput);"," ambientColor = ambientColor*tcolor.r;"," diffuseColor = diffuseColor*tcolor.r;"]).result;break;case 2:o=rd.substitute(o,"//VTK::TCoord::Impl",[" vec4 tcolor = texture2D(texture1, tcoordVCVSOutput);"," ambientColor = ambientColor*tcolor.r;"," diffuseColor = diffuseColor*tcolor.r;"," opacity = opacity * tcolor.g;"]).result;break;default:o=rd.substitute(o,"//VTK::TCoord::Impl",[" vec4 tcolor = texture2D(texture1, tcoordVCVSOutput);"," ambientColor = ambientColor*tcolor.rgb;"," diffuseColor = diffuseColor*tcolor.rgb;"," opacity = opacity * tcolor.a;"]).result}}else switch(r=rd.substitute(r,"//VTK::TCoord::Dec","attribute vec3 tcoordMC; varying vec3 tcoordVCVSOutput;").result,n=rd.substitute(n,"//VTK::TCoord::Dec",["in vec3 tcoordVCVSOutput[];","out vec3 tcoordVCGSOutput;"]).result,n=rd.substitute(n,"//VTK::TCoord::Impl","tcoordVCGSOutput = tcoordVCVSOutput[i];").result,o=rd.substitute(o,"//VTK::TCoord::Dec",["varying vec3 tcoordVCVSOutput;","uniform samplerCube texture1;"]).result,a){case 1:o=rd.substitute(o,"//VTK::TCoord::Impl",[" vec4 tcolor = textureCube(texture1, tcoordVCVSOutput);"," ambientColor = ambientColor*tcolor.r;"," diffuseColor = diffuseColor*tcolor.r;"]).result;break;case 2:o=rd.substitute(o,"//VTK::TCoord::Impl",[" vec4 tcolor = textureCube(texture1, tcoordVCVSOutput);"," ambientColor = ambientColor*tcolor.r;"," diffuseColor = diffuseColor*tcolor.r;"," opacity = opacity * tcolor.g;"]).result;break;default:o=rd.substitute(o,"//VTK::TCoord::Impl",[" vec4 tcolor = textureCube(texture1, tcoordVCVSOutput);"," ambientColor = ambientColor*tcolor.rgb;"," diffuseColor = diffuseColor*tcolor.rgb;"," opacity = opacity * tcolor.a;"]).result}e.Vertex=r,e.Geometry=n,e.Fragment=o}},e.replaceShaderClip=(e,r,n)=>{let o=e.Vertex,i=e.Fragment;if(t.renderable.getNumberOfClippingPlanes()){const e=t.renderable.getNumberOfClippingPlanes();o=rd.substitute(o,"//VTK::Clip::Dec",["uniform int numClipPlanes;",`uniform vec4 clipPlanes[${e}];`,`varying float clipDistancesVSOutput[${e}];`]).result,o=rd.substitute(o,"//VTK::Clip::Impl",[`for (int planeNum = 0; planeNum < ${e}; planeNum++)`," {"," if (planeNum >= numClipPlanes)"," {"," break;"," }"," clipDistancesVSOutput[planeNum] = dot(clipPlanes[planeNum], vertexMC);"," }"]).result,i=rd.substitute(i,"//VTK::Clip::Dec",["uniform int numClipPlanes;",`varying float clipDistancesVSOutput[${e}];`]).result,i=rd.substitute(i,"//VTK::Clip::Impl",[`for (int planeNum = 0; planeNum < ${e}; planeNum++)`," {"," if (planeNum >= numClipPlanes)"," {"," break;"," }"," if (clipDistancesVSOutput[planeNum] < 0.0) discard;"," }"]).result}e.Vertex=o,e.Fragment=i},e.getCoincidentParameters=(e,r)=>{let n={factor:0,offset:0};const o=r.getProperty();if(t.renderable.getResolveCoincidentTopology()==hl.PolygonOffset||o.getEdgeVisibility()&&o.getRepresentation()===Md.SURFACE){const e=t.lastBoundBO.getPrimitiveType();e===Nd.Points||o.getRepresentation()===Md.POINTS?n=t.renderable.getCoincidentTopologyPointOffsetParameter():e===Nd.Lines||o.getRepresentation()===Md.WIREFRAME?n=t.renderable.getCoincidentTopologyLineOffsetParameters():e!==Nd.Tris&&e!==Nd.TriStrips||(n=t.renderable.getCoincidentTopologyPolygonOffsetParameters()),e!==Nd.TrisEdges&&e!==Nd.TriStripsEdges||(n=t.renderable.getCoincidentTopologyPolygonOffsetParameters(),n.factor/=2,n.offset/=2)}const i=t._openGLRenderer.getSelector();return i&&i.getFieldAssociation()===Od.FIELD_ASSOCIATION_POINTS&&(n.offset-=2),n},e.replaceShaderPicking=(e,r,n)=>{let o=e.Fragment,i=e.Vertex;if(o=rd.substitute(o,"//VTK::Picking::Dec",["uniform int picking;","//VTK::Picking::Dec"]).result,t._openGLRenderer.getSelector()){switch(t.lastSelectionState!==Tl.ID_LOW24&&t.lastSelectionState!==Tl.ID_HIGH24||(i=rd.substitute(i,"//VTK::Picking::Dec",["flat out int vertexIDVSOutput;\n","uniform int VertexIDOffset;\n"]).result,i=rd.substitute(i,"//VTK::Picking::Impl"," vertexIDVSOutput = gl_VertexID + VertexIDOffset;\n").result,o=rd.substitute(o,"//VTK::Picking::Dec","flat in int vertexIDVSOutput;\n").result,o=rd.substitute(o,"//VTK::Picking::Impl",[" int idx = vertexIDVSOutput;","//VTK::Picking::Impl"]).result),t.lastSelectionState){case Tl.ID_LOW24:o=rd.substitute(o,"//VTK::Picking::Impl"," gl_FragData[0] = vec4(float(idx%256)/255.0, float((idx/256)%256)/255.0, float((idx/65536)%256)/255.0, 1.0);").result;break;case Tl.ID_HIGH24:o=rd.substitute(o,"//VTK::Picking::Impl"," gl_FragData[0] = vec4(float((idx/16777216)%256)/255.0, 0.0, 0.0, 1.0);").result;break;default:o=rd.substitute(o,"//VTK::Picking::Dec","uniform vec3 mapperIndex;").result,o=rd.substitute(o,"//VTK::Picking::Impl"," gl_FragData[0] = picking != 0 ? vec4(mapperIndex,1.0) : gl_FragData[0];").result}e.Fragment=o,e.Vertex=i}},e.replaceShaderValues=(r,n,o)=>{if(e.replaceShaderColor(r,n,o),e.replaceShaderNormal(r,n,o),e.replaceShaderLight(r,n,o),e.replaceShaderTCoord(r,n,o),e.replaceShaderPicking(r,n,o),e.replaceShaderClip(r,n,o),e.replaceShaderCoincidentOffset(r,n,o),e.replaceShaderPositionVC(r,n,o),t.haveSeenDepthRequest){let e=r.Fragment;e=rd.substitute(e,"//VTK::ZBuffer::Dec","uniform int depthRequest;").result,e=rd.substitute(e,"//VTK::ZBuffer::Impl",["if (depthRequest == 1) {","float iz = floor(gl_FragCoord.z*65535.0 + 0.1);","float rf = floor(iz/256.0)/255.0;","float gf = mod(iz,256.0)/255.0;","gl_FragData[0] = vec4(rf, gf, 0.0, 1.0); }"]).result,r.Fragment=e}},e.getNeedToRebuildShaders=(e,r,n)=>{let o=0,i=0;const a=e.getPrimitiveType(),s=t.currentInput;let l=!1;const u=s.getPointData().getNormals(),c=s.getCellData().getNormals(),d=n.getProperty().getInterpolation()===Rd.FLAT,p=n.getProperty().getRepresentation(),f=e.getOpenGLMode(p,a);if(f===t.context.TRIANGLES||c&&!u||!d&&u?l=!0:d||f!==t.context.LINES||(l=!0),n.getProperty().getLighting()&&l){o=0;const e=r.getLightsByReference();for(let t=0;t0&&(i++,0===o&&(o=1)),1===o&&(i>1||1!==r.getIntensity()||!r.lightTypeIsHeadLight())&&(o=2),o<3&&r.getPositional()&&(o=3)}}let h=!1;const m=t.lastBoundBO.getReferenceByName("lastLightComplexity"),g=t.lastBoundBO.getReferenceByName("lastLightCount");return m===o&&g===i||(t.lastBoundBO.set({lastLightComplexity:o},!0),t.lastBoundBO.set({lastLightCount:i},!0),h=!0),(!t.currentRenderPass&&t.lastRenderPassShaderReplacement||t.currentRenderPass&&t.currentRenderPass.getShaderReplacement()!==t.lastRenderPassShaderReplacement)&&(h=!0),!!(t.lastHaveSeenDepthRequest!==t.haveSeenDepthRequest||e.getShaderSourceTime().getMTime(){const o=t.renderable.getViewSpecificProperties().ShadersCallbacks;o&&o.forEach(t=>{t.callback(t.userData,e,r,n)})},e.setMapperShaderParameters=(r,n,o)=>{if(r.getProgram().isUniformUsed("PrimitiveIDOffset")&&r.getProgram().setUniformi("PrimitiveIDOffset",t.primitiveIDOffset),r.getProgram().isUniformUsed("VertexIDOffset")&&r.getProgram().setUniformi("VertexIDOffset",t.vertexIDOffset),r.getCABO().getElementCount()&&(t.VBOBuildTime.getMTime()>r.getAttributeUpdateTime().getMTime()||r.getShaderSourceTime().getMTime()>r.getAttributeUpdateTime().getMTime())){const e=t.lastBoundBO.getReferenceByName("lastLightComplexity");r.getProgram().isAttributeUsed("vertexMC")&&(r.getVAO().addAttributeArray(r.getProgram(),r.getCABO(),"vertexMC",r.getCABO().getVertexOffset(),r.getCABO().getStride(),t.context.FLOAT,3,!1)||kd("Error setting vertexMC in shader VAO.")),r.getProgram().isAttributeUsed("normalMC")&&r.getCABO().getNormalOffset()&&e>0?r.getVAO().addAttributeArray(r.getProgram(),r.getCABO(),"normalMC",r.getCABO().getNormalOffset(),r.getCABO().getStride(),t.context.FLOAT,3,!1)||kd("Error setting normalMC in shader VAO."):r.getVAO().removeAttributeArray("normalMC"),t.renderable.getCustomShaderAttributes().forEach((e,n)=>{r.getProgram().isAttributeUsed(`${e}MC`)&&(r.getVAO().addAttributeArray(r.getProgram(),r.getCABO(),`${e}MC`,r.getCABO().getCustomData()[n].offset,r.getCABO().getStride(),t.context.FLOAT,r.getCABO().getCustomData()[n].components,!1)||kd(`Error setting ${e}MC in shader VAO.`))}),r.getProgram().isAttributeUsed("tcoordMC")&&r.getCABO().getTCoordOffset()?r.getVAO().addAttributeArray(r.getProgram(),r.getCABO(),"tcoordMC",r.getCABO().getTCoordOffset(),r.getCABO().getStride(),t.context.FLOAT,r.getCABO().getTCoordComponents(),!1)||kd("Error setting tcoordMC in shader VAO."):r.getVAO().removeAttributeArray("tcoordMC"),r.getProgram().isAttributeUsed("scalarColor")&&r.getCABO().getColorComponents()?r.getVAO().addAttributeArray(r.getProgram(),r.getCABO().getColorBO(),"scalarColor",r.getCABO().getColorOffset(),r.getCABO().getColorBOStride(),t.context.UNSIGNED_BYTE,4,!0)||kd("Error setting scalarColor in shader VAO."):r.getVAO().removeAttributeArray("scalarColor"),r.getAttributeUpdateTime().modified()}if(t.renderable.getNumberOfClippingPlanes()){const e=t.renderable.getNumberOfClippingPlanes(),n=[],i=r.getCABO().getCoordShiftAndScaleEnabled()?r.getCABO().getInverseShiftAndScaleMatrix():null,a=i?d(t.tmpMat4,o.getMatrix()):o.getMatrix();i&&(m(a,a),b(a,a,i),m(a,a));for(let r=0;r{const o=t.lastBoundBO.getReferenceByName("lastLightComplexity");if(o<2)return;const i=e.getProgram();let a=0;const s=r.getLightsByReference();for(let e=0;e0){const e=n.getColorByReference(),o=n.getIntensity();t.lightColor[0]=e[0]*o,t.lightColor[1]=e[1]*o,t.lightColor[2]=e[2]*o;const s=n.getDirection(),l=r.getActiveCamera().getViewMatrix(),u=[...s];n.lightTypeIsSceneLight()&&(u[0]=l[0]*s[0]+l[1]*s[1]+l[2]*s[2],u[1]=l[4]*s[0]+l[5]*s[1]+l[6]*s[2],u[2]=l[8]*s[0]+l[9]*s[1]+l[10]*s[2],Lo(u)),t.lightDirection[0]=u[0],t.lightDirection[1]=u[1],t.lightDirection[2]=u[2],Lo(t.lightDirection),i.setUniform3fArray(`lightColor${a}`,t.lightColor),i.setUniform3fArray(`lightDirectionVC${a}`,t.lightDirection),a++}}if(o<3)return;const l=r.getActiveCamera().getViewMatrix();m(l,l),a=0;for(let e=0;e0){const e=t.getTransformedPosition(),r=new Float64Array(3);Sr(r,e,l),i.setUniform3fArray(`lightAttenuation${a}`,t.getAttenuationValuesByReference()),i.setUniformi(`lightPositional${a}`,t.getPositional()),i.setUniformf(`lightExponent${a}`,t.getExponent()),i.setUniformf(`lightConeAngle${a}`,t.getConeAngle()),i.setUniform3fArray(`lightPositionVC${a}`,[r[0],r[1],r[2]]),a++}}},e.setCameraShaderParameters=(e,i,a)=>{const s=e.getProgram(),l=t.openGLCamera.getKeyMatrices(i),u=i.getActiveCamera(),c=t.openGLCamera.getKeyMatrixTime().getMTime(),d=s.getLastCameraMTime(),p=e.getCABO().getCoordShiftAndScaleEnabled()?e.getCABO().getInverseShiftAndScaleMatrix():null,f=a.getIsIdentity(),m=f?{mcwc:null,normalMatrix:null}:t.openGLActor.getKeyMatrices();if(a.getCoordinateSystem()===Gd.DISPLAY){const e=t._openGLRenderer.getTiledSizeAndOrigin();h(t.tmpMat4),t.tmpMat4[0]=2/e.usize,t.tmpMat4[12]=-1,t.tmpMat4[5]=2/e.vsize,t.tmpMat4[13]=-1,b(t.tmpMat4,t.tmpMat4,p),s.setUniformMatrix("MCPCMatrix",t.tmpMat4)}else s.setUniformMatrix("MCPCMatrix",r([l.wcpc,m.mcwc,p],n,t.tmpMat4));s.isUniformUsed("MCVCMatrix")&&s.setUniformMatrix("MCVCMatrix",r([l.wcvc,m.mcwc,p],n,t.tmpMat4)),s.isUniformUsed("normalMatrix")&&s.setUniformMatrix3x3("normalMatrix",r([l.normalMatrix,m.normalMatrix],o,t.tmpMat3)),d!==c&&(s.isUniformUsed("cameraParallel")&&s.setUniformi("cameraParallel",u.getParallelProjection()),s.setLastCameraMTime(c)),f||s.setLastCameraMTime(0)},e.setPropertyShaderParameters=(e,r,n)=>{const o=e.getProgram();let i=n.getProperty(),a=i.getOpacity(),s=t.drawingEdges?i.getEdgeColorByReference():i.getAmbientColorByReference(),l=t.drawingEdges?i.getEdgeColorByReference():i.getDiffuseColorByReference(),u=t.drawingEdges?1:i.getAmbient(),c=t.drawingEdges?0:i.getDiffuse(),d=t.drawingEdges?0:i.getSpecular();const p=i.getSpecularPower();o.setUniformf("opacityUniform",a),o.setUniform3fArray("ambientColorUniform",s),o.setUniform3fArray("diffuseColorUniform",l),o.setUniformf("ambient",u),o.setUniformf("diffuse",c);const f=t.lastBoundBO.getReferenceByName("lastLightComplexity");if(f<1)return;let h=i.getSpecularColorByReference();if(o.setUniform3fArray("specularColorUniform",h),o.setUniformf("specularPowerUniform",p),o.setUniformf("specular",d),o.isUniformUsed("ambientIntensityBF")){if(i=n.getBackfaceProperty(),a=i.getOpacity(),s=i.getAmbientColor(),u=i.getAmbient(),l=i.getDiffuseColor(),c=i.getDiffuse(),h=i.getSpecularColor(),d=i.getSpecular(),o.setUniformf("ambientIntensityBF",u),o.setUniformf("diffuseIntensityBF",c),o.setUniformf("opacityUniformBF",a),o.setUniform3fArray("ambientColorUniformBF",s),o.setUniform3fArray("diffuseColorUniformBF",l),f<1)return;o.setUniformf("specularIntensityBF",d),o.setUniform3fArray("specularColorUniformBF",h),o.setUniformf("specularPowerUniformBF",p)}},e.updateMaximumPointCellIds=(e,r)=>{const n=t._openGLRenderer.getSelector();if(n){if(t.selectionWebGLIdsToVTKIds?.points?.length){const e=t.selectionWebGLIdsToVTKIds.points.length;n.setMaximumPointId(e-1)}if(t.selectionWebGLIdsToVTKIds?.cells?.length){const e=t.selectionWebGLIdsToVTKIds.cells.length;n.setMaximumCellId(e-1)}n.getFieldAssociation()===Od.FIELD_ASSOCIATION_POINTS&&(t.pointPicking=!0)}},e.renderPieceStart=(r,n)=>{t.primitiveIDOffset=0,t.vertexIDOffset=0;const o=function(e){const t=e.getSelector();return t?t.getCurrentPass():Tl.MIN_KNOWN_PASS-1}(t._openGLRenderer);t.lastSelectionState!==o&&(t.selectionStateChanged.modified(),t.lastSelectionState=o),t._openGLRenderer.getSelector()&&t._openGLRenderer.getSelector().renderProp(n),e.updateBufferObjects(r,n),t.renderable.getColorTextureMap()&&t.internalColorTexture.activate(),t.lastBoundBO=null},e.renderPieceDraw=(r,n)=>{const o=n.getProperty().getRepresentation(),i=n.getProperty().getEdgeVisibility()&&o===Md.SURFACE,a=t._openGLRenderer.getSelector(),s=a&&a.getFieldAssociation()===Od.FIELD_ASSOCIATION_POINTS&&(t.lastSelectionState===Tl.ID_LOW24||t.lastSelectionState===Tl.ID_HIGH24);for(let a=Nd.Start;a=0)||(t.lastBoundBO=t.primitives[a],t.primitiveIDOffset+=t.primitives[a].drawArrays(r,n,o,e),t.vertexIDOffset+=t.primitives[a].getCABO().getElementCount()))},e.renderPieceFinish=(e,r)=>{t.LastBoundBO&&t.LastBoundBO.getVAO().release(),t.renderable.getColorTextureMap()&&t.internalColorTexture.deactivate()},e.renderPiece=(r,n)=>{if(e.invokeEvent(Ud),t.renderable.getStatic()||t.renderable.update(),t.currentInput=t.renderable.getInputData(),e.invokeEvent(Vd),!t.currentInput)return void kd("No input!");if(!t.currentInput.getPoints||!t.currentInput.getPoints().getNumberOfValues())return;const o=t.context,i=n.getProperty().getBackfaceCulling(),a=n.getProperty().getFrontfaceCulling();i||a?a?(t._openGLRenderWindow.enableCullFace(),o.cullFace(o.FRONT)):(t._openGLRenderWindow.enableCullFace(),o.cullFace(o.BACK)):t._openGLRenderWindow.disableCullFace(),e.renderPieceStart(r,n),e.renderPieceDraw(r,n),e.renderPieceFinish(r,n)},e.updateBufferObjects=(t,r)=>{e.getNeedToRebuildBufferObjects(t,r)&&e.buildBufferObjects(t,r),e.updateMaximumPointCellIds()},e.getNeedToRebuildBufferObjects=(r,n)=>{const o=t.VBOBuildTime.getMTime();return o{const n=t.currentInput;if(null===n)return;t.renderable.mapScalars(n,1);const o=t.renderable.getColorMapColors();t.haveCellScalars=!1;const i=t.renderable.getScalarMode();t.renderable.getScalarVisibility()&&(i!==Fd.USE_CELL_DATA&&i!==Fd.USE_CELL_FIELD_DATA&&i!==Fd.USE_FIELD_DATA&&n.getPointData().getScalars()||i===Fd.USE_POINT_FIELD_DATA||!o||(t.haveCellScalars=!0));let a=r.getProperty().getInterpolation()!==Rd.FLAT?n.getPointData().getNormals():null;null===a&&n.getCellData().getNormals()&&(t.haveCellNormals=!0,a=n.getCellData().getNormals());const s=r.getProperty().getRepresentation();let l=n.getPointData().getTCoords();t.openGLActor.getActiveTextures()||(l=null);let u=!1;if(t.renderable.getColorCoordinates()){l=t.renderable.getColorCoordinates(),u=t.renderable.getAreScalarsMappedFromCells(),t.internalColorTexture||(t.internalColorTexture=Dd.newInstance({resizable:!0}));const e=t.internalColorTexture;e.setMinificationFilter(Bd.NEAREST),e.setMagnificationFilter(Bd.NEAREST),e.setWrapS(Ld.CLAMP_TO_EDGE),e.setWrapT(Ld.CLAMP_TO_EDGE),e.setOpenGLRenderWindow(t._openGLRenderWindow);const r=t.renderable.getColorTextureMap(),n=r.getExtent(),o=r.getPointData().getScalars();e.create2DFromRaw({width:n[1]-n[0]+1,height:n[3]-n[2]+1,numComps:o.getNumberOfComponents(),dataType:o.getDataType(),data:o.getData()}),e.activate(),e.sendParameters(),e.deactivate()}const c=t.renderable.getCustomShaderAttributes().map(e=>n.getPointData().getArrayByName(e)),d=`${n.getMTime()}A${s}B${n.getMTime()}C${a?a.getMTime():1}D${o?o.getMTime():1}E${r.getProperty().getEdgeVisibility()}F${l?l.getMTime():1}G${c.map(e=>e.getMTime()).join(",")}`;if(t.VBOBuildString!==d){const e={points:n.getPoints(),normals:a,tcoords:l,colors:o,cellOffset:0,vertexOffset:0,useTCoordsPerCell:u,haveCellScalars:t.haveCellScalars,haveCellNormals:t.haveCellNormals,customAttributes:c};t.renderable.getPopulateSelectionSettings()&&(t.selectionWebGLIdsToVTKIds={points:null,cells:null});const i=[{inRep:"verts",cells:n.getVerts()},{inRep:"lines",cells:n.getLines()},{inRep:"polys",cells:n.getPolys()},{inRep:"strips",cells:n.getStrips()},{inRep:"polys",cells:n.getPolys()},{inRep:"strips",cells:n.getStrips()}],p=r.getProperty().getEdgeVisibility()&&s===Md.SURFACE;for(let r=Nd.Start;r{let e=0;return t.primitives.forEach(t=>{e+=t.getAllocatedGPUMemoryInBytes()}),e}}(e,t)},"vtkOpenGLPolyDataMapper");Qt("vtkMapper",jd);const Wd={BACKGROUND:0,FOREGROUND:1};var Hd={DisplayLocation:Wd};const{primTypes:Kd}=ud,{Filter:Xd,Wrap:$d}=Dd,{vtkErrorMacro:qd}=jt,Yd={type:"StartEvent"},Jd={type:"EndEvent"},Qd={context:null,VBOBuildTime:0,VBOBuildString:null,primitives:null,primTypes:null,shaderRebuildString:null};const Zd=Pt(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Qd,r),Xt.extend(e,t,r),Pd(e,t,r),Id(e,t,r),t.primitives=[],t.primTypes=Kd,t.tmpMat4=h(new Float64Array(16));for(let e=Kd.Start;e{r&&(t.openGLActor2D=e.getFirstAncestorOfType("vtkOpenGLActor2D"),t._openGLRenderer=t.openGLActor2D.getFirstAncestorOfType("vtkOpenGLRenderer"),t._openGLRenderWindow=t._openGLRenderer.getLastAncestorOfType("vtkOpenGLRenderWindow"),t.openGLCamera=t._openGLRenderer.getViewNodeFor(t._openGLRenderer.getRenderable().getActiveCamera(),t.openGLCamera))},e.overlayPass=t=>{t&&e.render()},e.getShaderTemplate=(e,t,r)=>{e.Vertex="//VTK::System::Dec\n\n/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkPolyData2DVS.glsl\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*/\n\n// all variables that represent positions or directions have a suffix\n// indicating the coordinate system they are in. The possible values are\n// MC - Model Coordinates\n// WC - WC world coordinates\n// VC - View Coordinates\n// DC - Display Coordinates\n\nin vec4 vertexWC;\n\n// frag position in VC\n//VTK::PositionVC::Dec\n\n// material property values\n//VTK::Color::Dec\n\n// Texture coordinates\n//VTK::TCoord::Dec\n\n// Apple Bug\n//VTK::PrimID::Dec\n\nuniform mat4 WCVCMatrix; // World to view matrix\n\nvoid main()\n{\n // Apple Bug\n //VTK::PrimID::Impl\n\n gl_Position = WCVCMatrix*vertexWC;\n\n //VTK::TCoord::Impl\n\n //VTK::Color::Impl\n\n //VTK::PositionVC::Impl\n}\n",e.Fragment="//VTK::System::Dec\n\n/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkPolyData2DFS.glsl\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*/\n\nuniform int PrimitiveIDOffset;\n\n// Texture coordinates\n//VTK::TCoord::Dec\n\n// Scalar coloring\n//VTK::Color::Dec\n\n// Depth Peeling\n//VTK::DepthPeeling::Dec\n\n// picking support\n//VTK::Picking::Dec\n\n// the output of this shader\n//VTK::Output::Dec\n\n// Apple Bug\n//VTK::PrimID::Dec\n\nvoid main()\n{\n // Apple Bug\n //VTK::PrimID::Impl\n\n //VTK::Color::Impl\n //VTK::TCoord::Impl\n\n //VTK::DepthPeeling::Impl\n //VTK::Picking::Impl\n\n if (gl_FragData[0].a <= 0.0)\n {\n discard;\n }\n}\n",e.Geometry=""},e.render=()=>{const r=t._openGLRenderWindow.getContext();if(t.context!==r){t.context=r;for(let e=Kd.Start;e{if(e.invokeEvent(Yd),t.renderable.getStatic()||t.renderable.update(),t.currentInput=t.renderable.getInputData(),e.invokeEvent(Jd),!t.currentInput)return void qd("No input!");if(!t.currentInput.getPoints||!t.currentInput.getPoints().getNumberOfValues())return;const o=t.context;t._openGLRenderWindow.enableCullFace(),o.cullFace(o.BACK),e.renderPieceStart(r,n),e.renderPieceDraw(r,n),e.renderPieceFinish(r,n)},e.renderPieceStart=(r,n)=>{t.primitiveIDOffset=0,t._openGLRenderer.getSelector()&&(t._openGLRenderer.getSelector().getCurrentPass(),t._openGLRenderer.getSelector().renderProp(n)),t.renderable.getColorTextureMap()&&t.internalColorTexture.activate(),e.updateBufferObjects(r,n),t.lastBoundBO=null},e.getNeedToRebuildShaders=(e,r,n)=>e.getShaderSourceTime().getMTime(){e.getNeedToRebuildBufferObjects(t,r)&&e.buildBufferObjects(t,r)},e.getNeedToRebuildBufferObjects=(r,n)=>{const o=t.VBOBuildTime.getMTime();return!!(o{const n=t.currentInput;if(null===n)return;t.renderable.mapScalars(n,r.getProperty().getOpacity());const o=t.renderable.getColorMapColors(),i=r.getProperty().getRepresentation();let a=n.getPointData().getTCoords();t.openGLActor2D.getActiveTextures()||(a=null);let s=!1;if(t.renderable.getColorCoordinates()){a=t.renderable.getColorCoordinates(),s=t.renderable.getAreScalarsMappedFromCells(),t.internalColorTexture||(t.internalColorTexture=Dd.newInstance({resizable:!0}));const e=t.internalColorTexture;e.setMinificationFilter(Xd.NEAREST),e.setMagnificationFilter(Xd.NEAREST),e.setWrapS($d.CLAMP_TO_EDGE),e.setWrapT($d.CLAMP_TO_EDGE),e.setOpenGLRenderWindow(t._openGLRenderWindow);const r=t.renderable.getColorTextureMap(),n=r.getExtent(),o=r.getPointData().getScalars();e.create2DFromRaw({width:n[1]-n[0]+1,height:n[3]-n[2]+1,numComps:o.getNumberOfComponents(),dataType:o.getDataType(),data:o.getData()}),e.activate(),e.sendParameters(),e.deactivate()}const l=t.renderable.getTransformCoordinate(),u=e.getRenderWindow().getViews()[0].getViewportSize(e),c=`${n.getMTime()}A${i}B${n.getMTime()}C${o?o.getMTime():1}D${a?a.getMTime():1}E${l?e.getMTime():1}F${u}`;if(t.VBOBuildString!==c){let r=n.getPoints();if(l){const t=Jl.newInstance(),n=r.getNumberOfPoints();t.setNumberOfPoints(n);const o=[];for(let i=0;in.getPointData().getArrayByName(e))};u.cellOffset+=t.primitives[Kd.Points].getCABO().createVBO(n.getVerts(),"verts",i,u),u.cellOffset+=t.primitives[Kd.Lines].getCABO().createVBO(n.getLines(),"lines",i,u),u.cellOffset+=t.primitives[Kd.Tris].getCABO().createVBO(n.getPolys(),"polys",i,u),u.cellOffset+=t.primitives[Kd.TriStrips].getCABO().createVBO(n.getStrips(),"strips",i,u),t.VBOBuildTime.modified(),t.VBOBuildString=c}},e.renderPieceDraw=(r,n)=>{const o=n.getProperty().getRepresentation();t.context.depthMask(!0);for(let i=Kd.Start;i{t.lastBoundBO&&t.lastBoundBO.getVAO().release(),t.renderable.getColorTextureMap()&&t.internalColorTexture.deactivate()},e.replaceShaderValues=(t,r,n)=>{e.replaceShaderColor(t,r,n),e.replaceShaderTCoord(t,r,n),e.replaceShaderPicking(t,r,n),e.replaceShaderPositionVC(t,r,n)},e.replaceShaderColor=(e,r,n)=>{let o=e.Vertex,i=e.Geometry,a=e.Fragment,s=["uniform vec3 diffuseColorUniform;","uniform float opacityUniform;"],l=["vec3 diffuseColor = diffuseColorUniform;","float opacity = opacityUniform;"];0!==t.lastBoundBO.getCABO().getColorComponents()?(s=s.concat(["varying vec4 vertexColorVSOutput;"]),o=rd.substitute(o,"//VTK::Color::Dec",["attribute vec4 scalarColor;","varying vec4 vertexColorVSOutput;"]).result,o=rd.substitute(o,"//VTK::Color::Impl",["vertexColorVSOutput = scalarColor;"]).result,i=rd.substitute(i,"//VTK::Color::Dec",["in vec4 vertexColorVSOutput[];","out vec4 vertexColorGSOutput;"]).result,i=rd.substitute(i,"//VTK::Color::Impl",["vertexColorGSOutput = vertexColorVSOutput[i];"]).result,a=rd.substitute(a,"//VTK::Color::Impl",l.concat([" diffuseColor = vertexColorVSOutput.rgb;"," opacity = opacity*vertexColorVSOutput.a;"])).result):t.renderable.getAreScalarsMappedFromCells()&&(l=l.concat([" vec4 texColor = texture2D(texture1, tcoordVCVSOutput.st);"," diffuseColor = texColor.rgb;"," opacity = opacity*texColor.a;"])),l=l.concat(["gl_FragData[0] = vec4(diffuseColor, opacity);"]),a=rd.substitute(a,"//VTK::Color::Dec",s).result,a=rd.substitute(a,"//VTK::Color::Impl",l).result,e.Vertex=o,e.Geometry=i,e.Fragment=a},e.replaceShaderTCoord=(e,r,n)=>{if(t.lastBoundBO.getCABO().getTCoordOffset()){let r=e.Vertex,n=e.Geometry,o=e.Fragment;const i=t.lastBoundBO.getCABO().getTCoordComponents();1===i?(r=rd.substitute(r,"//VTK::TCoord::Dec",["in float tcoordMC;","out float tcoordVCVSOutput;"]).result,r=rd.substitute(r,"//VTK::TCoord::Impl",["tcoordVCVSOutput = tcoordMC;"]).result,n=rd.substitute(n,"//VTK::TCoord::Dec",["in float tcoordVCVSOutput[];\n","out float tcoordVCGSOutput;"]).result,n=rd.substitute(n,["//VTK::TCoord::Impl","tcoordVCGSOutput = tcoordVCVSOutput[i];"]).result,o=rd.substitute(o,"//VTK::TCoord::Dec",["in float tcoordVCVSOutput;","uniform sampler2D texture1;"]).result,o=rd.substitute(o,"//VTK::TCoord::Impl",["gl_FragData[0] = gl_FragData[0]*texture2D(texture1, vec2(tcoordVCVSOutput,0));"]).result):2===i&&(r=rd.substitute(r,"//VTK::TCoord::Dec",["in vec2 tcoordMC;","out vec2 tcoordVCVSOutput;"]).result,r=rd.substitute(r,"//VTK::TCoord::Impl",["tcoordVCVSOutput = tcoordMC;"]).result,n=rd.substitute(n,"//VTK::TCoord::Dec",["in vec2 tcoordVCVSOutput[];\n","out vec2 tcoordVCGSOutput;"]).result,n=rd.substitute(n,"//VTK::TCoord::Impl",["tcoordVCGSOutput = tcoordVCVSOutput[i];"]).result,o=rd.substitute(o,"//VTK::TCoord::Dec",["in vec2 tcoordVCVSOutput;","uniform sampler2D texture1;"]).result,o=rd.substitute(o,"//VTK::TCoord::Impl",["gl_FragData[0] = gl_FragData[0]*texture2D(texture1, tcoordVCVSOutput.st);"]).result),t.renderable.getAreScalarsMappedFromCells()&&(n=rd.substitute(n,"//VTK::PrimID::Impl",["gl_PrimitiveID = gl_PrimitiveIDIn;"]).result),e.Vertex=r,e.Geometry=n,e.Fragment=o}},e.replaceShaderPicking=(e,t,r)=>{let n=e.Fragment;n=rd.substitute(n,"//VTK::Picking::Dec",["uniform vec3 mapperIndex;","uniform int picking;"]).result,n=rd.substitute(n,"//VTK::Picking::Impl"," gl_FragData[0] = picking != 0 ? vec4(mapperIndex,1.0) : gl_FragData[0];").result,e.Fragment=n},e.replaceShaderPositionVC=(e,r,n)=>{t.lastBoundBO.replaceShaderPositionVC(e,r,n)},e.invokeShaderCallbacks=(e,r,n)=>{const o=t.renderable.getViewSpecificProperties().ShadersCallbacks;o&&o.forEach(t=>{t.callback(t.userData,e,r,n)})},e.setMapperShaderParameters=(e,r,n)=>{if(e.getProgram().isUniformUsed("PrimitiveIDOffset")&&e.getProgram().setUniformi("PrimitiveIDOffset",t.primitiveIDOffset),e.getProgram().isAttributeUsed("vertexWC")&&(e.getVAO().addAttributeArray(e.getProgram(),e.getCABO(),"vertexWC",e.getCABO().getVertexOffset(),e.getCABO().getStride(),t.context.FLOAT,3,!1)||qd("Error setting vertexWC in shader VAO.")),e.getCABO().getElementCount()&&(t.VBOBuildTime.getMTime()>e.getAttributeUpdateTime().getMTime()||e.getShaderSourceTime().getMTime()>e.getAttributeUpdateTime().getMTime())){t.renderable.getCustomShaderAttributes().forEach((r,n)=>{e.getProgram().isAttributeUsed(`${r}MC`)&&(e.getVAO().addAttributeArray(e.getProgram(),e.getCABO(),`${r}MC`,e.getCABO().getCustomData()[n].offset,e.getCABO().getStride(),t.context.FLOAT,e.getCABO().getCustomData()[n].components,!1)||qd(`Error setting ${r}MC in shader VAO.`))}),e.getProgram().isAttributeUsed("tcoordMC")&&e.getCABO().getTCoordOffset()?e.getVAO().addAttributeArray(e.getProgram(),e.getCABO(),"tcoordMC",e.getCABO().getTCoordOffset(),e.getCABO().getStride(),t.context.FLOAT,e.getCABO().getTCoordComponents(),!1)||qd("Error setting tcoordMC in shader VAO."):e.getVAO().removeAttributeArray("tcoordMC"),e.getProgram().isAttributeUsed("scalarColor")&&e.getCABO().getColorComponents()?e.getVAO().addAttributeArray(e.getProgram(),e.getCABO().getColorBO(),"scalarColor",e.getCABO().getColorOffset(),e.getCABO().getColorBOStride(),t.context.UNSIGNED_BYTE,4,!0)||qd("Error setting scalarColor in shader VAO."):e.getVAO().removeAttributeArray("scalarColor"),t.internalColorTexture&&e.getProgram().isUniformUsed("texture1")&&t.internalColorTexture.getTextureUnit()>-1&&e.getProgram().setUniformi("texture1",t.internalColorTexture.getTextureUnit());const o=t.openGLActor2D.getActiveTextures();if(o)for(let t=0;t{const o=t.renderable.getColorMapColors();if(!o||0===o.getNumberOfComponents()){const t=e.getProgram(),r=n.getProperty(),o=r.getOpacity();t.setUniformf("opacityUniform",o);const i=r.getColor();t.setUniform3fArray("diffuseColorUniform",i)}},e.setLightingShaderParameters=(e,t,r)=>{},e.setCameraShaderParameters=(e,r,o)=>{const i=e.getProgram(),a=e.getCABO().getCoordShiftAndScaleEnabled()?e.getCABO().getInverseShiftAndScaleMatrix():null,s=r.getRenderWindow().getViews()[0].getViewportSize(r),l=r.getViewport(),u=o.getActualPositionCoordinate().getComputedDoubleViewportValue(r),c=[0,0,1,1],d=[0,0,1,1];if(d[0]=l[0]>=c[0]?l[0]:c[0],d[1]=l[1]>=c[1]?l[1]:c[1],d[2]=l[2]<=c[2]?l[2]:c[2],d[3]=l[3]<=c[3]?l[3]:c[3],d[0]>=d[2])return;if(d[1]>=d[3])return;s[0]=bo(s[0]*(d[2]-d[0])/(l[2]-l[0])),s[1]=bo(s[1]*(d[3]-d[1])/(l[3]-l[1]));const p=t._openGLRenderer.getParent().getSize(),f=bo(u[0]-(d[0]-l[0])*p[0]),g=bo(u[1]-(d[1]-l[1])*p[1]),y=-f;let v=-f+s[0];const b=-g;let x=-g+s[1];y===v&&(v=y+1),b===x&&(x=b+1);const _=h(new Float64Array(16));var S,C,T;_[0]=2/(v-y),_[5]=2/(x-b),_[3]=-1*(v+y)/(v-y),_[7]=-1*(x+b)/(x-b),_[10]=0,_[11]=o.getProperty().getDisplayLocation()===Wd.FOREGROUND?-1:1,_[15]=1,m(_,_),i.setUniformMatrix("WCVCMatrix",(S=[_,a],C=n,T=t.tmpMat4,C.identity(T),S.reduce((e,t,r)=>0===r?t?C.copy(e,t):C.identity(e):t?C.multiply(e,e,t):e,T)))},e.getAllocatedGPUMemoryInBytes=()=>{let e=0;return t.primitives.forEach(t=>{e+=t.getAllocatedGPUMemoryInBytes()}),e}}(e,t)},"vtkOpenGLPolyDataMapper2D");Qt("vtkMapper2D",Zd);var ep={Orientation:{HORIZONTAL:"horizontal",VERTICAL:"vertical",AUTO:"auto"}};const{VectorMode:tp}=ul,{Orientation:rp}=ep;function np(e,t,r){e.strokeStyle=t.strokeColor,e.lineWidth=t.strokeSize,e.fillStyle=t.fontColor;const n=t.fontSize??r;e.font=`${t.fontStyle} ${n}px ${t.fontFamily}`}function op(e,t){return e=>{const r=e.getLastSize(),n=(r[0]/700)**.8,o=(r[1]/700)**.8,i=Math.min(n,o),a=e.getAxisTextStyle(),s=e.getTickTextStyle();Object.assign(a,t.axisTextStyle),Object.assign(s,t.tickTextStyle),void 0===a.fontSize&&(a.fontSize=Math.max(24*i,12)),void 0===s.fontSize&&(e.getLastAspectRatio()>1?s.fontSize=Math.max(20*i,10):s.fontSize=Math.max(16*i,10));const l=e.updateTextureAtlas();e.setTopTitle(!1);const u=e.getBoxSizeByReference();let c=!1;if(c=t.orientation===rp.VERTICAL||t.orientation!==rp.HORIZONTAL&&e.getLastAspectRatio()>1,c)e.setTickLabelPixelOffset(.3*s.fontSize),l.titleWidth<=l.tickWidth+e.getTickLabelPixelOffset()+.8*s.fontSize?(e.setTopTitle(!0),e.setAxisTitlePixelOffset(.2*s.fontSize),u[0]=2*(l.tickWidth+e.getTickLabelPixelOffset()+.8*s.fontSize)/r[0],e.setBoxPosition([.98-u[0],-.92])):(e.setAxisTitlePixelOffset(.2*s.fontSize),u[0]=2*(l.titleHeight+e.getAxisTitlePixelOffset()+l.tickWidth+e.getTickLabelPixelOffset()+.8*s.fontSize)/r[0],e.setBoxPosition([.99-u[0],-.92])),u[1]=Math.max(1.2,Math.min(1.84/o,1.84));else{e.setAxisTitlePixelOffset(1.2*s.fontSize),e.setTickLabelPixelOffset(.1*s.fontSize);const t=2*(.8*s.fontSize+l.titleHeight+e.getAxisTitlePixelOffset())/r[1],n=2*l.tickWidth/r[0];u[0]=Math.min(1.9,Math.max(1.4,1.4*n*(e.getTicks().length+3))),u[1]=t,e.setBoxPosition([-.5*u[0],-.97])}e.recomputeBarSegments(l)}}function ip(e,t){return e=>{const t=e.getLastTickBounds(),r=no().domain([t[0],t[1]]),n=r.ticks(5),o=r.tickFormat(5);e.setTicks(n),e.setTickStrings(n.map(o))}}const ap=zt.newInstance(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{renderable:null};Object.assign(t,{},r),zt.obj(e,t),zt.setGet(e,t,["axisTitlePixelOffset","tickLabelPixelOffset","renderable","topTitle","ticks","tickStrings","tickPositions"]),zt.get(e,t,["lastSize","lastAspectRatio","lastTickBounds","axisTextStyle","tickTextStyle","barActor","tmActor"]),zt.getArray(e,t,["boxPosition","boxSize"]),zt.setArray(e,t,["boxPosition","boxSize"],2),t.forceUpdate=!1,t.lastRebuildTime={},zt.obj(t.lastRebuildTime,{mtime:0}),t.lastSize=[-1,-1],t.tmCanvas=document.createElement("canvas"),t.tmContext=t.tmCanvas.getContext("2d"),t._tmAtlas=new Map,t.barMapper=Gl.newInstance(),t.barMapper.setInterpolateScalarsBeforeMapping(!0),t.barMapper.setUseLookupTableScalarRange(!0),t.polyData=mc.newInstance(),t.barMapper.setInputData(t.polyData),t.barActor=ss.newInstance(),t.barActor.setMapper(t.barMapper),t.tmPolyData=mc.newInstance(),t.tmMapper=Gl.newInstance(),t.tmMapper.setInputData(t.tmPolyData),t.tmTexture=vc.newInstance({resizable:!0}),t.tmTexture.setInterpolate(!1),t.tmActor=ss.newInstance({parentProp:e}),t.tmActor.setMapper(t.tmMapper),t.tmActor.addTexture(t.tmTexture),t.barPosition=[0,0],t.barSize=[0,0],t.boxPosition=[.88,-.92],t.boxSize=[.1,1.1],t.lastTickBounds=[],function(e,t){t.classHierarchy.push("vtkScalarBarActorHelper"),e.setRenderable=r=>{t.renderable!==r&&(t.renderable=r,t.barActor.setProperty(r.getProperty()),t.barActor.setParentProp(r),t.barActor.setCoordinateSystemToDisplay(),t.tmActor.setProperty(r.getProperty()),t.tmActor.setParentProp(r),t.tmActor.setCoordinateSystemToDisplay(),t.generateTicks=r.generateTicks,t.axisTextStyle={...r.getAxisTextStyle()},t.tickTextStyle={...r.getTickTextStyle()},e.modified())},e.updateAPISpecificData=(r,n,o)=>{t.lastSize[0]===r[0]&&t.lastSize[1]===r[1]||(t.lastSize[0]=r[0],t.lastSize[1]=r[1],t.lastAspectRatio=r[0]/r[1],t.forceUpdate=!0);const i=t.renderable.getScalarsToColors();if(i&&t.renderable.getVisibility()&&(t.barMapper.setLookupTable(i),t.camera=n,t.renderWindow=o,t.forceUpdate||Math.max(i.getMTime(),e.getMTime(),t.renderable.getMTime())>t.lastRebuildTime.getMTime())){const r=i.getMappingRange();if(t.lastTickBounds=[...r],t.renderable.getGenerateTicks()(e),t.renderable.getAutomated())t.renderable.getAutoLayout()(e);else{t.axisTextStyle={...t.renderable.getAxisTextStyle()},t.tickTextStyle={...t.renderable.getTickTextStyle()},t.barPosition=[...t.renderable.getBarPosition()],t.barSize=[...t.renderable.getBarSize()],t.boxPosition=[...t.renderable.getBoxPosition()],t.boxSize=[...t.renderable.getBoxSize()],t.axisTitlePixelOffset=t.renderable.getAxisTitlePixelOffset(),t.tickLabelPixelOffset=t.renderable.getTickLabelPixelOffset();const r=e.updateTextureAtlas();e.recomputeBarSegments(r)}e.updatePolyDataForLabels(),e.updatePolyDataForBarSegments(),t.lastRebuildTime.modified(),t.forceUpdate=!1}},e.updateTextureAtlas=()=>{t.tmContext.textBaseline="bottom",t.tmContext.textAlign="left";const r={},n=new Map;let o=0,i=1;np(t.tmContext,t.axisTextStyle,18);let a=t.tmContext.measureText(t.renderable.getAxisLabel()),s={height:a.actualBoundingBoxAscent+2,startingHeight:i,width:a.width+2,textStyle:t.axisTextStyle};n.set(t.renderable.getAxisLabel(),s),i+=s.height,o=s.width,r.titleWidth=s.width,r.titleHeight=s.height,r.tickWidth=0,r.tickHeight=0,np(t.tmContext,t.tickTextStyle,14);const l=[...e.getTickStrings(),"NaN","Below","Above"];for(let e=0;e{e.tcoords=[0,(i-e.startingHeight-e.height)/i,e.width/o,(i-e.startingHeight-e.height)/i,e.width/o,(i-e.startingHeight)/i,0,(i-e.startingHeight)/i]}),t.tmCanvas.width=o,t.tmCanvas.height=i,t.tmContext.textBaseline="bottom",t.tmContext.textAlign="left",t.tmContext.clearRect(0,0,o,i),n.forEach((e,r)=>{const n=e.textStyle===t.axisTextStyle?18:14;np(t.tmContext,e.textStyle,n),t.tmContext.fillText(r,1,e.startingHeight+e.height-1)}),t.tmTexture.setCanvas(t.tmCanvas),t.tmTexture.modified(),t._tmAtlas=n,r},e.computeBarSize=e=>{t.vertical=t.boxSize[1]>t.boxSize[0];const r=2*e.tickHeight/t.lastSize[1],n=[1,1];if(t.vertical){const o=2*(e.tickWidth+t.tickLabelPixelOffset)/t.lastSize[0];if(t.topTitle){const r=2*(e.titleHeight+t.axisTitlePixelOffset)/t.lastSize[1];t.barSize[0]=t.boxSize[0]-o,t.barSize[1]=t.boxSize[1]-r}else{const r=2*(e.titleHeight+t.axisTitlePixelOffset)/t.lastSize[0];t.barSize[0]=t.boxSize[0]-r-o,t.barSize[1]=t.boxSize[1]}t.barPosition[0]=t.boxPosition[0]+o,t.barPosition[1]=t.boxPosition[1],n[1]=r}else{const r=(2*e.tickWidth-8)/t.lastSize[0],o=2*(e.titleHeight+t.axisTitlePixelOffset)/t.lastSize[1];t.barSize[0]=t.boxSize[0],t.barPosition[0]=t.boxPosition[0],t.barSize[1]=t.boxSize[1]-o,t.barPosition[1]=t.boxPosition[1],n[0]=r}return n},e.recomputeBarSegments=r=>{const n=e.computeBarSize(r);t.barSegments=[];const o=[0,0],i=t.vertical?1:0,a=t.vertical?.01:.02;function s(e,r){t.barSegments.push({corners:[[...o],[o[0]+n[0],o[1]],[o[0]+n[0],o[1]+n[1]],[o[0],o[1]+n[1]]],scalars:r,title:e}),o[i]+=n[i]+a}t.renderable.getDrawNanAnnotation()&&t.renderable.getScalarsToColors().getNanColor()&&s("NaN",[NaN,NaN,NaN,NaN]),t.renderable.getDrawBelowRangeSwatch()&&t.renderable.getScalarsToColors().getUseBelowRangeColor?.()&&s("Below",[-.1,-.1,-.1,-.1]);const l=t.renderable.getScalarsToColors().getUseAboveRangeColor?.();o[i]+=a;const u=n[i];n[i]=l?1-2*a-n[i]-o[i]:1-a-o[i],s("ticks",t.vertical?[0,0,.995,.995]:[0,.995,.995,0]),t.renderable.getDrawAboveRangeSwatch()&&l&&(n[i]=u,o[i]+=a,s("Above",[1.1,1.1,1.1,1.1]))};const r=new Float64Array(3);e.createPolyDataForOneLabel=(e,n,o,i,a,s)=>{const l=t._tmAtlas.get(e);if(!l)return;let u=s.ptIdx,c=s.cellIdx;r[0]=(.5*n[0]+.5)*t.lastSize[0],r[1]=(.5*n[1]+.5)*t.lastSize[1],r[2]=n[2],r[0]+=a[0],r[1]+=a[1];const d=[],p="vertical"===i?[1,0]:[0,1];"vertical"===i?(d[0]=l.width,d[1]=-l.height,"middle"===o[0]?r[1]-=l.width/2:"right"===o[0]&&(r[1]-=l.width),"middle"===o[1]?r[0]+=l.height/2:"top"===o[1]&&(r[0]+=l.height)):(d[0]=l.width,d[1]=l.height,"middle"===o[0]?r[0]-=l.width/2:"right"===o[0]&&(r[0]-=l.width),"middle"===o[1]?r[1]-=l.height/2:"top"===o[1]&&(r[1]-=l.height)),s.points[3*u]=r[0],s.points[3*u+1]=r[1],s.points[3*u+2]=r[2],s.tcoords[2*u]=l.tcoords[0],s.tcoords[2*u+1]=l.tcoords[1],u++,r[p[0]]+=d[0],s.points[3*u]=r[0],s.points[3*u+1]=r[1],s.points[3*u+2]=r[2],s.tcoords[2*u]=l.tcoords[2],s.tcoords[2*u+1]=l.tcoords[3],u++,r[p[1]]+=d[1],s.points[3*u]=r[0],s.points[3*u+1]=r[1],s.points[3*u+2]=r[2],s.tcoords[2*u]=l.tcoords[4],s.tcoords[2*u+1]=l.tcoords[5],u++,r[p[0]]-=d[0],s.points[3*u]=r[0],s.points[3*u+1]=r[1],s.points[3*u+2]=r[2],s.tcoords[2*u]=l.tcoords[6],s.tcoords[2*u+1]=l.tcoords[7],u++,s.polys[4*c]=3,s.polys[4*c+1]=u-4,s.polys[4*c+2]=u-3,s.polys[4*c+3]=u-2,c++,s.polys[4*c]=3,s.polys[4*c+1]=u-4,s.polys[4*c+2]=u-2,s.polys[4*c+3]=u-1,s.ptIdx+=4,s.cellIdx+=2};const n=new Float64Array(3);e.updatePolyDataForLabels=()=>{const r=e.getTickStrings().length+t.barSegments.length,o=4*r,i=2*r,a=new Float64Array(3*o),s=new Uint16Array(4*i),l=new Float32Array(2*o),u={ptIdx:0,cellIdx:0,polys:s,points:a,tcoords:l},c=t.vertical?0:1,d=t.vertical?1:0;n[2]=-.99;const p=t.vertical?["right","middle"]:["middle","bottom"];let f=[0,1];const h=[0,0];t.vertical?(h[0]=-t.tickLabelPixelOffset,t.topTitle?(n[0]=t.boxPosition[0]+.5*t.boxSize[0],n[1]=t.barPosition[1]+t.barSize[1],e.createPolyDataForOneLabel(t.renderable.getAxisLabel(),n,["middle","bottom"],"horizontal",[0,t.axisTitlePixelOffset],u)):(n[0]=t.barPosition[0]+t.barSize[0],n[1]=t.barPosition[1]+.5*t.barSize[1],e.createPolyDataForOneLabel(t.renderable.getAxisLabel(),n,["middle","top"],"vertical",[t.axisTitlePixelOffset,0],u)),f=[-1,0]):(h[1]=t.tickLabelPixelOffset,n[0]=t.barPosition[0]+.5*t.barSize[0],n[1]=t.barPosition[1]+t.barSize[1],e.createPolyDataForOneLabel(t.renderable.getAxisLabel(),n,["middle","bottom"],"horizontal",[0,t.axisTitlePixelOffset],u)),n[c]=t.barPosition[c]+(.5*f[c]+.5)*t.barSize[c],n[d]=t.barPosition[d]+.5*t.barSize[d];let m=null;for(let r=0;r{const e=t.renderable.getScalarsToColors();let r=0;t.renderable.getDrawNanAnnotation()&&e.getNanColor()&&(r+=1),t.renderable.getDrawBelowRangeSwatch()&&e.getUseBelowRangeColor?.()&&(r+=1),t.renderable.getDrawAboveRangeSwatch()&&e.getUseAboveRangeColor?.()&&(r+=1);const o=4*(1+r),i=o;let a=1;e.getVectorMode()===tp.COMPONENT&&(a=e.getVectorComponent()+1);const s=new Float64Array(3*o),l=new Uint16Array(5*i),u=new Float32Array(o*a);let c=0,d=0;for(let e=0;e2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,function(e){return{automated:!0,autoLayout:null,axisLabel:"Scalar Value",barPosition:[0,0],barSize:[0,0],boxPosition:[.88,-.92],boxSize:[.1,1.1],scalarToColors:null,axisTitlePixelOffset:36,axisTextStyle:{fontColor:"white",fontStyle:"normal",fontSize:void 0,fontFamily:"serif"},tickLabelPixelOffset:14,tickTextStyle:{fontColor:"white",fontStyle:"normal",fontSize:void 0,fontFamily:"serif"},generateTicks:null,drawNanAnnotation:!0,drawBelowRangeSwatch:!0,drawAboveRangeSwatch:!0,orientation:null,...e}}(r)),t.autoLayout||(t.autoLayout=op(0,t)),t.generateTicks||(t.generateTicks=ip()),ss.extend(e,t,r),e.getProperty().setDiffuse(0),e.getProperty().setAmbient(1),zt.setGet(e,t,["automated","autoLayout","axisTitlePixelOffset","axisLabel","scalarsToColors","tickLabelPixelOffset","generateTicks","drawNanAnnotation","drawBelowRangeSwatch","drawAboveRangeSwatch","orientation"]),zt.get(e,t,["axisTextStyle","tickTextStyle"]),zt.getArray(e,t,["barPosition","barSize","boxPosition","boxSize"]),zt.setArray(e,t,["barPosition","barSize","boxPosition","boxSize"],2),function(e,t){t.classHierarchy.push("vtkScalarBarActor"),e.setTickTextStyle=r=>{t.tickTextStyle={...t.tickTextStyle,...r},e.modified()},e.setAxisTextStyle=r=>{t.axisTextStyle={...t.axisTextStyle,...r},e.modified()},e.setOrientationToHorizontal=()=>e.setOrientation(rp.HORIZONTAL),e.setOrientationToVertical=()=>e.setOrientation(rp.VERTICAL),e.resetAutoLayoutToDefault=()=>{e.setAutoLayout(op(0,t))},e.resetGenerateTicksToDefault=()=>{e.setGenerateTicks(ip())}}(e,t)}var lp={newInstance:zt.newInstance(sp,"vtkScalarBarActor"),extend:sp,newScalarBarActorHelper:ap,...ep};const up={};const cp=Pt(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,up,r),Xt.extend(e,t,r),t.scalarBarActorHelper=lp.newScalarBarActorHelper(),function(e,t){t.classHierarchy.push("vtkOpenGLScalarBarActor"),e.buildPass=r=>{r&&(t._openGLRenderer=e.getFirstAncestorOfType("vtkOpenGLRenderer"),t._openGLRenderWindow=t._openGLRenderer.getParent(),t.scalarBarActorHelper.getRenderable()||t.scalarBarActorHelper.setRenderable(t.renderable),e.prepareNodes(),e.addMissingNode(t.scalarBarActorHelper.getBarActor()),e.addMissingNode(t.scalarBarActorHelper.getTmActor()),e.removeUnusedNodes())},e.opaquePass=(e,r)=>{if(e){const e=t._openGLRenderer?t._openGLRenderer.getRenderable().getActiveCamera():null,r=t._openGLRenderer.getTiledSizeAndOrigin();t.scalarBarActorHelper.updateAPISpecificData([r.usize,r.vsize],e,t._openGLRenderWindow.getRenderable())}}}(e,t)},"vtkOpenGLScalarBarActor");Qt("vtkScalarBarActor",cp);const{vtkErrorMacro:dp}=jt,pp={context:null};const fp=Pt(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,pp,r),Xt.extend(e,t,r),t.openGLTexture=Dd.newInstance(),t.tris=ud.newInstance(),t.keyMatrixTime={},mt(t.keyMatrixTime,{mtime:0}),t.keyMatrices={normalMatrix:pe(new Float64Array(9)),mcwc:h(new Float64Array(16))},_t(e,t,["context"]),yt(e,t,["activeTextures"]),function(e,t){t.classHierarchy.push("vtkOpenGLSkybox"),e.buildPass=r=>{if(r){t._openGLRenderer=e.getFirstAncestorOfType("vtkOpenGLRenderer"),t._openGLRenderWindow=t._openGLRenderer.getParent(),t.context=t._openGLRenderWindow.getContext(),t.tris.setOpenGLRenderWindow(t._openGLRenderWindow),t.openGLTexture.setOpenGLRenderWindow(t._openGLRenderWindow);const r=t._openGLRenderer.getRenderable();t.openGLCamera=t._openGLRenderer.getViewNodeFor(r.getActiveCamera(),t.openGLCamera)}},e.queryPass=(e,r)=>{if(e){if(!t.renderable||!t.renderable.getVisibility())return;r.incrementOpaqueActorCount()}},e.opaquePass=(r,n)=>{if(r&&!t._openGLRenderer.getSelector()){e.updateBufferObjects(),t.context.depthMask(!0),t._openGLRenderWindow.getShaderCache().readyShaderProgram(t.tris.getProgram()),t.openGLTexture.render(t._openGLRenderWindow);const r=t.openGLTexture.getTextureUnit();t.tris.getProgram().setUniformi("sbtexture",r);const n=t._openGLRenderer.getRenderable(),o=t.openGLCamera.getKeyMatrices(n),i=new Float64Array(16);if(g(i,o.wcpc),t.tris.getProgram().setUniformMatrix("IMCPCMatrix",i),"box"===t.lastFormat){const e=n.getActiveCamera().getPosition();t.tris.getProgram().setUniform3f("camPos",e[0],e[1],e[2])}t.tris.getVAO().bind(),t.context.drawArrays(t.context.TRIANGLES,0,t.tris.getCABO().getElementCount()),t.tris.getVAO().release(),t.openGLTexture.deactivate()}},e.updateBufferObjects=()=>{if(!t.tris.getCABO().getElementCount()){const e=new Float32Array(12);for(let t=0;t<4;t++)e[3*t]=t%2*2-1,e[3*t+1]=t>1?1:-1,e[3*t+2]=1;const r=_s.newInstance({numberOfComponents:3,values:e});r.setName("points");const n=new Uint16Array(8);n[0]=3,n[1]=0,n[2]=1,n[3]=3,n[4]=3,n[5]=0,n[6]=3,n[7]=2;const o=_s.newInstance({numberOfComponents:1,values:n});t.tris.getCABO().createVBO(o,"polys",Ja.SURFACE,{points:r,cellOffset:0})}t.renderable.getFormat()!==t.lastFormat&&(t.lastFormat=t.renderable.getFormat(),"box"===t.lastFormat&&t.tris.setProgram(t._openGLRenderWindow.getShaderCache().readyShaderProgramArray("//VTK::System::Dec\n attribute vec3 vertexMC;\n uniform mat4 IMCPCMatrix;\n varying vec3 TexCoords;\n void main () {\n gl_Position = vec4(vertexMC.xyz, 1.0);\n vec4 wpos = IMCPCMatrix * gl_Position;\n TexCoords = wpos.xyz/wpos.w;\n }","//VTK::System::Dec\n //VTK::Output::Dec\n varying vec3 TexCoords;\n uniform samplerCube sbtexture;\n uniform vec3 camPos;\n void main () {\n // skybox looks from inside out\n // which means we have to adjust\n // our tcoords. Otherwise text would\n // be flipped\n vec3 tc = normalize(TexCoords - camPos);\n if (abs(tc.z) < max(abs(tc.x),abs(tc.y)))\n {\n tc = vec3(1.0, 1.0, -1.0) * tc;\n }\n else\n {\n tc = vec3(-1.0, 1.0, 1.0) * tc;\n }\n gl_FragData[0] = textureCube(sbtexture, tc);\n }","")),"background"===t.lastFormat&&t.tris.setProgram(t._openGLRenderWindow.getShaderCache().readyShaderProgramArray("//VTK::System::Dec\n attribute vec3 vertexMC;\n uniform mat4 IMCPCMatrix;\n varying vec2 TexCoords;\n void main () {\n gl_Position = vec4(vertexMC.xyz, 1.0);\n vec4 wpos = IMCPCMatrix * gl_Position;\n TexCoords = vec2(vertexMC.x, vertexMC.y)*0.5 + 0.5;\n }","//VTK::System::Dec\n //VTK::Output::Dec\n varying vec2 TexCoords;\n uniform sampler2D sbtexture;\n void main () {\n gl_FragData[0] = texture2D(sbtexture, TexCoords);\n }","")),t.tris.getShaderSourceTime().modified(),t.tris.getVAO().bind(),t.tris.getVAO().addAttributeArray(t.tris.getProgram(),t.tris.getCABO(),"vertexMC",t.tris.getCABO().getVertexOffset(),t.tris.getCABO().getStride(),t.context.FLOAT,3,t.context.FALSE)||dp("Error setting vertexMC in shader VAO."));const e=t.renderable.getTextures();e.length||dp("vtkSkybox requires a texture map"),t.openGLTexture.getRenderable()!==e[0]&&(t.openGLTexture.releaseGraphicsResources(t._openGLRenderWindow),t.openGLTexture.setRenderable(e[0]))}}(e,t)});Qt("vtkSkybox",fp);const{vtkDebugMacro:hp}=jt,mp={};const gp=Pt(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,mp,r),Xt.extend(e,t,r),function(e,t){t.classHierarchy.push("vtkOpenGLPixelSpaceCallbackMapper"),e.opaquePass=(r,n)=>{t._openGLRenderer=e.getFirstAncestorOfType("vtkOpenGLRenderer"),t._openGLRenderWindow=t._openGLRenderer.getLastAncestorOfType("vtkOpenGLRenderWindow");const o=t._openGLRenderer.getAspectRatio(),i=t._openGLRenderer?t._openGLRenderer.getRenderable().getActiveCamera():null,a=t._openGLRenderer.getTiledSizeAndOrigin();let s=null;if(t.renderable.getUseZValues()){const e=n.getZBufferTexture(),r=Math.floor(e.getWidth()),o=Math.floor(e.getHeight()),i=t._openGLRenderWindow.getContext();e.bind();const a=n.getFramebuffer();a?a.saveCurrentBindingsAndBuffers():hp("No framebuffer to save/restore");const l=i.createFramebuffer();i.bindFramebuffer(i.FRAMEBUFFER,l),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,e.getHandle(),0),i.checkFramebufferStatus(i.FRAMEBUFFER)===i.FRAMEBUFFER_COMPLETE&&(s=new Uint8Array(r*o*4),i.viewport(0,0,r,o),i.readPixels(0,0,r,o,i.RGBA,i.UNSIGNED_BYTE,s)),a&&a.restorePreviousBindingsAndBuffers(),i.deleteFramebuffer(l)}t.renderable.invokeCallback(t.renderable.getInputData(),i,o,a,s)},e.queryPass=(e,r)=>{e&&t.renderable.getUseZValues()&&r.requestDepth()}}(e,t)},"vtkOpenGLPixelSpaceCallbackMapper");Qt("vtkPixelSpaceCallbackMapper",gp);const yp=Object.create(null);function vp(e,t){yp[e]=t}const bp={};function xp(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,bp,r),t.overrides=yp,Yt.extend(e,t,r),function(e,t){t.classHierarchy.push("vtkWebGPUViewNodeFactory")}(0,t)}var _p={newInstance:zt.newInstance(xp,"vtkWebGPUViewNodeFactory"),extend:xp};const Sp={keyMatrixTime:null,keyMatrices:null};const Cp=zt.newInstance(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Sp,r),Xt.extend(e,t,r),t.keyMatrixTime={},zt.obj(t.keyMatrixTime),t.keyMatrices={normalMatrix:new Float64Array(16),vcpc:new Float64Array(16),pcsc:new Float64Array(16),wcvc:new Float64Array(16),scpc:new Float64Array(16),scvc:new Float64Array(16)},zt.setGet(e,t,["keyMatrixTime"]),function(e,t){t.classHierarchy.push("vtkWebGPUCamera"),e.getProjectionMatrix=(e,r,n,o)=>{if(h(e),t.renderable.getParallelProjection()){const i=t.renderable.getParallelScale(),a=i*r,s=i,l=(o[0]-1)*a,u=(o[0]+1)*a,c=(o[1]-1)*s,d=(o[1]+1)*s,p=1/(u-l),f=1/(d-c);e[0]=2*p,e[5]=2*f,e[10]=1/(n[1]-n[0]),e[12]=(u+l)*p,e[13]=(d+c)*f,e[14]=n[1]/(n[1]-n[0])}else{const i=Math.tan(Math.PI*t.renderable.getViewAngle()/360);let a,s;!0===t.renderable.getUseHorizontalViewAngle()?(a=n[0]*i,s=n[0]*i/r):(a=n[0]*i*r,s=n[0]*i);const l=(o[0]-1)*a,u=(o[0]+1)*a,c=(o[1]-1)*s,d=(o[1]+1)*s;e[0]=2*n[0]/(u-l),e[5]=2*n[0]/(d-c),e[12]=(l+u)/(u-l),e[13]=(c+d)/(d-c),e[10]=0,e[14]=n[0],e[11]=-1,e[15]=0}},e.convertToOpenGLDepth=e=>{if(t.renderable.getParallelProjection())return 1-e;const r=t.renderable.getClippingRangeByReference();let n=-r[0]/e;return n=(r[0]+r[1])/(r[1]-r[0])+2*r[0]*r[1]/(n*(r[1]-r[0])),.5*n+.5},e.getKeyMatrices=r=>{const n=r.getRenderable(),o=r.getParent();if(Math.max(o.getMTime(),e.getMTime(),n.getMTime(),t.renderable.getMTime(),r.getStabilizedTime())>t.keyMatrixTime.getMTime()){const n=t.renderable.getViewMatrix();d(t.keyMatrices.normalMatrix,n),t.keyMatrices.normalMatrix[3]=0,t.keyMatrices.normalMatrix[7]=0,t.keyMatrices.normalMatrix[11]=0,g(t.keyMatrices.normalMatrix,t.keyMatrices.normalMatrix),m(t.keyMatrices.wcvc,n);const o=r.getStabilizedCenterByReference();x(t.keyMatrices.scvc,t.keyMatrices.wcvc,o);const i=r.getAspectRatio(),a=t.renderable.getClippingRangeByReference();e.getProjectionMatrix(t.keyMatrices.vcpc,i,a,t.renderable.getWindowCenterByReference()),b(t.keyMatrices.scpc,t.keyMatrices.vcpc,t.keyMatrices.scvc),g(t.keyMatrices.pcsc,t.keyMatrices.scpc),t.keyMatrixTime.modified()}return t.keyMatrices}}(e,t)});vp("vtkCamera",Cp);const Tp={device:null,handle:null,label:null};function wp(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Tp,r),zt.obj(e,t),t.bindables=[],t.bindGroupTime={},zt.obj(t.bindGroupTime,{mtime:0}),zt.get(e,t,["bindGroupTime","handle","sizeInBytes","usage"]),zt.setGet(e,t,["label","device","arrayInformation"]),function(e,t){t.classHierarchy.push("vtkWebGPUBindGroup"),e.setBindables=r=>{if(t.bindables.length===r.length){let e=!0;for(let n=0;n{const r=[];for(let e=0;e{let n=e.getMTime();for(let e=0;en?r:n}if(n{const r=[],n=e.getBindGroupLayoutCount(t.label);for(let e=0;e2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Ep,r),zt.obj(e,t),zt.get(e,t,["lastCameraMTime"]),zt.setGet(e,t,["device","handle"]),function(e,t){t.classHierarchy.push("vtkWebGPUShaderModule"),e.initialize=(e,r)=>{t.device=e,t.handle=t.device.getHandle().createShaderModule({code:r.getCode()})}}(e,t)}var Pp={newInstance:zt.newInstance(Dp,"vtkWebGPUShaderModule"),extend:Dp};const Ip={shaderModules:null,device:null,window:null};function Op(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Ip,r),t._shaderModules=new Map,zt.obj(e,t),zt.setGet(e,t,["device","window"]),function(e,t){t.classHierarchy.push("vtkWebGPUShaderCache"),e.getShaderModule=e=>{const r=e.getType(),n=e.getHash(),o=t._shaderModules.keys();for(let e=0;e3&&void 0!==arguments[3])||arguments[3];const o=Array.isArray(r)?r.join("\n"):r;let i=!1;-1!==e.search(t)&&(i=!0);let a="";n&&(a="g");const s=new RegExp(t,a);return{replace:i,result:e.replace(s,o)}}};const Mp={handle:null,layouts:null,renderEncoder:null,shaderDescriptions:null,vertexState:null,topology:null,pipelineDescription:null};function Rp(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Mp,r),mt(e,t),t.layouts=[],t.shaderDescriptions=[],yt(e,t,["handle","pipelineDescription"]),_t(e,t,["device","renderEncoder","topology","vertexState"]),function(e,t){t.classHierarchy.push("vtkWebGPUPipeline"),e.getShaderDescriptions=()=>t.shaderDescriptions,e.initialize=(e,r)=>{t.pipelineDescription=t.renderEncoder.getPipelineSettings(),t.pipelineDescription.primitive.topology=t.topology,t.pipelineDescription.vertex=t.vertexState,t.pipelineDescription.label=r;const n=[];for(let e=0;e{for(let r=0;r{e&&t.layouts.push({layout:e.getBindGroupLayout(t.device),label:e.getLabel()})},e.getBindGroupLayout=e=>t.layouts[e].layout,e.getBindGroupLayoutCount=e=>{for(let r=0;r{t.bindBuffers(e)}}(e,t)}var Fp={newInstance:Pt(Rp,"vtkWebGPUPipeline"),extend:Rp};const Bp={type:null,hash:null,code:null,outputNames:null,outputTypes:null};function Lp(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Bp,r),t.outputNames=[],t.outputTypes=[],t.outputInterpolations=[],t.builtinOutputNames=[],t.builtinOutputTypes=[],t.builtinInputNames=[],t.builtinInputTypes=[],zt.obj(e,t),zt.setGet(e,t,["type","hash","code"]),zt.getArray(e,t,["outputTypes","outputNames","outputInterpolations"]),function(e,t){t.classHierarchy.push("vtkWebGPUShaderDescription"),e.hasOutput=e=>t.outputNames.includes(e),e.addOutput=function(e,r){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;t.outputTypes.push(e),t.outputNames.push(r),t.outputInterpolations.push(n)},e.addBuiltinOutput=(e,r)=>{t.builtinOutputTypes.push(e),t.builtinOutputNames.push(r)},e.addBuiltinInput=(e,r)=>{t.builtinInputTypes.push(e),t.builtinInputNames.push(r)},e.replaceShaderCode=(e,r)=>{const n=[];let o=[];if(r&&n.push(r.getShaderCode()),e||t.builtinInputNames.length){const r=[];if(r.push(`struct ${t.type}Input\n{`),e){const t=e.getOutputNamesByReference(),n=e.getOutputTypesByReference(),o=e.getOutputInterpolationsByReference();for(let e=0;e1&&(r.push("};"),o=r,n[n.length-1]+=",",n.push(`input: ${t.type}Input`))}if(n.length&&(t.code=Np.substitute(t.code,"//VTK::IOStructs::Input",n).result),t.outputNames.length+t.builtinOutputNames.length){const e=[`struct ${t.type}Output\n{`];for(let r=0;r ${t.type}Output`]).result}t.code=Np.substitute(t.code,"//VTK::IOStructs::Dec",o).result}}(e,t)}var kp={newInstance:zt.newInstance(Lp,"vtkWebGPUShaderDescription"),extend:Lp};const Up={r8unorm:{numComponents:1,nativeType:Uint8Array,stride:1,elementSize:1,sampleType:"float"},r8snorm:{numComponents:1,nativeType:Int8Array,stride:1,elementSize:1,sampleType:"float"},r8uint:{numComponents:1,nativeType:Uint8Array,stride:1,elementSize:1,sampleType:"uint"},r8sint:{numComponents:1,nativeType:Int8Array,stride:1,elementSize:1,sampleType:"sint"},r16uint:{numComponents:1,nativeType:Uint16Array,stride:2,elementSize:2,sampleType:"uint"},r16sint:{numComponents:1,nativeType:Int16Array,stride:2,elementSize:2,sampleType:"sint"},r16float:{numComponents:1,nativeType:Float32Array,stride:2,elementSize:2,sampleType:"float"},rg8unorm:{numComponents:2,nativeType:Uint8Array,stride:2,elementSize:1,sampleType:"float"},rg8snorm:{numComponents:2,nativeType:Int8Array,stride:2,elementSize:1,sampleType:"float"},rg8uint:{numComponents:2,nativeType:Uint8Array,stride:2,elementSize:1,sampleType:"uint"},rg8sint:{numComponents:2,nativeType:Int8Array,stride:2,elementSize:1,sampleType:"sint"},r32uint:{numComponents:1,nativeType:Uint32Array,stride:4,elementSize:4,sampleType:"uint"},r32sint:{numComponents:1,nativeType:Int32Array,stride:4,elementSize:4,sampleType:"sint"},r32float:{numComponents:1,nativeType:Float32Array,stride:4,elementSize:4,sampleType:"unfilterable-float"},rg16uint:{numComponents:2,nativeType:Uint16Array,stride:4,elementSize:2,sampleType:"uint"},rg16sint:{numComponents:2,nativeType:Int16Array,stride:4,elementSize:2,sampleType:"sint"},rg16float:{numComponents:2,nativeType:Float32Array,stride:4,elementSize:2,sampleType:"float"},rgba8unorm:{numComponents:4,nativeType:Uint8Array,stride:4,elementSize:1,sampleType:"float"},"rgba8unorm-srgb":{numComponents:4,nativeType:Uint8Array,stride:4,elementSize:1,sampleType:"float"},rgba8snorm:{numComponents:4,nativeType:Int8Array,stride:4,elementSize:1,sampleType:"float"},rgba8uint:{numComponents:4,nativeType:Uint8Array,stride:4,elementSize:1,sampleType:"uint"},rgba8sint:{numComponents:4,nativeType:Int8Array,stride:4,elementSize:1,sampleType:"sint"},bgra8unorm:{numComponents:4,nativeType:Uint8Array,stride:4,elementSize:1,sampleType:"float"},"bgra8unorm-srgb":{numComponents:4,nativeType:Uint8Array,stride:4,elementSize:1,sampleType:"float"},rgb9e5ufloat:{numComponents:4,nativeType:Uint32Array,stride:4,sampleType:"float"},rgb10a2unorm:{numComponents:4,nativeType:Uint32Array,stride:4,sampleType:"float"},rg11b10ufloat:{numComponents:4,nativeType:Float32Array,stride:4,sampleType:"float"},rg32uint:{numComponents:2,nativeType:Uint32Array,stride:8,elementSize:4,sampleType:"uint"},rg32sint:{numComponents:2,nativeType:Int32Array,stride:8,elementSize:4,sampleType:"sint"},rg32float:{numComponents:2,nativeType:Float32Array,stride:8,elementSize:4,sampleType:"unfilterable-float"},rgba16uint:{numComponents:4,nativeType:Uint16Array,stride:8,elementSize:2,sampleType:"uint"},rgba16sint:{numComponents:4,nativeType:Int16Array,stride:8,elementSize:2,sampleType:"sint"},rgba16float:{numComponents:4,nativeType:Float32Array,stride:8,elementSize:2,sampleType:"float"},rgba32uint:{numComponents:4,nativeType:Uint32Array,stride:16,elementSize:4,sampleType:"uint"},rgba32sint:{numComponents:4,nativeType:Int32Array,stride:16,elementSize:4,sampleType:"sint"},rgba32float:{numComponents:4,nativeType:Float32Array,stride:16,elementSize:4,sampleType:"unfilterable-float"},stencil8:{numComponents:1,nativeType:Uint8Array,stride:1,elementSize:1,sampleType:"uint"},depth16unorm:{numComponents:1,nativeType:Uint16Array,stride:2,elementSize:2,sampleType:"depth"},depth24plus:{numComponents:1,nativeType:Uint32Array,stride:4,elementSize:3,sampleType:"depth"},"depth24plus-stencil8":{numComponents:2,nativeType:Uint32Array,stride:4,sampleType:"mixed"},depth32float:{numComponents:1,nativeType:Float32Array,stride:4,elementSize:4,sampleType:"depth"}};var Vp=function(e){return!e||e.length<6?0:e in Up==1?Up[e]:(Ze(`unknown format ${e}`),null)},Gp=function(e){if(!e||e.length<5)return 0;let t=1;"x"===e[e.length-2]&&(t=Number(e[e.length-1]));const r=1===t?e.length-1:e.length-3,n=Number(e[r]);return Number.isNaN(n)?(Ze(`unknown format ${e}`),0):t*(5-n/2)},zp=function(e){if(!e||e.length<5)return 0;let t=1;return"x"===e[e.length-2]&&(t=Number(e[e.length-1])),t},jp=function(e){if(!e||e.length<5)return 0;let t;if("f"===e[0])t="Float";else if("s"===e[0])t="Int";else{if("u"!==e[0])return void Ze(`unknown format ${e}`);t="Uint"}const r=e.split("x")[0],n=Number(r[r.length-1]);if(!Number.isNaN(n))return t+=8*(5-n/2),t+="Array",t;Ze(`unknown format ${e}`)},Wp=function(e){let t;if("f"===e[0]||"n"===e[1])t="f32";else if("s"===e[0]&&"i"===e[1])t="i32";else{if("u"!==e[0]||"i"!==e[1])return void Ze(`unknown format ${e}`);t="u32"}let r=1;return"x"===e[e.length-2]&&(r=Number(e[e.length-1])),4===r?`vec4<${t}>`:3===r?`vec3<${t}>`:2===r?`vec2<${t}>`:t},Hp=function(e){if(!e)return 0;let t=1;return"vec"===e.substring(0,3)?t=Number(e[3]):"mat"===e.substring(0,3)&&(t=e[3]*e[5]),4*t},Kp=function(e){if(e)return e.includes("f32")?"Float32Array":e.includes("i32")?"Int32Array":e.includes("u32")?"Uint32Array":void Ze(`unknown format ${e}`)};function Xp(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let r=0;r2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,$p,r),mt(e,t),t.bindingDescriptions=[],t.attributeDescriptions=[],t.inputs=[],_t(e,t,["created","device","handle","indexBuffer"]),function(e,t){t.classHierarchy.push("vtkWebGPUVertexInput"),e.addBuffer=function(e,r){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"vertex",o=r;Array.isArray(o)||(o=[o]);for(let r=0;re.names[0]t.names[0]?1:0)},e.removeBufferIfPresent=e=>{for(let r=0;r{for(let r=0;r{for(let r=0;r{for(let r=0;r{let e="",r=0;for(let n=0;n0&&(e+=",\n"),e=`${e} @location(${r}) ${t.inputs[n].names[o]} : ${a}`,r++}return e},e.getVertexInputInformation=()=>{const e={};if(t.inputs.length){const r=[];let n=0;for(let e=0;e{for(let r=0;r{},e.releaseGraphicsResources=()=>{t.created&&(t.inputs=[],t.bindingDescriptions=[],t.attributeDescriptions=[])}}(e,t)}var Yp={newInstance:Pt(qp,"vtkWebGPUVertexInput"),extend:qp};const Jp={additionalBindables:void 0,bindGroup:null,device:null,fragmentShaderTemplate:null,numberOfInstances:1,numberOfVertices:0,pipelineHash:null,shaderReplacements:null,SSBO:null,textureViews:null,topology:"triangle-list",UBO:null,vertexShaderTemplate:null,WebGPURenderer:null};function Qp(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Jp,r),Xt.extend(e,t,r),t.textureViews=[],t.vertexInput=Yp.newInstance(),t.bindGroup=Ap.newInstance({label:"mapperBG"}),t.additionalBindables=[],t.fragmentShaderTemplate=t.fragmentShaderTemplate||"\n//VTK::Renderer::Dec\n\n//VTK::Color::Dec\n\n//VTK::Normal::Dec\n\n//VTK::TCoord::Dec\n\n//VTK::Select::Dec\n\n//VTK::RenderEncoder::Dec\n\n//VTK::Mapper::Dec\n\n//VTK::IOStructs::Dec\n\n@fragment\nfn main(\n//VTK::IOStructs::Input\n)\n//VTK::IOStructs::Output\n{\n var output : fragmentOutput;\n\n //VTK::Color::Impl\n\n //VTK::Normal::Impl\n\n //VTK::Light::Impl\n\n //VTK::TCoord::Impl\n\n //VTK::Select::Impl\n\n // var computedColor:vec4 = vec4(1.0,0.5,0.5,1.0);\n\n //VTK::RenderEncoder::Impl\n return output;\n}\n",t.vertexShaderTemplate=t.vertexShaderTemplate||"\n//VTK::Renderer::Dec\n\n//VTK::Color::Dec\n\n//VTK::Normal::Dec\n\n//VTK::TCoord::Dec\n\n//VTK::Select::Dec\n\n//VTK::Mapper::Dec\n\n//VTK::IOStructs::Dec\n\n@vertex\nfn main(\n//VTK::IOStructs::Input\n)\n//VTK::IOStructs::Output\n{\n var output : vertexOutput;\n\n // var vertex: vec4 = vertexBC;\n\n //VTK::Color::Impl\n\n //VTK::Normal::Impl\n\n //VTK::TCoord::Impl\n\n //VTK::Select::Impl\n\n //VTK::Position::Impl\n\n return output;\n}\n",t.shaderReplacements=new Map,zt.get(e,t,["pipeline","vertexInput"]),zt.setGet(e,t,["additionalBindables","device","fragmentShaderTemplate","interpolate","numberOfInstances","numberOfVertices","pipelineHash","shaderReplacements","SSBO","textureViews","topology","UBO","vertexShaderTemplate","WebGPURenderer"]),function(e,t){t.classHierarchy.push("vtkWebGPUSimpleMapper"),e.generateShaderDescriptions=(r,n,o)=>{const i=kp.newInstance({type:"vertex",hash:r,code:t.vertexShaderTemplate}),a=kp.newInstance({type:"fragment",hash:r,code:t.fragmentShaderTemplate}),s=n.getShaderDescriptions();s.push(i),s.push(a);const l=t.vertexShaderTemplate+t.fragmentShaderTemplate,u=new RegExp("//VTK::[^:]*::","g"),c=l.match(u).filter((e,t,r)=>r.indexOf(e)===t),d=c.map(e=>`replaceShader${e.substring(7,e.length-2)}`);for(let e=0;e{const n=t.getShaderDescription("vertex");n.replaceShaderCode(null,r),t.getShaderDescription("fragment").replaceShaderCode(n)},e.replaceShaderRenderEncoder=(e,r,n)=>{t.renderEncoder.replaceShaderCode(r)},t.shaderReplacements.set("replaceShaderRenderEncoder",e.replaceShaderRenderEncoder),e.replaceShaderRenderer=(e,r,n)=>{if(!t.WebGPURenderer)return;const o=t.WebGPURenderer.getBindGroup().getShaderCode(r),i=r.getShaderDescription("vertex");let a=i.getCode();a=Np.substitute(a,"//VTK::Renderer::Dec",[o]).result,i.setCode(a);const s=r.getShaderDescription("fragment");a=s.getCode(),a=Np.substitute(a,"//VTK::Renderer::Dec",[o]).result,s.setCode(a)},t.shaderReplacements.set("replaceShaderRenderer",e.replaceShaderRenderer),e.replaceShaderMapper=(e,r,n)=>{const o=t.bindGroup.getShaderCode(r),i=r.getShaderDescription("vertex");let a=i.getCode();a=Np.substitute(a,"//VTK::Mapper::Dec",[o]).result,i.setCode(a);const s=r.getShaderDescription("fragment");s.addBuiltinInput("bool","@builtin(front_facing) frontFacing"),a=s.getCode(),a=Np.substitute(a,"//VTK::Mapper::Dec",[o]).result,s.setCode(a)},t.shaderReplacements.set("replaceShaderMapper",e.replaceShaderMapper),e.replaceShaderPosition=(e,t,r)=>{const n=t.getShaderDescription("vertex");n.addBuiltinOutput("vec4","@builtin(position) Position");let o=n.getCode();o=Np.substitute(o,"//VTK::Position::Impl",[" output.Position = rendererUBO.SCPCMatrix*vertexBC;"]).result,n.setCode(o)},t.shaderReplacements.set("replaceShaderPosition",e.replaceShaderPosition),e.replaceShaderTCoord=(e,t,r)=>{t.getShaderDescription("vertex").addOutput("vec2","tcoordVS")},t.shaderReplacements.set("replaceShaderTCoord",e.replaceShaderTCoord),e.addTextureView=e=>{t.textureViews.includes(e)||t.textureViews.push(e)},e.prepareToDraw=r=>{t.renderEncoder=r,e.updateInput(),e.updateBuffers(),e.updateBindings(),e.updatePipeline()},e.updateInput=()=>{},e.updateBuffers=()=>{},e.updateBindings=()=>{t.bindGroup.setBindables(e.getBindables())},e.computePipelineHash=()=>{},e.registerDrawCallback=r=>{r.registerDrawCallback(t.pipeline,e.draw)},e.prepareAndDraw=r=>{e.prepareToDraw(r),r.setPipeline(t.pipeline),e.draw(r)},e.draw=e=>{const r=e.getBoundPipeline();e.activateBindGroup(t.bindGroup),t.WebGPURenderer&&t.WebGPURenderer.bindUBO(e),r.bindVertexInput(e,t.vertexInput);const n=t.vertexInput.getIndexBuffer();n?e.drawIndexed(n.getIndexCount(),t.numberOfInstances,0,0,0):e.draw(t.numberOfVertices,t.numberOfInstances,0,0)},e.getBindables=()=>{const e=[...t.additionalBindables];t.UBO&&e.push(t.UBO),t.SSBO&&e.push(t.SSBO);for(let r=0;r{e.computePipelineHash(),t.pipeline=t.device.getPipeline(t.pipelineHash),t.pipeline||(t.pipeline=Fp.newInstance(),t.pipeline.setDevice(t.device),t.WebGPURenderer&&t.pipeline.addBindGroupLayout(t.WebGPURenderer.getBindGroup()),t.pipeline.addBindGroupLayout(t.bindGroup),e.generateShaderDescriptions(t.pipelineHash,t.pipeline,t.vertexInput),t.pipeline.setTopology(t.topology),t.pipeline.setRenderEncoder(t.renderEncoder),t.pipeline.setVertexState(t.vertexInput.getVertexInputInformation()),t.device.createPipeline(t.pipelineHash,t.pipeline))}}(e,t)}var Zp={newInstance:zt.newInstance(Qp,"vtkWebGPUSimpleMapper"),extend:Qp};const ef={};function tf(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,ef,r),Zp.extend(e,t,r),function(e,t){t.classHierarchy.push("vtkWebGPUFullScreenQuad"),e.replaceShaderPosition=(e,t,r)=>{const n=t.getShaderDescription("vertex");n.addBuiltinOutput("vec4","@builtin(position) Position"),n.addOutput("vec4","vertexVC");let o=n.getCode();o=Np.substitute(o,"//VTK::Position::Impl",["output.tcoordVS = vec2(vertexBC.x * 0.5 + 0.5, 1.0 - vertexBC.y * 0.5 - 0.5);","output.Position = vec4(vertexBC, 1.0);","output.vertexVC = vec4(vertexBC, 1);"]).result,n.setCode(o)},t.shaderReplacements.set("replaceShaderPosition",e.replaceShaderPosition),e.updateBuffers=()=>{const e=t.device.getBufferManager().getFullScreenQuadBuffer();t.vertexInput.addBuffer(e,["vertexBC"]),t.numberOfVertices=6}}(e,t)}var rf={newInstance:zt.newInstance(tf,"vtkWebGPUFullScreenQuad"),extend:tf},nf={BufferUsage:{Verts:0,Lines:1,Triangles:2,Strips:3,LinesFromStrips:4,LinesFromTriangles:5,Points:6,UniformArray:7,PointArray:8,NormalsFromPoints:9,Texture:10,RawVertex:11,Storage:12,Index:13},PrimitiveTypes:{Start:0,Points:0,Lines:1,Triangles:2,TriangleStrips:3,TriangleEdges:4,TriangleStripEdges:5,End:6}};const of=["getMappedRange","mapAsync","unmap"];const af={device:null,handle:null,sizeInBytes:0,strideInBytes:0,arrayInformation:null,usage:null,label:null,sourceTime:null};function sf(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,af,r),zt.obj(e,t),zt.get(e,t,["handle","sizeInBytes","usage"]),zt.setGet(e,t,["strideInBytes","device","arrayInformation","label","sourceTime"]),function(e,t){t.classHierarchy.push("vtkWebGPUBuffer"),e.create=(e,r)=>{t.handle=t.device.getHandle().createBuffer({size:e,usage:r,label:t.label}),t.sizeInBytes=e,t.usage=r},e.write=e=>{!function(e,t,r,n){const o=n.byteLength,i=e.createBuffer({size:o,usage:GPUBufferUsage.COPY_SRC,mappedAtCreation:!0}),a=i.getMappedRange(0,o);new Uint8Array(a).set(new Uint8Array(n)),i.unmap();const s=e.createCommandEncoder();s.copyBufferToBuffer(i,0,t,0,o);const l=s.finish();e.queue.submit([l]),i.destroy()}(t.device.getHandle(),t.handle,0,e.buffer)},e.createAndWrite=(e,r)=>{const n=4*Math.ceil(e.byteLength/4);t.handle=t.device.getHandle().createBuffer({size:n,usage:r,mappedAtCreation:!0,label:t.label}),t.sizeInBytes=n,t.usage=r,new Uint8Array(t.handle.getMappedRange()).set(new Uint8Array(e.buffer)),t.handle.unmap()};for(let r=0;r2)for(let i=0;i2){for(let i=0;i2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,xf,r),lf.extend(e,t,r),zt.setGet(e,t,["flatIdToPointId","flatIdToCellId","flatSize","indexCount"]),function(e,t){t.classHierarchy.push("vtkWebGPUIndexBuffer"),e.buildIndexBuffer=e=>{const r=e.cells,n=e.primitiveType,o=e.representation,i=e.cellOffset,a=r.getData(),s=a.length,l=function(e){switch(e){case cf.Points:return"points";case cf.Lines:return"lines";case cf.Triangles:case cf.TriangleEdges:return"polys";case cf.TriangleStripEdges:case cf.TriangleStrips:return"strips";default:return""}}(n),u=e.numberOfPoints,c={provokedPointIds:new Uint8Array(u),extraPoints:0,iboSize:0,flatId:0,iboId:0,cellProvokedMap:new df};let d=null;d=o===uf.POINTS||n===cf.Points?bf.anythingToPoints:o===uf.WIREFRAME||n===cf.Lines?bf[`${l}ToWireframe`]:bf[`${l}ToSurface`],mf=hf;let p=i||0;for(let e=0;e2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Df,r),mt(e,t),_t(e,t,["device"]),function(e,t){function r(e){let r,n;if(e.dataArray&&!e.nativeArray&&(e.nativeArray=e.dataArray.getData()),e.usage===Cf.Index&&(r=Sf.newInstance({label:e.label}),r.setDevice(t.device),n=GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST,r.buildIndexBuffer(e),r.createAndWrite(e.nativeArray,n),r.setArrayInformation([{format:e.format}])),r||(r=lf.newInstance({label:e.label}),r.setDevice(t.device)),e.usage===Cf.UniformArray&&(n=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,r.createAndWrite(e.nativeArray,n)),e.usage===Cf.Storage&&(n=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST,r.createAndWrite(e.nativeArray,n)),e.usage===Cf.Texture&&(n=GPUBufferUsage.COPY_SRC,r.createAndWrite(e.nativeArray,n)),e.usage===Cf.PointArray){n=GPUBufferUsage.VERTEX;const t=jp(e.format),o=Af(e.indexBuffer,e.dataArray.getData(),e.dataArray.getNumberOfComponents(),t,{packExtra:e.packExtra,shift:e.shift,scale:e.scale,cellData:e.cellData,cellOffset:e.cellOffset});r.createAndWrite(o.nativeArray,n),r.setStrideInBytes(Gp(e.format)),r.setArrayInformation([{offset:0,format:e.format,interpolation:e.cellData?"flat":"perspective"}])}if(e.usage===Cf.NormalsFromPoints){n=GPUBufferUsage.VERTEX;const t=jp(e.format),o=function(e,t){const r=t.getData(),n=e.getData();if(!n||!r)return null;const o=new Int8Array(4*e.getNumberOfCells()),i=n.length;let a=0;for(let e=0;et.device.hasCachedObject(e),e.getBuffer=e=>e.hash?t.device.getCachedObject(e.hash,r,e):r(e),e.getBufferForPointArray=(t,r)=>{const n=function(e){let t;switch(e.getDataType()){case wf.UNSIGNED_CHAR:t="uint8";break;case wf.FLOAT:t="float32";break;case wf.UNSIGNED_INT:t="uint32";break;case wf.INT:t="sint32";break;case wf.DOUBLE:t="float32";break;case wf.UNSIGNED_SHORT:t="uint16";break;case wf.SHORT:t="sin16";break;default:t="float32"}switch(e.getNumberOfComponents()){case 2:t+="x2";break;case 3:t.includes("32")||Tf(`unsupported x3 type for ${t}`),t+="x3";break;case 4:t+="x4"}return t}(t),o={hash:`${t.getMTime()}I${r.getMTime()}${n}`,usage:Cf.PointArray,format:n,dataArray:t,indexBuffer:r};return e.getBuffer(o)},e.getFullScreenQuadBuffer=()=>{if(t.fullScreenQuadBuffer)return t.fullScreenQuadBuffer;t.fullScreenQuadBuffer=lf.newInstance(),t.fullScreenQuadBuffer.setDevice(t.device);const e=new Float32Array([-1,-1,0,1,-1,0,1,1,0,-1,-1,0,1,1,0,-1,1,0]);return t.fullScreenQuadBuffer.createAndWrite(e,GPUBufferUsage.VERTEX),t.fullScreenQuadBuffer.setStrideInBytes(12),t.fullScreenQuadBuffer.setArrayInformation([{offset:0,format:"float32x3"}]),t.fullScreenQuadBuffer}}(e,t)}var If={newInstance:Pt(Pf),extend:Pf,...nf};const{BufferUsage:Of}=If,{vtkErrorMacro:Nf}=zt,Mf={bufferEntries:null,bufferEntryNames:null,sizeInBytes:0,label:null,numberOfInstances:1};function Rf(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Mf,r),zt.obj(e,t),t._bufferEntryNames=new Map,t.bufferEntries=[],t._sendTime={},zt.obj(t._sendTime,{mtime:0}),t.bindGroupTime={},zt.obj(t.bindGroupTime,{mtime:0}),t.bindGroupLayoutEntry=t.bindGroupLayoutEntry||{buffer:{type:"read-only-storage"}},zt.get(e,t,["bindGroupTime"]),zt.setGet(e,t,["device","bindGroupLayoutEntry","label","numberOfInstances","sizeInBytes"]),function(e,t){t.classHierarchy.push("vtkWebGPUStorageBuffer"),e.addEntry=(e,r)=>{if(t._bufferEntryNames.has(e))return void Nf(`entry named ${e} already exists`);t._bufferEntryNames.set(e,t.bufferEntries.length);const n=Hp(r);t.bufferEntries.push({name:e,type:r,sizeInBytes:n,offset:t.sizeInBytes,nativeType:Kp(r)}),t.sizeInBytes+=n},e.send=e=>{if(!t._buffer){const r={nativeArray:t.Float32Array,usage:Of.Storage,label:t.label};return t._buffer=e.getBufferManager().getBuffer(r),t.bindGroupTime.modified(),void t._sendTime.modified()}e.getHandle().queue.writeBuffer(t._buffer.getHandle(),0,t.arrayBuffer,0,t.sizeInBytes*t.numberOfInstances),t._sendTime.modified()},e.createView=e=>{e in t==0&&(t.arrayBuffer||(t.arrayBuffer=new ArrayBuffer(t.sizeInBytes*t.numberOfInstances)),t[e]=zt.newTypedArray(e,t.arrayBuffer))},e.setValue=(r,n,o)=>{const i=t._bufferEntryNames.get(r);if(void 0===i)return void Nf(`entry named ${r} not found in UBO`);const a=t.bufferEntries[i];e.createView(a.nativeType);const s=t[a.nativeType];s[(a.offset+n*t.sizeInBytes)/s.BYTES_PER_ELEMENT]=o},e.setArray=(r,n,o)=>{const i=t._bufferEntryNames.get(r);if(void 0===i)return void Nf(`entry named ${r} not found in UBO`);const a=t.bufferEntries[i];e.createView(a.nativeType);const s=t[a.nativeType],l=(a.offset+n*t.sizeInBytes)/s.BYTES_PER_ELEMENT;for(let e=0;e{const o=t._bufferEntryNames.get(r);if(void 0===o)return void Nf(`entry named ${r} not found in UBO`);const i=t.bufferEntries[o];e.createView(i.nativeType);const a=t[i.nativeType],s=n.length/t.numberOfInstances;for(let e=0;e{const o=t._bufferEntryNames.get(r);if(void 0===o)return void Nf(`entry named ${r} not found in UBO`);const i=t.bufferEntries[o];e.createView(i.nativeType);const a=t[i.nativeType],s=n.length/t.numberOfInstances;for(let e=0;e{const o=t._bufferEntryNames.get(r);if(void 0===o)return void Nf(`entry named ${r} not found in UBO`);const i=t.bufferEntries[o];e.createView(i.nativeType);const a=t[i.nativeType];for(let e=0;et._sendTime.getMTime(),e.getShaderCode=(e,r)=>{const n=[`struct ${t.label}StructEntry\n{`];for(let e=0;e,\n};\n@binding(${e}) @group(${r}) var ${t.label}: ${t.label}Struct;\n`),n.join("\n")},e.getBindGroupEntry=()=>({resource:{buffer:t._buffer.getHandle()}}),e.clearData=()=>{t.numberOfInstances=0,t.sizeInBytes=0,t.bufferEntries=[],t._bufferEntryNames=new Map,t._buffer=null,delete t.arrayBuffer,delete t.Float32Array}}(e,t)}var Ff={newInstance:zt.newInstance(Rf,"vtkWebGPUStorageBuffer"),extend:Rf};const{BufferUsage:Bf}=If,{vtkErrorMacro:Lf}=zt,kf={bufferEntries:null,bufferEntryNames:null,sizeInBytes:0,label:null,bindGroupLayoutEntry:null,bindGroupEntry:null};function Uf(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,kf,r),zt.obj(e,t),t._bufferEntryNames=new Map,t.bufferEntries=[],t.bindGroupLayoutEntry=t.bindGroupLayoutEntry||{buffer:{type:"uniform"}},t.sendTime={},zt.obj(t.sendTime,{mtime:0}),t.bindGroupTime={},zt.obj(t.bindGroupTime,{mtime:0}),t.sendDirty=!0,t.sortDirty=!0,zt.get(e,t,["binding","bindGroupTime"]),zt.setGet(e,t,["bindGroupLayoutEntry","device","label","sizeInBytes"]),function(e,t){t.classHierarchy.push("vtkWebGPUUniformBuffer"),e.addEntry=(e,r)=>{t._bufferEntryNames.has(e)?Lf(`entry named ${e} already exists`):(t.sortDirty=!0,t._bufferEntryNames.set(e,t.bufferEntries.length),t.bufferEntries.push({name:e,type:r,sizeInBytes:Hp(r),offset:-1,nativeType:Kp(r),packed:!1}))},e.sortBufferEntries=()=>{if(!t.sortDirty)return;let e=0;const r=[];let n=4;for(let e=0;e4&&(o.packed=!0,o.offset=e,r.push(o),e+=o.sizeInBytes)}for(let n=0;n{if(!t.UBO){const r={nativeArray:t.Float32Array,usage:Bf.UniformArray,label:t.label};t.UBO=e.getBufferManager().getBuffer(r),t.bindGroupTime.modified(),t.sendDirty=!1}t.sendDirty&&(e.getHandle().queue.writeBuffer(t.UBO.getHandle(),0,t.arrayBuffer,0,t.sizeInBytes),t.sendDirty=!1),t.sendTime.modified()},e.createView=e=>{e in t==0&&(t.arrayBuffer||(t.arrayBuffer=new ArrayBuffer(t.sizeInBytes)),t[e]=zt.newTypedArray(e,t.arrayBuffer))},e.setValue=(r,n)=>{e.sortBufferEntries();const o=t._bufferEntryNames.get(r);if(void 0===o)return void Lf(`entry named ${r} not found in UBO`);const i=t.bufferEntries[o];e.createView(i.nativeType);const a=t[i.nativeType];i.lastValue!==n&&(a[i.offset/a.BYTES_PER_ELEMENT]=n,t.sendDirty=!0),i.lastValue=n},e.setArray=(r,n)=>{e.sortBufferEntries();const o=t._bufferEntryNames.get(r);if(void 0===o)return void Lf(`entry named ${r} not found in UBO`);const i=t.bufferEntries[o];e.createView(i.nativeType);const a=t[i.nativeType];let s=!1;for(let e=0;e({resource:{buffer:t.UBO.getHandle()}}),e.getSendTime=()=>t.sendTime.getMTime(),e.getShaderCode=(r,n)=>{e.sortBufferEntries();const o=[`struct ${t.label}Struct\n{`];for(let e=0;e ${t.label}: ${t.label}Struct;`),o.join("\n")}}(e,t)}var Vf={newInstance:zt.newInstance(Uf,"vtkWebGPUUniformBuffer"),extend:Uf};const{vtkDebugMacro:Gf}=jt,zf="\n//VTK::Renderer::Dec\n\n//VTK::Mapper::Dec\n\n//VTK::TCoord::Dec\n\n//VTK::RenderEncoder::Dec\n\n//VTK::IOStructs::Dec\n\n@fragment\nfn main(\n//VTK::IOStructs::Input\n)\n//VTK::IOStructs::Output\n{\n var output: fragmentOutput;\n\n var computedColor: vec4 = mapperUBO.BackgroundColor;\n\n //VTK::RenderEncoder::Impl\n return output;\n}\n",jf=new Float64Array(16),Wf=new Float64Array(16);function Hf(e){return e.getPositional()?e.getConeAngle()>=90?0:2:1}const Kf={bindGroup:null,selector:null,renderEncoder:null,recenterThreshold:20,suppressClear:!1,stabilizedCenter:[0,0,0]};const Xf=Pt(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Kf,r),Xt.extend(e,t,r),t.UBO=Vf.newInstance({label:"rendererUBO"}),t.UBO.addEntry("WCVCMatrix","mat4x4"),t.UBO.addEntry("SCPCMatrix","mat4x4"),t.UBO.addEntry("PCSCMatrix","mat4x4"),t.UBO.addEntry("SCVCMatrix","mat4x4"),t.UBO.addEntry("VCPCMatrix","mat4x4"),t.UBO.addEntry("WCVCNormals","mat4x4"),t.UBO.addEntry("viewportSize","vec2"),t.UBO.addEntry("LightCount","i32"),t.UBO.addEntry("MaxEnvironmentMipLevel","f32"),t.UBO.addEntry("BackgroundDiffuseStrength","f32"),t.UBO.addEntry("BackgroundSpecularStrength","f32"),t.UBO.addEntry("cameraParallel","u32"),t.SSBO=Ff.newInstance({label:"rendererLightSSBO"}),t.lightTimeString="",t.bindGroup=Ap.newInstance({label:"rendererBG"}),t.bindGroup.setBindables([t.UBO,t.SSBO]),t.tmpMat4=h(new Float64Array(16)),t.stabilizedTime={},mt(t.stabilizedTime,{mtime:0}),yt(e,t,["bindGroup","stabilizedTime"]),St(e,t,["stabilizedCenter"]),_t(e,t,["renderEncoder","selector","suppressClear","UBO"]),function(e,t){t.classHierarchy.push("vtkWebGPURenderer"),e.buildPass=r=>{if(r){if(!t.renderable)return;t.camera=t.renderable.getActiveCamera(),e.updateLights(),e.prepareNodes(),e.addMissingNode(t.camera),e.addMissingNodes(t.renderable.getViewPropsWithNestedProps()),e.removeUnusedNodes(),t.webgpuCamera=e.getViewNodeFor(t.camera,t.webgpuCamera),e.updateStabilizedMatrix()}},e.updateStabilizedMatrix=()=>{const e=t.camera.getClippingRange(),r=t.camera.getPositionByReference(),n=[],o=[];vr(o,t.camera.getDirectionOfProjectionByReference(),.5*(e[0]+e[1])),gr(n,r,o),wr(o,n,t.stabilizedCenter),Ar(o)/(e[1]-e[0])>t.recenterThreshold&&(t.stabilizedCenter=n,t.stabilizedTime.modified())},e.updateLights=()=>{let e=0;const r=t.renderable.getLightsByReference();for(let t=0;t0&&e++;return e||(Gf("No lights are on, creating one."),t.renderable.createLight()),e},e.updateUBO=()=>{const r=t.UBO.getSendTime();if(t._parent.getMTime()>r||e.getMTime()>r||t.camera.getMTime()>r||t.renderable.getMTime()>r){const r=t.webgpuCamera.getKeyMatrices(e);t.UBO.setArray("WCVCMatrix",r.wcvc),t.UBO.setArray("SCPCMatrix",r.scpc),t.UBO.setArray("PCSCMatrix",r.pcsc),t.UBO.setArray("SCVCMatrix",r.scvc),t.UBO.setArray("VCPCMatrix",r.vcpc),t.UBO.setArray("WCVCNormals",r.normalMatrix),t.UBO.setValue("LightCount",t.renderable.getLights().length),t.UBO.setValue("MaxEnvironmentMipLevel",t.renderable.getEnvironmentTexture()?.getMipLevel()),t.UBO.setValue("BackgroundDiffuseStrength",t.renderable.getEnvironmentTextureDiffuseStrength()),t.UBO.setValue("BackgroundSpecularStrength",t.renderable.getEnvironmentTextureSpecularStrength());const n=e.getYInvertedTiledSizeAndOrigin();t.UBO.setArray("viewportSize",[n.usize,n.vsize]),t.UBO.setValue("cameraParallel",t.camera.getParallelProjection());const o=t._parent.getDevice();t.UBO.sendIfNeeded(o)}},e.updateSSBO=()=>{const r=t.renderable.getLights(),n=t.webgpuCamera.getKeyMatrices(e);let o=`${t.renderable.getMTime()}`;for(let e=0;e"),t.SSBO.addEntry("LightDir","vec4"),t.SSBO.addEntry("LightColor","vec4"),t.SSBO.addEntry("LightData","vec4"),t.SSBO.setAllInstancesFromArray("LightPos",e),t.SSBO.setAllInstancesFromArray("LightDir",o),t.SSBO.setAllInstancesFromArray("LightColor",i),t.SSBO.setAllInstancesFromArray("LightData",a);const s=t._parent.getDevice();t.SSBO.send(s)}t.lightTimeString=o},e.scissorAndViewport=t=>{const r=e.getYInvertedTiledSizeAndOrigin();t.getHandle().setViewport(r.lowerLeftU,r.lowerLeftV,r.usize,r.vsize,0,1),t.getHandle().setScissorRect(r.lowerLeftU,r.lowerLeftV,r.usize,r.vsize)},e.bindUBO=e=>{e.activateBindGroup(t.bindGroup)},e.opaquePass=r=>{r?(t.renderEncoder.begin(t._parent.getCommandEncoder()),e.updateUBO(),e.updateSSBO()):(e.scissorAndViewport(t.renderEncoder),e.clear(),t.renderEncoder.end())},e.clear=()=>{if(t.renderable.getTransparent()||t.suppressClear)return;const r=t._parent.getDevice();if(!t.clearFSQ){t.clearFSQ=rf.newInstance(),t.clearFSQ.setDevice(r),t.clearFSQ.setPipelineHash("clearfsq"),t.clearFSQ.setFragmentShaderTemplate(zf);const e=Vf.newInstance({label:"mapperUBO"});e.addEntry("FSQMatrix","mat4x4"),e.addEntry("BackgroundColor","vec4"),t.clearFSQ.setUBO(e),t.backgroundTex=t.renderable.getEnvironmentTexture()}if("clearfsqwithtexture"!==t.clearFSQ.getPipelineHash()&&t.renderable.getUseEnvironmentTextureAsBackground()&&t.backgroundTex?.getImageLoaded()){t.clearFSQ.setFragmentShaderTemplate("\nfn vecToRectCoord(dir: vec3) -> vec2 {\n var tau: f32 = 6.28318530718;\n var pi: f32 = 3.14159265359;\n var out: vec2 = vec2(0.0);\n\n out.x = atan2(dir.z, dir.x) / tau;\n out.x += 0.5;\n\n var phix: f32 = length(vec2(dir.x, dir.z));\n out.y = atan2(dir.y, phix) / pi + 0.5;\n\n return out;\n}\n\n//VTK::Renderer::Dec\n\n//VTK::Mapper::Dec\n\n//VTK::TCoord::Dec\n\n//VTK::RenderEncoder::Dec\n\n//VTK::IOStructs::Dec\n\n@fragment\nfn main(\n//VTK::IOStructs::Input\n)\n//VTK::IOStructs::Output\n{\n var output: fragmentOutput;\n\n var tcoord: vec4 = vec4(input.vertexVC.xy, -1, 1);\n var V: vec4 = normalize(mapperUBO.FSQMatrix * tcoord); // vec2((input.tcoordVS.x - 0.5) * 2, -(input.tcoordVS.y - 0.5) * 2);\n // textureSampleLevel gets rid of some ugly artifacts\n var background = textureSampleLevel(EnvironmentTexture, EnvironmentTextureSampler, vecToRectCoord(V.xyz), 0.0);\n var computedColor: vec4 = vec4(background.rgb, 1);\n\n //VTK::RenderEncoder::Impl\n return output;\n}\n");const e=Vf.newInstance({label:"mapperUBO"});e.addEntry("FSQMatrix","mat4x4"),e.addEntry("BackgroundColor","vec4"),t.clearFSQ.setUBO(e);const n=r.getTextureManager().getTextureForVTKTexture(t.backgroundTex,"EnvironmentTexture");if(n.getReady()){const e=n.createView("EnvironmentTexture");t.clearFSQ.setTextureViews([e]),t.backgroundTexLoaded=!0;const o=t.backgroundTex.getInterpolate()?"linear":"nearest";e.addSampler(r,{addressModeU:"repeat",addressModeV:"clamp-to-edge",addressModeW:"repeat",minFilter:o,magFilter:o,mipmapFilter:"linear"})}t.clearFSQ.setPipelineHash("clearfsqwithtexture")}else if("clearfsqwithtexture"===t.clearFSQ.getPipelineHash()&&!t.renderable.getUseEnvironmentTextureAsBackground()){t.clearFSQ=rf.newInstance(),t.clearFSQ.setDevice(r),t.clearFSQ.setPipelineHash("clearfsq"),t.clearFSQ.setFragmentShaderTemplate(zf);const e=Vf.newInstance({label:"mapperUBO"});e.addEntry("FSQMatrix","mat4x4"),e.addEntry("BackgroundColor","vec4"),t.clearFSQ.setUBO(e)}const n=t.webgpuCamera.getKeyMatrices(e),o=t.renderable.getBackgroundByReference();t.clearFSQ.getUBO().setArray("BackgroundColor",o),m(Wf,n.normalMatrix),oe(jf,n.scvc,n.pcsc),oe(jf,Wf,jf),t.clearFSQ.getUBO().setArray("FSQMatrix",jf),t.clearFSQ.getUBO().sendIfNeeded(r),t.clearFSQ.prepareAndDraw(t.renderEncoder)},e.translucentPass=r=>{r?t.renderEncoder.begin(t._parent.getCommandEncoder()):(e.scissorAndViewport(t.renderEncoder),t.renderEncoder.end())},e.volumeDepthRangePass=r=>{r?t.renderEncoder.begin(t._parent.getCommandEncoder()):(e.scissorAndViewport(t.renderEncoder),t.renderEncoder.end())},e.getAspectRatio=()=>{const e=t._parent.getSizeByReference(),r=t.renderable.getViewportByReference();return e[0]*(r[2]-r[0])/((r[3]-r[1])*e[1])},e.convertToOpenGLDepth=e=>t.webgpuCamera.convertToOpenGLDepth(e),e.getYInvertedTiledSizeAndOrigin=()=>{const r=e.getTiledSizeAndOrigin(),n=t._parent.getSizeByReference();return r.lowerLeftV=n[1]-r.vsize-r.lowerLeftV,r},e.getTiledSizeAndOrigin=()=>{const e=t.renderable.getViewportByReference(),r=[0,0,1,1],n=e[0]-r[0],o=e[1]-r[1],i=t._parent.normalizedDisplayToDisplay(n,o),a=Math.round(i[0]),s=Math.round(i[1]),l=e[2]-r[0],u=e[3]-r[1],c=t._parent.normalizedDisplayToDisplay(l,u);let d=Math.round(c[0])-a,p=Math.round(c[1])-s;return d<0&&(d=0),p<0&&(p=0),{usize:d,vsize:p,lowerLeftU:a,lowerLeftV:s}},e.getPropFromID=e=>{for(let r=0;rt.stabilizedTime.getMTime(),e.releaseGraphicsResources=()=>{null!==t.selector&&t.selector.releaseGraphicsResources()}}(e,t)},"vtkWebGPURenderer");vp("vtkRenderer",Xf);const{CoordinateSystem:$f}=Ka,qf={keyMatricesTime:null,keyMatrices:null,propID:void 0,bufferShift:void 0};const Yf=zt.newInstance(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,qf,r),Xt.extend(e,t,r),t.keyMatricesTime={},zt.obj(t.keyMatricesTime,{mtime:0}),t.keyMatrices={normalMatrix:new Float64Array(16),bcwc:new Float64Array(16),bcsc:new Float64Array(16)},zt.get(e,t,["propID","keyMatricesTime"]),t.bufferShift=[0,0,0,0],function(e,t){t.classHierarchy.push("vtkWebGPUActor"),e.buildPass=r=>{r&&(t.WebGPURenderer=e.getFirstAncestorOfType("vtkWebGPURenderer"),t.WebGPURenderWindow=t.WebGPURenderer.getFirstAncestorOfType("vtkWebGPURenderWindow"),void 0===t.propID&&(t.propID=t.WebGPURenderWindow.getUniquePropID()),e.prepareNodes(),e.addMissingNode(t.renderable.getMapper()),e.removeUnusedNodes())},e.traverseOpaquePass=r=>{t.renderable&&t.renderable.getNestedVisibility()&&t.renderable.getIsOpaque()&&(!t.WebGPURenderer.getSelector()||t.renderable.getNestedPickable())&&(e.apply(r,!0),t.children[0]&&t.children[0].traverse(r),e.apply(r,!1))},e.traverseTranslucentPass=r=>{!t.renderable||!t.renderable.getNestedVisibility()||t.renderable.getIsOpaque()||t.WebGPURenderer.getSelector()&&!t.renderable.getNestedPickable()||(e.apply(r,!0),t.children[0]&&t.children[0].traverse(r),e.apply(r,!1))},e.queryPass=(e,r)=>{if(e){if(!t.renderable||!t.renderable.getVisibility())return;t.renderable.getIsOpaque()?r.incrementOpaqueActorCount():r.incrementTranslucentActorCount()}},e.getBufferShift=r=>(e.getKeyMatrices(r),t.bufferShift),e.getKeyMatrices=e=>{if(Math.max(t.renderable.getMTime(),e.getStabilizedTime())>t.keyMatricesTime.getMTime()){t.renderable.computeMatrix();const r=t.renderable.getMatrix();t.bufferShift[0]=r[3],t.bufferShift[1]=r[7],t.bufferShift[2]=r[11];const n=e.getStabilizedCenterByReference();t.renderable.getCoordinateSystem()===$f.WORLD&&(t.bufferShift[0]-=n[0],t.bufferShift[1]-=n[1],t.bufferShift[2]-=n[2]),m(t.keyMatrices.bcwc,r),t.renderable.getIsIdentity()?h(t.keyMatrices.normalMatrix):(d(t.keyMatrices.normalMatrix,t.keyMatrices.bcwc),t.keyMatrices.normalMatrix[3]=0,t.keyMatrices.normalMatrix[7]=0,t.keyMatrices.normalMatrix[11]=0,g(t.keyMatrices.normalMatrix,t.keyMatrices.normalMatrix),m(t.keyMatrices.normalMatrix,t.keyMatrices.normalMatrix)),x(t.keyMatrices.bcwc,t.keyMatrices.bcwc,[-t.bufferShift[0],-t.bufferShift[1],-t.bufferShift[2]]),t.renderable.getCoordinateSystem()===$f.WORLD?x(t.keyMatrices.bcsc,t.keyMatrices.bcwc,[-n[0],-n[1],-n[2]]):d(t.keyMatrices.bcsc,t.keyMatrices.bcwc),t.keyMatricesTime.modified()}return t.keyMatrices}}(e,t)});vp("vtkActor",Yf);const{CoordinateSystem:Jf}=Ka,Qf={keyMatricesTime:null,keyMatrices:null,propID:void 0,bufferShift:void 0};const Zf=zt.newInstance(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Qf,r),Xt.extend(e,t,r),t.keyMatricesTime={},zt.obj(t.keyMatricesTime,{mtime:0}),t.keyMatrices={normalMatrix:new Float64Array(16),bcwc:new Float64Array(16),bcsc:new Float64Array(16)},zt.get(e,t,["propID","keyMatricesTime"]),t.bufferShift=[0,0,0,0],function(e,t){t.classHierarchy.push("vtkWebGPUActor2D"),e.buildPass=r=>{r&&(t.WebGPURenderer=e.getFirstAncestorOfType("vtkWebGPURenderer"),t.WebGPURenderWindow=t.WebGPURenderer.getFirstAncestorOfType("vtkWebGPURenderWindow"),void 0===t.propID&&(t.propID=t.WebGPURenderWindow.getUniquePropID()),e.prepareNodes(),e.addMissingNode(t.renderable.getMapper()),e.removeUnusedNodes())},e.traverseOpaquePass=r=>{t.renderable&&t.renderable.getNestedVisibility()&&t.renderable.getIsOpaque()&&(!t.WebGPURenderer.getSelector()||t.renderable.getNestedPickable())&&(e.apply(r,!0),t.children[0]&&t.children[0].traverse(r),e.apply(r,!1))},e.traverseTranslucentPass=r=>{!t.renderable||!t.renderable.getNestedVisibility()||t.renderable.getIsOpaque()||t.WebGPURenderer.getSelector()&&!t.renderable.getNestedPickable()||(e.apply(r,!0),t.children[0]&&t.children[0].traverse(r),e.apply(r,!1))},e.queryPass=(e,r)=>{if(e){if(!t.renderable||!t.renderable.getVisibility())return;t.renderable.getIsOpaque()?r.incrementOpaqueActorCount():r.incrementTranslucentActorCount()}},e.getBufferShift=r=>(e.getKeyMatrices(r),t.bufferShift),e.getKeyMatrices=e=>{if(Math.max(t.renderable.getMTime(),e.getStabilizedTime())>t.keyMatricesTime.getMTime()){t.bufferShift[0]=0,t.bufferShift[1]=0,t.bufferShift[2]=0;const r=e.getStabilizedCenterByReference();t.renderable.getCoordinateSystem()===Jf.WORLD&&(t.bufferShift[0]-=r[0],t.bufferShift[1]-=r[1],t.bufferShift[2]-=r[2]),h(t.keyMatrices.bcwc),h(t.keyMatrices.normalMatrix),x(t.keyMatrices.bcwc,t.keyMatrices.bcwc,[-t.bufferShift[0],-t.bufferShift[1],-t.bufferShift[2]]),t.renderable.getCoordinateSystem()===Jf.WORLD?x(t.keyMatrices.bcsc,t.keyMatrices.bcwc,[-r[0],-r[1],-r[2]]):d(t.keyMatrices.bcsc,t.keyMatrices.bcwc),t.keyMatricesTime.modified()}return t.keyMatrices}}(e,t)});vp("vtkActor2D",Zf);const eh={};const th=Pt(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,eh,r),Xt.extend(e,t,r),t.CubeAxesActorHelper=Fc.newCubeAxesActorHelper(),function(e,t){t.classHierarchy.push("vtkWebGPUCubeAxesActor"),e.buildPass=r=>{r&&(t.WebGPURenderer=e.getFirstAncestorOfType("vtkWebGPURenderer"),t.WebGPURenderWindow=t.WebGPURenderer.getParent(),t.CubeAxesActorHelper.getRenderable()||t.CubeAxesActorHelper.setRenderable(t.renderable),e.prepareNodes(),e.addMissingNode(t.CubeAxesActorHelper.getTmActor()),e.addMissingNode(t.renderable.getGridActor()),e.removeUnusedNodes())},e.opaquePass=(e,r)=>{if(e){const e=t.WebGPURenderer?t.WebGPURenderer.getRenderable().getActiveCamera():null,r=t.WebGPURenderer.getTiledSizeAndOrigin();t.CubeAxesActorHelper.updateAPISpecificData([r.usize,r.vsize],e,t.WebGPURenderWindow.getRenderable())}}}(e,t)},"vtkWebGPUCubeAxesActor");vp("vtkCubeAxesActor",th);const{DisplayLocation:rh}=Hd,nh={color:[1,1,1],opacity:1,pointSize:1,lineWidth:1,representation:Ja.SURFACE,displayLocation:rh.FOREGROUND};function oh(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,nh,r),zt.obj(e,t),zt.setGet(e,t,["opacity","lineWidth","pointSize","displayLocation","representation"]),zt.setGetArray(e,t,["color"],3),function(e,t){t.classHierarchy.push("vtkProperty2D"),e.setDisplayLocationToBackground=()=>e.setDisplayLocation(rh.BACKGROUND),e.setDisplayLocationToForeground=()=>e.setDisplayLocation(rh.FOREGROUND),e.setRepresentationToWireframe=()=>e.setRepresentation(Ja.WIREFRAME),e.setRepresentationToSurface=()=>e.setRepresentation(Ja.SURFACE),e.setRepresentationToPoints=()=>e.setRepresentation(Ja.POINTS),e.getRepresentationAsString=()=>zt.enumToString(Ja,t.representation)}(e,t)}var ih={newInstance:zt.newInstance(oh,"vtkProperty2D"),extend:oh,...Hd};const{BufferUsage:ah,PrimitiveTypes:sh}=If,{Representation:lh}=os,{ScalarMode:uh}=Gl,{CoordinateSystem:ch}=Ka,{DisplayLocation:dh}=ih;function ph(e){return e.indexOf("edge")>=0}const fh={is2D:!1,cellArray:null,currentInput:null,cellOffset:0,primitiveType:0,colorTexture:null,renderEncoder:null,textures:null};function hh(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,fh,r),Zp.extend(e,t,r),t.fragmentShaderTemplate='\nstruct PBRData {\n diffuse: vec3,\n specular: vec3,\n}\n\nstruct Material {\n ior: f32,\n roughness: f32,\n metallic: f32,\n base: vec3,\n};\n\nstruct DirectionalLight {\n direction: vec3,\n color: vec3,\n};\n\nstruct PointLight {\n position: vec3,\n color: vec3,\n};\n\nstruct SpotLight {\n position: vec3,\n direction: vec3,\n cones: vec2,\n color: vec3,\n};\n\nconst pi: f32 = 3.14159265359;\n\n// Dot product with the max already in it\nfn mdot(a: vec3, b: vec3) -> f32 {\n return max(0.0, dot(a, b));\n}\n// Dot product with a max in it that does not allow for negative values\n// Physically based rendering is accurate as long as normals are accurate,\n// however this is pretty often not the case. In order to prevent negative\n// values from ruining light calculations and creating zones of zero light,\n// this remapping is used, which smoothly clamps the dot product between\n// zero and one while still maintaining a good amount of accuracy.\nfn cdot(a: vec3, b: vec3) -> f32 {\n var d: f32 = max(0.0, dot(a, b));\n d = pow((d + 1.0) / 2.0, 2.6);\n return d;\n}\n\n// Lambertian diffuse model\nfn lambertDiffuse(base: vec3, N: vec3, L: vec3) -> vec3 {\n var NdotL: f32 = mdot(N, L);\n NdotL = pow(NdotL, 1.5);\n return (base/pi)*NdotL;\n}\n\n// Yasuhiro Fujii improvement on the Oren-Nayar model\n// https://mimosa-pudica.net/improved-oren-nayar.html\n// p is surface color, o is roughness\nfn fujiiOrenNayar(p: vec3, o: f32, N: vec3, L: vec3, V: vec3) -> vec3 {\n var invpi: f32 = 0.31830988618; // 1/pi\n\n var o2 = o*o;\n var NdotL: f32 = mdot(N, L);\n NdotL = pow(NdotL, 1.5); // Less physically accurate, but hides the "seams" between lights better\n\n var NdotV: f32 = mdot(N, V);\n var LdotV: f32 = mdot(L, V);\n\n var s: f32 = LdotV - NdotL*NdotV;\n var t: f32 = mix(1.0, max(NdotL, NdotV), step(0.0, s)); // Mix with step is the equivalent of an if statement\n var A: vec3 = 0.5*(o2 / (o2 + 0.33)) + 0.17*p*(o2 / (o2 + 0.13));\n A = invpi*(1 - A);\n var B: f32 = 0.45*(o2 / (o2 + 0.09));\n B = invpi*B;\n\n return p*NdotL*(A + B*(s/t));\n}\n\n// Fresnel portion of BRDF (IOR only, simplified)\nfn schlickFresnelIOR(V: vec3, N: vec3, ior: f32, k: f32) -> f32 {\n var NdotV: f32 = mdot(V, N);\n var F0: f32 = (pow((ior - 1.0), 2.0) + k*k) / (pow((ior + 1.0), 2.0) + k*k); // This takes into account the roughness, which the other one does not\n return F0 + (1.0 - F0) * pow((1.0-NdotV), 5.0);\n}\n\n// Fresnel portion of BRDF (Color ior, better)\nfn schlickFresnelRGB(V: vec3, N: vec3, F0: vec3) -> vec3 {\n var NdotV: f32 = mdot(V, N);\n return F0 + (1.0 - F0) * pow((1-NdotV), 5.0);\n}\n\n// Normal portion of BRDF\n// https://learnopengl.com/PBR/Theory\n// Trowbridge-Reitz GGX functions: normal, halfway, roughness^2\nfn trGGX(N: vec3, H: vec3, a: f32) -> f32 {\n var a2: f32 = a*a;\n var NdotH = mdot(N, H);\n var NdotH2 = NdotH*NdotH;\n\n var denom: f32 = NdotH2 * (a2 - 1.0) + 1.0;\n\n return a2 / max((pi*denom*denom), 0.000001);\n}\n\n// A VERY bad approximation of anisotropy. Real anisotropic calculations require tangent and bitangent\nfn anisotrophicTrGGX(N: vec3, H: vec3, O: vec3, s: f32, a: f32) -> f32 {\n var Op: vec3 = (rendererUBO.WCVCNormals * vec4(normalize(O) * s, 0.)).xyz;\n\n var ggx1: f32 = trGGX(N + Op*s, H, a);\n var ggx2: f32 = trGGX(N - Op*s, H, a);\n return (0.5 * ggx1 + 0.5 * ggx2);\n}\n\n// Geometry portion of BRDF\nfn schlickGGX(N: vec3, X: vec3, k: f32) -> f32 {\n var NdotX = cdot(N, X);\n return NdotX / max(0.000001, (NdotX*(1.0-k) + k));\n}\n\nfn smithSurfaceRoughness(N: vec3, V: vec3, L: vec3, k: f32) -> f32 {\n var ggx1: f32 = min(1.0, schlickGGX(N, V, k));\n var ggx2: f32 = min(1.0, schlickGGX(N, L, k));\n return ggx1*ggx2;\n}\n\n// BRDF Combination\nfn cookTorrance(D: f32, F: f32, G: f32, N: vec3, V: vec3, L: vec3) -> f32 {\n var num: f32 = D*F*G;\n var denom: f32 = 4*cdot(V, N)*cdot(L, N);\n\n return num / max(denom, 0.000001);\n}\n\n// Different lighting calculations for different light sources\nfn calcDirectionalLight(N: vec3, V: vec3, mat: Material, light: DirectionalLight) -> PBRData {\n var L: vec3 = normalize(light.direction); // Light Vector\n var H: vec3 = normalize(L + V); // Halfway Vector\n\n var alpha = mat.roughness * mat.roughness;\n var k: f32 = alpha * alpha / 2.0;\n\n var D: f32 = trGGX(N, H, alpha); // Distribution\n // var F: f32 = schlickFresnelIOR(V, N, ior, k); // Fresnel\n var G: f32 = smithSurfaceRoughness(N, V, L, k); // Geometry\n\n var brdf: f32 = cookTorrance(D, 1.0, G, N, V, L); // Fresnel term is replaced with 1 because it is added later\n var incoming: vec3 = light.color;\n var angle: f32 = mdot(L, N);\n angle = pow(angle, 1.5);\n\n var specular: vec3 = brdf * incoming * angle;\n // Oren-Nayar gives a clay-like effect when fully rough which some people may not want, so it might be better to give a separate\n // control property for the diffuse vs specular roughness\n var diffuse: vec3 = incoming * fujiiOrenNayar(mat.base, mat.roughness, N, L, V);\n // Stores the specular and diffuse separately to allow for finer post processing\n var out = PBRData(diffuse, specular);\n\n return out; // Returns angle along with color of light so the final color can be multiplied by angle as well (creates black areas)\n}\n\nfn calcPointLight(N: vec3, V: vec3, fragPos: vec3, mat: Material, light: PointLight) -> PBRData {\n var L: vec3 = normalize(light.position - fragPos);\n var H: vec3 = normalize(L + V);\n var dist = distance(light.position, fragPos);\n\n var alpha = mat.roughness * mat.roughness;\n var k: f32 = alpha * alpha / 2.0;\n\n var D: f32 = trGGX(N, H, alpha); // Distribution\n var F: f32 = schlickFresnelIOR(V, N, mat.ior, k); // Fresnel\n var G: f32 = smithSurfaceRoughness(N, V, L, k); // Geometry\n\n var brdf: f32 = cookTorrance(D, 1.0, G, N, V, L);\n var incoming: vec3 = light.color * (1.0 / (dist * dist));\n var angle: f32 = mdot(L, N);\n angle = pow(angle, 1.5); // Smoothing factor makes it less accurate, but reduces ugly "seams" between light sources\n\n var specular: vec3 = brdf * incoming * angle;\n var diffuse: vec3 = incoming * fujiiOrenNayar(mat.base, mat.roughness, N, L, V);\n // Stores the specular and diffuse separately to allow for finer post processing\n // Could also be done (propably more properly) with a struct\n var out = PBRData(diffuse, specular);\n\n return out; // Returns angle along with color of light so the final color can be multiplied by angle as well (creates black areas)\n}\n\n// For a reason unknown to me, spheres dont seem to behave propperly with head-on spot lights\nfn calcSpotLight(N: vec3, V: vec3, fragPos: vec3, mat: Material, light: SpotLight) -> PBRData {\n var L: vec3 = normalize(light.position - fragPos);\n var H: vec3 = normalize(L + V); // Halfway Vector\n var dist = distance(light.position, fragPos);\n\n var alpha = mat.roughness * mat.roughness;\n var k: f32 = alpha * alpha / 2.0; // could also be pow(alpha + 1.0, 2) / 8\n\n var D: f32 = trGGX(N, H, alpha); // Distribution\n // var F: f32 = schlickFresnelIOR(V, N, ior, k); // Fresnel\n var G: f32 = smithSurfaceRoughness(N, V, L, k); // Geometry\n\n var brdf: f32 = cookTorrance(D, 1.0, G, N, V, L);\n\n var theta: f32 = mdot(normalize(light.direction), L);\n var epsilon: f32 = light.cones.x - light.cones.y;\n var intensity: f32 = (theta - light.cones.y) / epsilon;\n intensity = clamp(intensity, 0.0, 1.0);\n intensity /= dist * dist;\n\n var incoming: vec3 = light.color * intensity;\n\n var angle: f32 = mdot(L, N);\n angle = pow(angle, 1.5); // Smoothing factor makes it less accurate, but reduces ugly "seams" between light sources\n\n var specular: vec3 = brdf * incoming * angle;\n var diffuse: vec3 = incoming * fujiiOrenNayar(mat.base, mat.roughness, N, L, V);\n\n // Stores the specular and diffuse separately to allow for finer post processing\n // Could also be done (propably more properly) with a struct\n var out = PBRData(diffuse, specular);\n\n return out; // Returns angle along with color of light so the final color can be multiplied by angle as well (creates black areas)\n}\n\n// Environment mapping stuff\n// Takes in a vector and converts it to an equivalent coordinate in a rectilinear texture. Should be replaced with cubemaps at some point\nfn vecToRectCoord(dir: vec3) -> vec2 {\n var tau: f32 = 6.28318530718;\n var out: vec2 = vec2(0.0);\n\n out.x = atan2(dir.z, dir.x) / tau;\n out.x += 0.5;\n\n var phix: f32 = length(vec2(dir.x, dir.z));\n out.y = atan2(dir.y, phix) / pi + 0.5;\n\n return out;\n}\n\n//VTK::Renderer::Dec\n\n//VTK::Color::Dec\n\n//VTK::TCoord::Dec\n\n// optional surface normal declaration\n//VTK::Normal::Dec\n\n//VTK::Select::Dec\n\n//VTK::RenderEncoder::Dec\n\n//VTK::Mapper::Dec\n\n//VTK::IOStructs::Dec\n\n@fragment\nfn main(\n//VTK::IOStructs::Input\n)\n//VTK::IOStructs::Output\n{\n var output : fragmentOutput;\n\n // Temporary ambient, diffuse, and opacity\n var ambientColor: vec4 = mapperUBO.AmbientColor;\n var diffuseColor: vec4 = mapperUBO.DiffuseColor;\n var opacity: f32 = mapperUBO.Opacity;\n var ior: f32 = mapperUBO.BaseIOR;\n\n // This should be declared somewhere else\n var _diffuseMap: vec4 = vec4(1.0);\n var _roughnessMap: vec4 = vec4(1.0);\n var _metallicMap: vec4 = vec4(1.0);\n var _normalMap: vec4 = vec4(0.0, 0.0, 1.0, 0.0); // normal map was setting off the normal vector detection in fragment\n var _ambientOcclusionMap: vec4 = vec4(1.);\n var _emissionMap: vec4 = vec4(0.);\n\n //VTK::Color::Impl\n\n //VTK::TCoord::Impl\n\n //VTK::Normal::Impl\n\n var computedColor: vec4 = vec4(diffuseColor.rgb, 1.0);\n\n //VTK::Light::Impl\n\n //VTK::Select::Impl\n\n // Use texture alpha for transparency\n computedColor.a = mapperUBO.Opacity * _diffuseMap.a;\n if (computedColor.a == 0.0) { discard; };\n\n //VTK::Position::Impl\n\n //VTK::RenderEncoder::Impl\n\n return output;\n}\n',t.vertexShaderTemplate="\n//VTK::Renderer::Dec\n\n//VTK::Color::Dec\n\n//VTK::Normal::Dec\n\n//VTK::TCoord::Dec\n\n//VTK::Select::Dec\n\n//VTK::Mapper::Dec\n\n//VTK::IOStructs::Dec\n\n@vertex\nfn main(\n//VTK::IOStructs::Input\n)\n//VTK::IOStructs::Output\n{\n var output : vertexOutput;\n\n var vertex: vec4 = vertexBC;\n\n //VTK::Color::Impl\n\n //VTK::Normal::Impl\n\n //VTK::TCoord::Impl\n\n //VTK::Select::Impl\n\n //VTK::Position::Impl\n\n return output;\n}\n",t._tmpMat3=pe(new Float64Array(9)),t._tmpMat4=h(new Float64Array(16)),t.UBO=Vf.newInstance({label:"mapperUBO"}),t.UBO.addEntry("BCWCMatrix","mat4x4"),t.UBO.addEntry("BCSCMatrix","mat4x4"),t.UBO.addEntry("MCWCNormals","mat4x4"),t.UBO.addEntry("AmbientColor","vec4"),t.UBO.addEntry("DiffuseColor","vec4"),t.UBO.addEntry("EdgeColor","vec4"),t.UBO.addEntry("SpecularColor","vec4"),t.UBO.addEntry("AmbientIntensity","f32"),t.UBO.addEntry("DiffuseIntensity","f32"),t.UBO.addEntry("Roughness","f32"),t.UBO.addEntry("Metallic","f32"),t.UBO.addEntry("Ambient","f32"),t.UBO.addEntry("Normal","f32"),t.UBO.addEntry("Emission","f32"),t.UBO.addEntry("NormalStrength","f32"),t.UBO.addEntry("BaseIOR","f32"),t.UBO.addEntry("SpecularIntensity","f32"),t.UBO.addEntry("LineWidth","f32"),t.UBO.addEntry("Opacity","f32"),t.UBO.addEntry("ZValue","f32"),t.UBO.addEntry("PropID","u32"),t.UBO.addEntry("ClipNear","f32"),t.UBO.addEntry("ClipFar","f32"),t.UBO.addEntry("Time","u32"),_t(e,t,["cellArray","currentInput","cellOffset","is2D","primitiveType","renderEncoder"]),t.textures=[],function(e,t){t.classHierarchy.push("vtkWebGPUCellArrayMapper"),e.buildPass=r=>{r&&(t.is2D?(t.WebGPUActor=e.getFirstAncestorOfType("vtkWebGPUActor2D"),t.forceZValue=!0):(t.WebGPUActor=e.getFirstAncestorOfType("vtkWebGPUActor"),t.forceZValue=!1),t.coordinateSystem=t.WebGPUActor.getRenderable().getCoordinateSystem(),t.useRendererMatrix=t.coordinateSystem!==ch.DISPLAY,t.WebGPURenderer=t.WebGPUActor.getFirstAncestorOfType("vtkWebGPURenderer"),t.WebGPURenderWindow=t.WebGPURenderer.getParent(),t.device=t.WebGPURenderWindow.getDevice())},e.translucentPass=r=>{r&&(e.prepareToDraw(t.WebGPURenderer.getRenderEncoder()),t.renderEncoder.registerDrawCallback(t.pipeline,e.draw))},e.opaquePass=r=>{r&&(e.prepareToDraw(t.WebGPURenderer.getRenderEncoder()),t.renderEncoder.registerDrawCallback(t.pipeline,e.draw))},e.updateUBO=()=>{const r=t.WebGPUActor.getRenderable().getProperty(),n=t.UBO.getSendTime();if(e.getMTime()<=n&&r.getMTime()<=n&&t.renderable.getMTime()<=n)return;const o=t.WebGPUActor.getKeyMatrices(t.WebGPURenderer);if(t.UBO.setArray("BCWCMatrix",o.bcwc),t.UBO.setArray("BCSCMatrix",o.bcsc),t.UBO.setArray("MCWCNormals",o.normalMatrix),t.is2D){const e=r.getDisplayLocation?.()??dh.BACKGROUND;t.UBO.setValue("ZValue",e===dh.FOREGROUND?1:0);const n=r.getColorByReference();t.UBO.setValue("AmbientIntensity",1),t.UBO.setArray("DiffuseColor",[...n,1]),t.UBO.setValue("DiffuseIntensity",0),t.UBO.setValue("SpecularIntensity",0)}else t.UBO.setValue("AmbientIntensity",r.getAmbient()),t.UBO.setArray("AmbientColor",[...r.getAmbientColorByReference(),1]),t.UBO.setValue("DiffuseIntensity",r.getDiffuse()),t.UBO.setArray("DiffuseColor",[...r.getDiffuseColorByReference(),1]),t.UBO.setValue("Roughness",r.getRoughness()),t.UBO.setValue("BaseIOR",r.getBaseIOR()),t.UBO.setValue("Metallic",r.getMetallic()),t.UBO.setValue("NormalStrength",r.getNormalStrength()),t.UBO.setValue("Emission",r.getEmission()),t.UBO.setValue("SpecularIntensity",r.getSpecular()),r.getSpecularColorByReference()&&t.UBO.setArray("SpecularColor",[...r.getSpecularColorByReference(),1]);const i=r.getEdgeColorByReference?.();i&&t.UBO.setArray("EdgeColor",[...i,1]),t.UBO.setValue("LineWidth",r.getLineWidth()),t.UBO.setValue("Opacity",r.getOpacity()),t.UBO.setValue("PropID",t.WebGPUActor.getPropID()),t.UBO.sendIfNeeded(t.WebGPURenderWindow.getDevice())},e.haveWideLines=()=>{const e=t.WebGPUActor.getRenderable(),r=e.getProperty().getRepresentation();return!(e.getProperty().getLineWidth()<=1)&&t.primitiveType!==sh.Verts&&(t.primitiveType!==sh.Triangles&&t.primitiveType!==sh.TriangleStrips||r===lh.WIREFRAME)},e.replaceShaderPosition=(r,n,o)=>{const i=n.getShaderDescription("vertex");i.addBuiltinOutput("vec4","@builtin(position) Position"),i.hasOutput("vertexVC")||i.addOutput("vec4","vertexVC");let a=i.getCode();t.useRendererMatrix?(a=Np.substitute(a,"//VTK::Position::Impl",[" var pCoord: vec4 = rendererUBO.SCPCMatrix*mapperUBO.BCSCMatrix*vertexBC;"," output.vertexVC = rendererUBO.SCVCMatrix * mapperUBO.BCSCMatrix * vec4(vertexBC.xyz, 1.0);","//VTK::Position::Impl"]).result,t.forceZValue&&(a=Np.substitute(a,"//VTK::Position::Impl",["pCoord = vec4(pCoord.xyz/pCoord.w, 1.0);","pCoord.z = mapperUBO.ZValue;","//VTK::Position::Impl"]).result)):(a=Np.substitute(a,"//VTK::Position::Impl",[" var pCoord: vec4 = mapperUBO.BCSCMatrix*vertexBC;"," pCoord.x = 2.0* pCoord.x / rendererUBO.viewportSize.x - 1.0;"," pCoord.y = 2.0* pCoord.y / rendererUBO.viewportSize.y - 1.0;"," pCoord.z = 0.5 - 0.5 * pCoord.z;","//VTK::Position::Impl"]).result,t.forceZValue&&(a=Np.substitute(a,"//VTK::Position::Impl",[" pCoord.z = mapperUBO.ZValue;","//VTK::Position::Impl"]).result)),e.haveWideLines()&&(i.addBuiltinInput("u32","@builtin(instance_index) instanceIndex"),a=Np.substitute(a,"//VTK::Position::Impl",[" var tmpPos: vec4 = pCoord;"," var numSteps: f32 = ceil(mapperUBO.LineWidth - 1.0);"," var offset: f32 = (mapperUBO.LineWidth - 1.0) * (f32(input.instanceIndex / 2u) - numSteps/2.0) / numSteps;"," var tmpPos2: vec3 = tmpPos.xyz / tmpPos.w;"," tmpPos2.x = tmpPos2.x + 2.0 * (f32(input.instanceIndex) % 2.0) * offset / rendererUBO.viewportSize.x;"," tmpPos2.y = tmpPos2.y + 2.0 * (f32(input.instanceIndex + 1u) % 2.0) * offset / rendererUBO.viewportSize.y;"," tmpPos2.z = min(1.0, tmpPos2.z + 0.00001);"," pCoord = vec4(tmpPos2.xyz * tmpPos.w, tmpPos.w);","//VTK::Position::Impl"]).result),a=Np.substitute(a,"//VTK::Position::Impl",[" output.Position = pCoord;"]).result,i.setCode(a)},t.shaderReplacements.set("replaceShaderPosition",e.replaceShaderPosition),e.replaceShaderNormal=(e,r,n)=>{const o=n.getBuffer("normalMC"),i=t.WebGPUActor.getRenderable();if(o){const e=r.getShaderDescription("vertex");e.hasOutput("normalVC")||e.addOutput("vec3","normalVC",o.getArrayInformation()[0].interpolation),e.hasOutput("tangentVC")||e.addOutput("vec3","tangentVC",o.getArrayInformation()[0].interpolation),e.hasOutput("bitangentVC")||e.addOutput("vec3","bitangentVC",o.getArrayInformation()[0].interpolation);let t=e.getCode();t=Np.substitute(t,"//VTK::Normal::Impl",[" output.normalVC = normalize((rendererUBO.WCVCNormals * mapperUBO.MCWCNormals * normalMC).xyz);"," var c1: vec3 = cross(output.normalVC, vec3(0, 0, 1));"," var c2: vec3 = cross(output.normalVC, vec3(0, 1, 0));"," var tangent: vec3 = mix(c1, c2, distance(c1, c2));"," output.tangentVC = normalize(tangent);"," output.bitangentVC = normalize(cross(output.normalVC, tangent));"]).result,e.setCode(t);const n=r.getShaderDescription("fragment");t=n.getCode(),t=i.getProperty().getNormalTexture()?Np.substitute(t,"//VTK::Normal::Impl",[" var normal: vec3 = input.normalVC;"," if (!input.frontFacing) { normal = -normal; }"," var tangent: vec3 = input.tangentVC;"," var bitangent: vec3 = input.bitangentVC;"," var TCVCMatrix: mat3x3 = mat3x3("," tangent.x, bitangent.x, normal.x,"," tangent.y, bitangent.y, normal.y,"," tangent.z, bitangent.z, normal.z,"," );"," var mappedNormal: vec3 = TCVCMatrix * (_normalMap.xyz * 2 - 1);"," normal = mix(normal, mappedNormal, mapperUBO.NormalStrength);"," normal = normalize(normal);"]).result:Np.substitute(t,"//VTK::Normal::Impl",[" var normal: vec3 = input.normalVC;"," if (!input.frontFacing) { normal = -normal; }"," normal = normalize(normal);"]).result,n.setCode(t)}},t.shaderReplacements.set("replaceShaderNormal",e.replaceShaderNormal),e.replaceShaderLight=(e,r,n)=>{if(e.includes("sel"))return;const o=r.getShaderDescription("vertex");o.hasOutput("vertexVC")||o.addOutput("vec4","vertexVC");const i=t.WebGPURenderer.getRenderable(),a=r.getShaderDescription("fragment");let s=a.getCode();if(!s.includes("var normal:")||!t.useRendererMatrix||ph(e)||t.is2D||e.includes("sel"))s=Np.substitute(s,"//VTK::Light::Impl",[" let diffuse = diffuseColor.rgb;"," let specular = mapperUBO.SpecularColor.rgb * mapperUBO.SpecularColor.a;"," computedColor = vec4(diffuse * _diffuseMap.rgb, mapperUBO.Opacity);"]).result,a.setCode(s);else{const e=[" let fragPos = vec3(input.vertexVC.xyz);"," let V = mix(normalize(-fragPos), vec3(0, 0, 1), f32(rendererUBO.cameraParallel)); // View Vector"," let baseColor = _diffuseMap.rgb * diffuseColor.rgb;"," let roughness = max(0.000001, mapperUBO.Roughness * _roughnessMap.r);"," let metallic = mapperUBO.Metallic * _metallicMap.r;"," let alpha = roughness * roughness;"," let k = alpha * alpha / 2.0;"," var diffuse = vec3(0.);"," var specular = vec3(0.);"," let emission = _emissionMap.rgb * mapperUBO.Emission;",""," // Material struct"," let mat = Material(ior, roughness, metallic, baseColor);",""," {"," var i = 0;"," loop {"," if (!(i < rendererUBO.LightCount)) { break; }"," switch (i32(rendererLightSSBO.values[i].LightData.x)) {"," // Point Light"," case 0 {"," let color = rendererLightSSBO.values[i].LightColor.rgb * rendererLightSSBO.values[i].LightColor.w;"," let pos = (rendererLightSSBO.values[i].LightPos).xyz;"," let pointLight = PointLight(pos, color);"," let result = calcPointLight(normal, V, fragPos, mat, pointLight);"," diffuse += max(vec3(0), result.diffuse);"," specular += max(vec3(0), result.specular);"," }"," // Directional light"," case 1 {"," let dir = normalize((rendererUBO.WCVCNormals * vec4(normalize(rendererLightSSBO.values[i].LightDir.xyz), 0.)).xyz);"," let color = rendererLightSSBO.values[i].LightColor.rgb * rendererLightSSBO.values[i].LightColor.w;"," let dirLight = DirectionalLight(dir, color);"," let result = calcDirectionalLight(normal, V, mat, dirLight); // diffuseColor.rgb needs to be fixed with a more dynamic diffuse color"," diffuse += max(vec3(0), result.diffuse);"," specular += max(vec3(0), result.specular);"," }"," // Spot Light"," case 2 {"," let color = rendererLightSSBO.values[i].LightColor.rgb * rendererLightSSBO.values[i].LightColor.w;"," let pos = (rendererLightSSBO.values[i].LightPos).xyz;"," let dir = normalize((rendererUBO.WCVCNormals * vec4(normalize(rendererLightSSBO.values[i].LightDir.xyz), 0.)).xyz);"," let cones = vec2(rendererLightSSBO.values[i].LightData.y, rendererLightSSBO.values[i].LightData.z);"," let spotLight = SpotLight(pos, dir, cones, color);"," let result = calcSpotLight(normal, V, fragPos, mat, spotLight);"," diffuse += max(vec3(0), result.diffuse);"," specular += max(vec3(0), result.specular);"," }"," default { continue; }"," }"," continuing { i++; }"," }"," }"," let fresnel = min(1.0, schlickFresnelIOR(V, normal, ior, k)); // Fresnel"," // This could be controlled with its own variable (that isnt base color) for better artistic control"," let fresnelMetallic = schlickFresnelRGB(V, normal, baseColor); // Fresnel for metal, takes color into account"," let kS = min(vec3(1.0), mix(vec3(fresnel), fresnelMetallic, metallic));"," let kD = (1.0 - kS) * (1.0 - metallic);"," let PBR = mapperUBO.DiffuseIntensity * kD * diffuse + kS * specular;"," computedColor = vec4(PBR + emission, mapperUBO.Opacity);"];i.getEnvironmentTexture()?.getImageLoaded()&&e.push(" // To get diffuse IBL, the texture is sampled with normals in worldspace"," let diffuseIBLCoords = (transpose(rendererUBO.WCVCNormals) * vec4(normal, 1.)).xyz;"," let diffuseCoords = vecToRectCoord(diffuseIBLCoords);"," // To get specular IBL, the texture is sampled as the worldspace reflection between the normal and view vectors"," // Reflections are first calculated in viewspace, then converted to worldspace to sample the environment"," let VreflN = normalize(reflect(-V, normal));"," let reflectionIBLCoords = (transpose(rendererUBO.WCVCNormals) * vec4(VreflN, 1.)).xyz;"," let specularCoords = vecToRectCoord(reflectionIBLCoords);"," let diffuseIBL = textureSampleLevel(EnvironmentTexture, EnvironmentTextureSampler, diffuseCoords, rendererUBO.MaxEnvironmentMipLevel);"," let level = roughness * rendererUBO.MaxEnvironmentMipLevel;"," let specularIBL = textureSampleLevel(EnvironmentTexture, EnvironmentTextureSampler, specularCoords, level);"," let specularIBLContribution = specularIBL.rgb * rendererUBO.BackgroundSpecularStrength;"," computedColor += vec4(specularIBLContribution * kS, 0);"," let diffuseIBLContribution = diffuseIBL.rgb * rendererUBO.BackgroundDiffuseStrength;"," computedColor += vec4(diffuseIBLContribution * baseColor * _ambientOcclusionMap.rgb * kD, 0);"),s=Np.substitute(s,"//VTK::Light::Impl",e).result,a.setCode(s)}},t.shaderReplacements.set("replaceShaderLight",e.replaceShaderLight),e.replaceShaderColor=(e,t,r)=>{if(ph(e)){const e=t.getShaderDescription("fragment");let r=e.getCode();return r=Np.substitute(r,"//VTK::Color::Impl",["ambientColor = mapperUBO.EdgeColor;","diffuseColor = mapperUBO.EdgeColor;"]).result,void e.setCode(r)}const n=r.getBuffer("colorVI");if(!n)return;const o=t.getShaderDescription("vertex");o.addOutput("vec4","color",n.getArrayInformation()[0].interpolation);let i=o.getCode();i=Np.substitute(i,"//VTK::Color::Impl",[" output.color = colorVI;"]).result,o.setCode(i);const a=t.getShaderDescription("fragment");i=a.getCode(),i=Np.substitute(i,"//VTK::Color::Impl",["ambientColor = input.color;","diffuseColor = input.color;","opacity = mapperUBO.Opacity * input.color.a;"]).result,a.setCode(i)},t.shaderReplacements.set("replaceShaderColor",e.replaceShaderColor),e.replaceShaderTCoord=(e,r,n)=>{if(!n.hasAttribute("tcoord"))return;const o=r.getShaderDescription("vertex"),i=n.getBuffer("tcoord"),a=zp(i.getArrayInformation()[0].format);let s=o.getCode();o.addOutput(`vec${a}`,"tcoordVS"),s=Np.substitute(s,"//VTK::TCoord::Impl",[" output.tcoordVS = tcoord;"]).result,o.setCode(s);const l=r.getShaderDescription("fragment");s=l.getCode();const u=t.WebGPUActor.getRenderable(),c=u.getProperty(),d=e=>!!e&&e.getDimensionality()===a,p=[],f=c.getDiffuseTexture?.();(f?.getImageLoaded()||u.getTextures()[0]||t.colorTexture)&&(d(f)||d(u.getTextures()[0])||d(t.colorTexture))&&p.push("_diffuseMap = textureSample(DiffuseTexture, DiffuseTextureSampler, input.tcoordVS);");const h=c.getORMTexture?.(),m=c.getRMTexture?.(),g=c.getRoughnessTexture?.(),y=c.getMetallicTexture?.(),v=c.getAmbientOcclusionTexture?.(),b=c.getEmissionTexture?.(),x=c.getNormalTexture?.();h?.getImageLoaded()?d(h)&&p.push("_ambientOcclusionMap = textureSample(ORMTexture, ORMTextureSampler, input.tcoordVS).rrra;","_roughnessMap = textureSample(ORMTexture, ORMTextureSampler, input.tcoordVS).ggga;","_metallicMap = textureSample(ORMTexture, ORMTextureSampler, input.tcoordVS).bbba;"):m?.getImageLoaded()?d(m)&&p.push("_roughnessMap = textureSample(RMTexture, RMTextureSampler, input.tcoordVS).ggga;","_metallicMap = textureSample(RMTexture, RMTextureSampler, input.tcoordVS).bbba;"):(g?.getImageLoaded()&&d(g)&&p.push("_roughnessMap = textureSample(RoughnessTexture, RoughnessTextureSampler, input.tcoordVS).ggga;"),y?.getImageLoaded()&&d(y)&&p.push("_metallicMap = textureSample(MetallicTexture, MetallicTextureSampler, input.tcoordVS).bbba;"),v?.getImageLoaded()&&d(v)&&p.push("_ambientOcclusionMap = textureSample(AmbientOcclusionTexture, AmbientOcclusionTextureSampler, input.tcoordVS).rrra;")),b?.getImageLoaded()&&d(b)&&p.push("_emissionMap = textureSample(EmissionTexture, EmissionTextureSampler, input.tcoordVS);"),x?.getImageLoaded()&&d(x)&&p.push("_normalMap = textureSample(NormalTexture, NormalTextureSampler, input.tcoordVS);"),s=Np.substitute(s,"//VTK::TCoord::Impl",p).result,l.setCode(s)},t.shaderReplacements.set("replaceShaderTCoord",e.replaceShaderTCoord),e.replaceShaderSelect=(e,t,r)=>{if(e.includes("sel")){const e=t.getShaderDescription("fragment");let r=e.getCode();r=Np.substitute(r,"//VTK::Select::Impl",[" var compositeID: u32 = 0u;"]).result,e.setCode(r)}},t.shaderReplacements.set("replaceShaderSelect",e.replaceShaderSelect),e.getUsage=(e,t)=>e===lh.POINTS||t===sh.Points?ah.Verts:t===sh.Lines?ah.Lines:e===lh.WIREFRAME?t===sh.Triangles?ah.LinesFromTriangles:ah.LinesFromStrips:t===sh.Triangles?ah.Triangles:t===sh.TriangleStrips?ah.Strips:t===sh.TriangleEdges?ah.LinesFromTriangles:ah.LinesFromStrips,e.getHashFromUsage=e=>`pt${e}`,e.getTopologyFromUsage=e=>{switch(e){case ah.Triangles:return"triangle-list";case ah.Verts:return"point-list";case ah.Lines:default:return"line-list"}},e.buildVertexInput=()=>{const r=t.currentInput,n=t.cellArray,o=t.primitiveType;let i=t.WebGPUActor.getRenderable().getProperty().getRepresentation();const a=t.WebGPURenderWindow.getDevice();let s=!1;o===sh.TriangleEdges&&(s=!0,i=lh.WIREFRAME);const l=t.vertexInput,u=r.getPoints();let c=null;if(n?(c=a.getBufferManager().getBuffer({hash:`R${i}P${o}${n.getMTime()}`,usage:ah.Index,cells:n,numberOfPoints:u.getNumberOfPoints(),primitiveType:o,representation:i}),l.setIndexBuffer(c)):l.setIndexBuffer(null),u){const e=t.WebGPUActor.getBufferShift(t.WebGPURenderer);l.addBuffer(a.getBufferManager().getBuffer({hash:`${u.getMTime()}I${c?.getMTime?.()??0}${e.join()}float32x4`,usage:ah.PointArray,format:"float32x4",dataArray:u,indexBuffer:c,shift:e,packExtra:!0}),["vertexBC"])}else l.removeBufferIfPresent("vertexBC");const d=e.getUsage(i,o);if(t._usesCellNormals=!1,t.is2D||d!==ah.Triangles&&d!==ah.Strips)l.removeBufferIfPresent("normalMC");else{const e=r.getPointData().getNormals(),i={format:"snorm8x4",indexBuffer:c,packExtra:!0,shift:0,scale:127};e?(i.hash=`${e.getMTime()}I${c.getMTime()}snorm8x4`,i.dataArray=e,i.usage=ah.PointArray,l.addBuffer(a.getBufferManager().getBuffer(i),["normalMC"])):o===sh.Triangles?(t._usesCellNormals=!0,i.hash=`PFN${u.getMTime()}I${c.getMTime()}snorm8x4`,i.dataArray=u,i.cells=n,i.usage=ah.NormalsFromPoints,l.addBuffer(a.getBufferManager().getBuffer(i),["normalMC"])):l.removeBufferIfPresent("normalMC")}let p=!1;if(t.renderable.getScalarVisibility()){const e=t.renderable.getColorMapColors();if(e&&!s){const n=t.renderable.getScalarMode(),o=(n===uh.USE_CELL_DATA||n===uh.USE_CELL_FIELD_DATA||n===uh.USE_FIELD_DATA||!r.getPointData().getScalars())&&n!==uh.USE_POINT_FIELD_DATA&&e;l.addBuffer(a.getBufferManager().getBuffer({usage:ah.PointArray,format:"unorm8x4",hash:`${o}${e.getMTime()}I${c.getMTime()}unorm8x4`,dataArray:e,indexBuffer:c,cellData:o,cellOffset:0}),["colorVI"]),p=!0}}p||l.removeBufferIfPresent("colorVI");let f=null;f=t.renderable.getInterpolateScalarsBeforeMapping?.()&&t.renderable.getColorCoordinates()?t.renderable.getColorCoordinates():r.getPointData().getTCoords(),f&&!s?l.addBuffer(a.getBufferManager().getBufferForPointArray(f,l.getIndexBuffer()),["tcoord"]):l.removeBufferIfPresent("tcoord")},e.updateTextures=()=>{const e=[],r=[],n=t.renderable.getColorTextureMap?.();n&&!t.colorTexture&&(t.colorTexture=vc.newInstance({label:"polyDataColor"})),n&&(t.colorTexture.setInputData(n),r.push(["DiffuseTexture",t.colorTexture]));const o=t.WebGPUActor.getRenderable(),i=t.WebGPURenderer.getRenderable();[["DiffuseTexture",o.getProperty().getDiffuseTexture?.()],["DiffuseTexture",o.getTextures()[0]],["DiffuseTexture",t.colorTexture],["ORMTexture",o.getProperty().getORMTexture?.()],["RMTexture",o.getProperty().getRMTexture?.()],["RoughnessTexture",o.getProperty().getRoughnessTexture?.()],["MetallicTexture",o.getProperty().getMetallicTexture?.()],["NormalTexture",o.getProperty().getNormalTexture?.()],["AmbientOcclusionTexture",o.getProperty().getAmbientOcclusionTexture?.()],["EmissionTexture",o.getProperty().getEmissionTexture?.()],["EnvironmentTexture",i.getEnvironmentTexture?.()]].forEach(e=>{let[t,n]=e;n&&((n.getInputData()||n.getJsImageData()||n.getCanvas()||n.getImageBitmap())&&r.push([t,n]),n.getImage()&&n.getImageLoaded()&&r.push([t,n]))}),r.forEach(r=>{let[n,o]=r;const i=t.device.getTextureManager().getTextureForVTKTexture(o,n);if(!i.getReady())return;let a=!1;for(let r=0;r=0;r--)e[r]||(t.textures.splice(r,1),t.textureViews.splice(r,1))},e.computePipelineHash=()=>{let r=`pd${t.useRendererMatrix?"r":""}${t.forceZValue?"z":""}`;if(t.primitiveType===sh.TriangleEdges||t.primitiveType===sh.TriangleStripEdges)r+="edge";else{if(t.vertexInput.hasAttribute("normalMC")&&(r+="n"),t.vertexInput.hasAttribute("colorVI")&&(r+="c"),t.vertexInput.hasAttribute("tcoord")){const e=t.vertexInput.getBuffer("tcoord");r+=`t${zp(e.getArrayInformation()[0].format)}`}t.textures.length&&(r+=`tx${t.textures.length}`)}t._usesCellNormals&&(r+="cn"),t.SSBO&&(r+="ssbo"),r+=e.getHashFromUsage(t.usage),r+=t.renderEncoder.getPipelineHash(),t.pipelineHash=r},e.updateBuffers=()=>{t.primitiveType!==sh.TriangleEdges&&t.primitiveType!==sh.TriangleStripEdges&&e.updateTextures();const r=t.WebGPUActor.getRenderable(),n=r.getProperty().getRepresentation();t.usage=e.getUsage(n,t.primitiveType),e.buildVertexInput();const o=t.vertexInput.getBuffer("vertexBC");if(e.setNumberOfVertices(o.getSizeInBytes()/o.getStrideInBytes()),e.setTopology(e.getTopologyFromUsage(t.usage)),e.updateUBO(),e.haveWideLines()){const t=r.getProperty();e.setNumberOfInstances(Math.ceil(2*t.getLineWidth()))}else e.setNumberOfInstances(1)}}(e,t)}var mh={newInstance:Pt(hh,"vtkWebGPUCellArrayMapper"),extend:hh};const{PrimitiveTypes:gh}=If,yh={primitives:null};const vh=Pt(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,yh,r),Xt.extend(e,t,r),t.primitives=[],function(e,t){t.classHierarchy.push("vtkWebGPUPolyDataMapper"),e.createCellArrayMapper=()=>mh.newInstance(),e.buildPass=r=>{if(r){t.WebGPUActor=e.getFirstAncestorOfType("vtkWebGPUActor"),t.renderable.getStatic()||t.renderable.update();const r=t.renderable.getInputData();t.renderable.mapScalars(r,1),e.updateCellArrayMappers(r)}},e.updateCellArrayMappers=r=>{if(!r)return void Ze("No input!");const n=[r.getVerts(),r.getLines(),r.getPolys(),r.getStrips()],o=[];let i=0;for(let a=gh.Points;a<=gh.TriangleStrips;a++)if(n[a].getNumberOfValues()>0){t.primitives[a]||(t.primitives[a]=e.createCellArrayMapper());const s=t.primitives[a];s.setCellArray(n[a]),s.setCurrentInput(r),s.setCellOffset(i),s.setPrimitiveType(a),s.setRenderable(t.renderable),i+=n[a].getNumberOfCells(),o.push(s)}else t.primitives[a]=null;if(t.WebGPUActor.getRenderable().getProperty().getEdgeVisibility()){if(n[gh.Triangles].getNumberOfValues()>0){const i=gh.TriangleEdges;t.primitives[i]||(t.primitives[i]=e.createCellArrayMapper());const a=t.primitives[i];a.setCellArray(n[gh.Triangles]),a.setCurrentInput(r),a.setCellOffset(t.primitives[gh.Triangles].getCellOffset()),a.setPrimitiveType(i),a.setRenderable(t.renderable),o.push(a)}else t.primitives[gh.TriangleEdges]=null;if(n[gh.TriangleStrips].getNumberOfValues()>0){const i=gh.TriangleStripEdges;t.primitives[i]||(t.primitives[i]=e.createCellArrayMapper());const a=t.primitives[i];a.setCellArray(n[gh.TriangleStrips]),a.setCurrentInput(r),a.setCellOffset(t.primitives[gh.TriangleStrips].getCellOffset()),a.setPrimitiveType(i),a.setRenderable(t.renderable),o.push(a)}else t.primitives[gh.TriangleStripEdges]=null}e.prepareNodes(),e.addMissingChildren(o),e.removeUnusedNodes()}}(e,t)},"vtkWebGPUPolyDataMapper");vp("vtkMapper",vh);const{PrimitiveTypes:bh}=If;const xh=Pt(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,function(e){return{primitives:[],...e}}(r)),Xt.extend(e,t,r),t.primitives=[],function(e,t){t.classHierarchy.push("vtkWebGPUPolyDataMapper2D"),e.createCellArrayMapper=()=>mh.newInstance(),e.buildPass=r=>{if(r){t.WebGPUActor=e.getFirstAncestorOfType("vtkWebGPUActor2D"),t.renderable.getStatic()||t.renderable.update();const r=t.renderable.getInputData();t.renderable.mapScalars(r,1),e.updateCellArrayMappers(r)}},e.updateCellArrayMappers=r=>{const n=[r.getVerts(),r.getLines(),r.getPolys(),r.getStrips()],o=[];let i=0;for(let a=bh.Points;a<=bh.Triangles;a++)if(n[a].getNumberOfValues()>0){t.primitives[a]||(t.primitives[a]=e.createCellArrayMapper());const s=t.primitives[a];s.setCellArray(n[a]),s.setCurrentInput(r),s.setCellOffset(i),s.setPrimitiveType(a),s.setRenderable(t.renderable),s.setIs2D(!0),i+=n[a].getNumberOfCells(),o.push(s)}else t.primitives[a]=null;e.prepareNodes(),e.addMissingChildren(o),e.removeUnusedNodes()}}(e,t)},"vtkWebGPUPolyDataMapper2D");vp("vtkMapper2D",xh);const _h={};const Sh=Pt(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,_h,r),Xt.extend(e,t,r),t.scalarBarActorHelper=lp.newScalarBarActorHelper(),function(e,t){t.classHierarchy.push("vtkWebGPUScalarBarActor"),e.buildPass=r=>{r&&(t.WebGPURenderer=e.getFirstAncestorOfType("vtkWebGPURenderer"),t.WebGPURenderWindow=t.WebGPURenderer.getParent(),t.scalarBarActorHelper.getRenderable()||t.scalarBarActorHelper.setRenderable(t.renderable),e.prepareNodes(),e.addMissingNode(t.scalarBarActorHelper.getBarActor()),e.addMissingNode(t.scalarBarActorHelper.getTmActor()),e.removeUnusedNodes())},e.opaquePass=(e,r)=>{if(e){const e=t.WebGPURenderer?t.WebGPURenderer.getRenderable().getActiveCamera():null,r=t.WebGPURenderer.getTiledSizeAndOrigin();t.scalarBarActorHelper.updateAPISpecificData([r.usize,r.vsize],e,t.WebGPURenderWindow.getRenderable())}}}(e,t)},"vtkWebGPUScalarBarActor");vp("vtkScalarBarActor",Sh);const Ch={device:null,handle:null,label:null,options:null};function Th(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Ch,r),zt.obj(e,t),t.options={},t.bindGroupLayoutEntry={visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,sampler:{}},t.bindGroupTime={},zt.obj(t.bindGroupTime,{mtime:0}),zt.get(e,t,["bindGroupTime","handle","options"]),zt.setGet(e,t,["bindGroupLayoutEntry","device","label"]),function(e,t){t.classHierarchy.push("vtkWebGPUSampler"),e.create=function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t.device=e,t.options.addressModeU=r.addressModeU?r.addressModeU:"clamp-to-edge",t.options.addressModeV=r.addressModeV?r.addressModeV:"clamp-to-edge",t.options.addressModeW=r.addressModeW?r.addressModeW:"clamp-to-edge",t.options.magFilter=r.magFilter?r.magFilter:"nearest",t.options.minFilter=r.minFilter?r.minFilter:"nearest",t.options.mipmapFilter=r.mipmapFilter?r.mipmapFilter:"nearest",t.options.label=t.label,t.handle=t.device.getHandle().createSampler(t.options),t.bindGroupTime.modified()},e.getShaderCode=(e,r)=>`@binding(${e}) @group(${r}) var ${t.label}: sampler;`,e.getBindGroupEntry=()=>({resource:t.handle})}(e,t)}var wh={newInstance:zt.newInstance(Th),extend:Th};const Ah={texture:null,handle:null,sampler:null,label:null};function Eh(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Ah,r),zt.obj(e,t),t.bindGroupLayoutEntry={visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d"}},t.bindGroupTime={},zt.obj(t.bindGroupTime,{mtime:0}),zt.get(e,t,["bindGroupTime","texture"]),zt.setGet(e,t,["bindGroupLayoutEntry","label","sampler"]),function(e,t){t.classHierarchy.push("vtkWebGPUTextureView"),e.create=(e,r)=>{t.texture=e,t.options=r,t.options.dimension=t.options.dimension||"2d",t.options.label=t.label,t.textureHandle=e.getHandle(),t.handle=t.textureHandle.createView(t.options),t.bindGroupLayoutEntry.texture.viewDimension=t.options.dimension;const n=Vp(t.texture.getFormat());t.bindGroupLayoutEntry.texture.sampleType=n.sampleType},e.createFromTextureHandle=(e,r)=>{t.texture=null,t.options=r,t.options.dimension=t.options.dimension||"2d",t.options.label=t.label,t.textureHandle=e,t.handle=t.textureHandle.createView(t.options),t.bindGroupLayoutEntry.texture.viewDimension=t.options.dimension;const n=Vp(r.format);t.bindGroupLayoutEntry.texture.sampleType=n.sampleType,t.bindGroupTime.modified()},e.getBindGroupEntry=()=>({resource:e.getHandle()}),e.getShaderCode=(e,r)=>{let n="f32";"sint"===t.bindGroupLayoutEntry.texture.sampleType?n="i32":"uint"===t.bindGroupLayoutEntry.texture.sampleType&&(n="u32");let o=`@binding(${e}) @group(${r}) var ${t.label}: texture_${t.options.dimension}<${n}>;`;return"depth"===t.bindGroupLayoutEntry.texture.sampleType&&(o=`@binding(${e}) @group(${r}) var ${t.label}: texture_depth_${t.options.dimension};`),o},e.addSampler=(r,n)=>{const o=wh.newInstance({label:`${t.label}Sampler`});o.create(r,n),e.setSampler(o)},e.getBindGroupTime=()=>(t.texture&&t.texture.getHandle()!==t.textureHandle&&(t.textureHandle=t.texture.getHandle(),t.handle=t.textureHandle.createView(t.options),t.bindGroupTime.modified()),t.bindGroupTime),e.getHandle=()=>(t.texture&&t.texture.getHandle()!==t.textureHandle&&(t.textureHandle=t.texture.getHandle(),t.handle=t.textureHandle.createView(t.options),t.bindGroupTime.modified()),t.handle)}(e,t)}var Dh={newInstance:zt.newInstance(Eh),extend:Eh};const Ph={device:null,handle:null,buffer:null,ready:!1,label:null};function Ih(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Ph,r),zt.obj(e,t),zt.get(e,t,["handle","ready","width","height","depth","format","usage"]),zt.setGet(e,t,["device","label"]),function(e,t){t.classHierarchy.push("vtkWebGPUTexture"),e.create=(e,r)=>{t.device=e,t.width=r.width,t.height=r.height,t.depth=r.depth?r.depth:1;const n=1===t.depth?"2d":"3d";t.format=r.format?r.format:"rgba8unorm",t.mipLevel=r.mipLevel?r.mipLevel:0,t.usage=r.usage?r.usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST,t.handle=t.device.getHandle().createTexture({size:[t.width,t.height,t.depth],format:t.format,usage:t.usage,label:t.label,dimension:n,mipLevelCount:t.mipLevel+1})},e.assignFromHandle=(e,r,n)=>{t.device=e,t.handle=r,t.width=n.width,t.height=n.height,t.depth=n.depth?n.depth:1,t.format=n.format?n.format:"rgba8unorm",t.usage=n.usage?n.usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST},e.writeImageData=r=>{let n=[];const o=n=>{t.device.getHandle().queue.copyExternalImageToTexture({source:n,flipY:r.flip},{texture:t.handle,premultipliedAlpha:!0,mipLevel:0,origin:{x:0,y:0,z:0}},[n.width,n.height,t.depth]),3!==e.getDimensionality()&&t.mipLevel>0&&vc.generateMipmaps(t.device.getHandle(),t.handle,t.mipLevel+1),t.ready=!0};if(r.canvas)return void o(r.canvas);if(r.imageBitmap)return r.width=r.imageBitmap.width,r.height=r.imageBitmap.height,r.depth=1,r.format="rgba8unorm",r.flip=!0,void o(r.imageBitmap);if(r.jsImageData)return r.width=r.jsImageData.width,r.height=r.jsImageData.height,r.depth=1,r.format="rgba8unorm",r.flip=!0,void o(r.jsImageData);if(r.image)return r.width=r.image.width,r.height=r.image.height,r.depth=1,r.format="rgba8unorm",r.flip=!0,void o(r.image);const i=Vp(t.format);let a=t.width*i.stride;r.nativeArray&&(n=r.nativeArray);const s=3===e.getDimensionality(),l=((e,t,r)=>{const n=2===i.elementSize&&"float"===i.sampleType,o=e.BYTES_PER_ELEMENT,a=e.length/(t*r)*o;if(!n&&a%256==0)return[e,a];const s=a/o,l=i.elementSize,u=256*Math.floor((s*l+255)/256),c=u/l,d=zt.newTypedArray(n?"Uint16Array":e.constructor.name,c*t*r),p=t*r;if(n)for(let t=0;t0&&vc.generateMipmaps(t.device.getHandle(),t.handle,t.mipLevel+1),t.ready=!0},e.getScale=()=>{const e=Vp(t.format);return 2===e.elementSize&&"float"===e.sampleType?1:255},e.getNumberOfComponents=()=>Vp(t.format).numComponents,e.getDimensionality=()=>{let e=0;return t.width>1&&e++,t.height>1&&e++,t.depth>1&&e++,e},e.resizeToMatch=e=>{e.getWidth()===t.width&&e.getHeight()===t.height&&e.getDepth()===t.depth||(t.width=e.getWidth(),t.height=e.getHeight(),t.depth=e.getDepth(),t.handle=t.device.getHandle().createTexture({size:[t.width,t.height,t.depth],format:t.format,usage:t.usage,label:t.label}))},e.resize=function(e,r){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;e===t.width&&r===t.height&&n===t.depth||(t.width=e,t.height=r,t.depth=n,t.handle=t.device.getHandle().createTexture({size:[t.width,t.height,t.depth],format:t.format,usage:t.usage,label:t.label}))},e.createView=function(r){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};n.dimension||(n.dimension=1===t.depth?"2d":"3d");const o=Dh.newInstance({label:r});return o.create(e,n),o}}(e,t)}var Oh={newInstance:zt.newInstance(Ih),extend:Ih};const Nh={};const Mh=zt.newInstance(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Nh,r),Xt.extend(e,t,r),function(e,t){t.classHierarchy.push("vtkWebGPUPixelSpaceCallbackMapper"),e.opaquePass=(r,n)=>{t.WebGPURenderer=e.getFirstAncestorOfType("vtkWebGPURenderer"),t.WebGPURenderWindow=t.WebGPURenderer.getParent();const o=t.WebGPURenderer.getAspectRatio(),i=t.WebGPURenderer?t.WebGPURenderer.getRenderable().getActiveCamera():null,a=t.WebGPURenderer.getTiledSizeAndOrigin();t.renderable.getUseZValues(),t.renderable.invokeCallback(t.renderable.getInputData(),i,o,a,null)}}(e,t)},"vtkWebGPUPixelSpaceCallbackMapper");vp("vtkPixelSpaceCallbackMapper",Mh);const{vtkDebugMacro:Rh}=zt,Fh={position:[0,0,1],focalPoint:[0,0,0],viewUp:[0,1,0],directionOfProjection:[0,0,-1],parallelProjection:!1,useHorizontalViewAngle:!1,viewAngle:30,parallelScale:1,clippingRange:[.01,1000.01],windowCenter:[0,0],viewPlaneNormal:[0,0,1],useOffAxisProjection:!1,screenBottomLeft:[-.5,-.5,-.5],screenBottomRight:[.5,-.5,-.5],screenTopRight:[.5,.5,-.5],freezeFocalPoint:!1,projectionMatrix:null,viewMatrix:null,modelTransformMatrix:null,cameraLightTransform:u(),physicalTranslation:[0,0,0],physicalScale:1,physicalViewUp:[0,1,0],physicalViewNorth:[0,0,-1]};function Bh(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Fh,r),zt.obj(e,t),zt.get(e,t,["distance"]),zt.setGet(e,t,["parallelProjection","useHorizontalViewAngle","viewAngle","parallelScale","useOffAxisProjection","freezeFocalPoint","physicalScale"]),zt.getArray(e,t,["directionOfProjection","viewPlaneNormal","position","focalPoint"]),zt.setGetArray(e,t,["clippingRange","windowCenter"],2),zt.setGetArray(e,t,["viewUp","screenBottomLeft","screenBottomRight","screenTopRight","physicalTranslation","physicalViewUp","physicalViewNorth"],3),function(e,t){t.classHierarchy.push("vtkCamera");const r=new Float64Array(3),n=new Float64Array([0,0,-1]),o=new Float64Array([0,1,0]),i=h(new Float64Array(16)),a=h(new Float64Array(16)),s=new Float64Array(3),l=new Float64Array(3),u=new Float64Array(3),c=h(new Float64Array(16)),p=h(new Float64Array(16)),f=new Float64Array(3),y=new Float64Array(3);function v(){t.viewPlaneNormal[0]=-t.directionOfProjection[0],t.viewPlaneNormal[1]=-t.directionOfProjection[1],t.viewPlaneNormal[2]=-t.directionOfProjection[2]}e.orthogonalizeViewUp=()=>{const r=e.getViewMatrix();t.viewUp[0]=r[4],t.viewUp[1]=r[5],t.viewUp[2]=r[6],e.modified()},e.setPosition=(r,n,o)=>{r===t.position[0]&&n===t.position[1]&&o===t.position[2]||(t.position[0]=r,t.position[1]=n,t.position[2]=o,e.computeDistance(),e.modified())},e.setFocalPoint=(r,n,o)=>{r===t.focalPoint[0]&&n===t.focalPoint[1]&&o===t.focalPoint[2]||(t.focalPoint[0]=r,t.focalPoint[1]=n,t.focalPoint[2]=o,e.computeDistance(),e.modified())},e.setDistance=r=>{if(t.distance===r)return;t.distance=r,t.distance<1e-20&&(t.distance=1e-20,Rh("Distance is set to minimum."));const n=t.directionOfProjection;t.focalPoint[0]=t.position[0]+n[0]*t.distance,t.focalPoint[1]=t.position[1]+n[1]*t.distance,t.focalPoint[2]=t.position[2]+n[2]*t.distance,e.modified()},e.computeDistance=()=>{const e=t.focalPoint[0]-t.position[0],r=t.focalPoint[1]-t.position[1],n=t.focalPoint[2]-t.position[2];if(t.distance=Math.sqrt(e*e+r*r+n*n),t.distance<1e-20){t.distance=1e-20,Rh("Distance is set to minimum.");const e=t.directionOfProjection;t.focalPoint[0]=t.position[0]+e[0]*t.distance,t.focalPoint[1]=t.position[1]+e[1]*t.distance,t.focalPoint[2]=t.position[2]+e[2]*t.distance}t.directionOfProjection[0]=e/t.distance,t.directionOfProjection[1]=r/t.distance,t.directionOfProjection[2]=n/t.distance,v()},e.dolly=r=>{if(r<=0)return;const n=t.distance/r;e.setPosition(t.focalPoint[0]-n*t.directionOfProjection[0],t.focalPoint[1]-n*t.directionOfProjection[1],t.focalPoint[2]-n*t.directionOfProjection[2])},e.roll=r=>{const n=t.position,o=t.focalPoint,i=t.viewUp,a=new Float64Array([i[0],i[1],i[2],0]);h(c);const s=new Float64Array([o[0]-n[0],o[1]-n[1],o[2]-n[2]]);S(c,c,yo(r),s),Ni(a,a,c),t.viewUp[0]=a[0],t.viewUp[1]=a[1],t.viewUp[2]=a[2],e.modified()},e.azimuth=r=>{const n=t.focalPoint;h(p),x(p,p,n),S(p,p,yo(r),t.viewUp),x(p,p,[-n[0],-n[1],-n[2]]),Sr(f,t.position,p),e.setPosition(f[0],f[1],f[2])},e.yaw=r=>{const n=t.position;h(p),x(p,p,n),S(p,p,yo(r),t.viewUp),x(p,p,[-n[0],-n[1],-n[2]]),Sr(y,t.focalPoint,p),e.setFocalPoint(y[0],y[1],y[2])},e.elevation=r=>{const n=t.focalPoint,o=e.getViewMatrix(),i=[-o[0],-o[1],-o[2]];h(p),x(p,p,n),S(p,p,yo(r),i),x(p,p,[-n[0],-n[1],-n[2]]),Sr(f,t.position,p),e.setPosition(f[0],f[1],f[2])},e.pitch=r=>{const n=t.position,o=e.getViewMatrix(),i=[o[0],o[1],o[2]];h(p),x(p,p,n),S(p,p,yo(r),i),x(p,p,[-n[0],-n[1],-n[2]]),Sr(y,t.focalPoint,p),e.setFocalPoint(...y)},e.zoom=r=>{r<=0||(t.parallelProjection?t.parallelScale/=r:t.viewAngle/=r,e.modified())},e.translate=(r,n,o)=>{const i=[r,n,o];Po(t.position,i,t.position),Po(t.focalPoint,i,t.focalPoint),e.computeDistance(),e.modified()},e.applyTransform=r=>{const n=[...t.viewUp,1],o=[],i=[],a=[];n[0]+=t.position[0],n[1]+=t.position[1],n[2]+=t.position[2],Ni(o,[...t.position,1],r),Ni(i,[...t.focalPoint,1],r),Ni(a,n,r),a[0]-=o[0],a[1]-=o[1],a[2]-=o[2],e.setPosition(...o.slice(0,3)),e.setFocalPoint(...i.slice(0,3)),e.setViewUp(...a.slice(0,3))},e.getThickness=()=>t.clippingRange[1]-t.clippingRange[0],e.setThickness=r=>{let n=r;n<1e-20&&(n=1e-20,Rh("Thickness is set to minimum.")),e.setClippingRange(t.clippingRange[0],t.clippingRange[0]+n)},e.setThicknessFromFocalPoint=r=>{let n=r;n<1e-20&&(n=1e-20,Rh("Thickness is set to minimum.")),e.setClippingRange(t.distance-n/2,t.distance+n/2)},e.setRoll=e=>{},e.getRoll=()=>{},e.setObliqueAngles=(e,t)=>{},e.getOrientation=()=>{},e.getOrientationWXYZ=()=>{},e.getFrustumPlanes=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new Float64Array(24);const n=[[1,0,0,1],[-1,0,0,1],[0,1,0,1],[0,-1,0,1],[0,0,1,1],[0,0,-1,1]],o=e.getCompositeProjectionMatrix(t,-1,1);for(let e=0;e<6;e++)Ni(n[e],n[e],o),ko(n[e]),r[4*e+0]=n[e][0],r[4*e+1]=n[e][1],r[4*e+2]=n[e][2],r[4*e+3]=n[e][3];return r},e.getCameraLightTransformMatrix=e=>(d(e,t.cameraLightTransform),e),e.computeCameraLightTransform=()=>{d(i,e.getViewMatrix()),g(i,i),E(a,[t.distance,t.distance,t.distance]),b(i,i,a),h(t.cameraLightTransform),x(t.cameraLightTransform,i,[0,0,-1])},e.deepCopy=e=>{},e.physicalOrientationToWorldDirection=e=>{const t=ki(e[0],e[1],e[2],e[3]),r=Mi(),n=ki(0,0,1,0);var o,i;return i=t,(o=r)[0]=-i[0],o[1]=-i[1],o[2]=-i[2],o[3]=i[3],Bi(n,t,n),Bi(n,n,r),[n[0],n[1],n[2]]},e.getPhysicalToWorldMatrix=t=>{e.getWorldToPhysicalMatrix(t),g(t,t)},e.getWorldToPhysicalMatrix=e=>{h(e);const r=[3];Fo(t.physicalViewNorth,t.physicalViewUp,r),e[0]=r[0],e[1]=r[1],e[2]=r[2],e[4]=t.physicalViewUp[0],e[5]=t.physicalViewUp[1],e[6]=t.physicalViewUp[2],e[8]=-t.physicalViewNorth[0],e[9]=-t.physicalViewNorth[1],e[10]=-t.physicalViewNorth[2],m(e,e),mr(s,1/t.physicalScale,1/t.physicalScale,1/t.physicalScale),_(e,e,s),x(e,e,t.physicalTranslation)},e.computeViewParametersFromViewMatrix=a=>{g(i,a),Sr(s,r,i),e.computeDistance();const c=t.distance;e.setPosition(s[0],s[1],s[2]),Sr(l,n,i),yr(l,l,s),br(l,l),e.setDirectionOfProjection(l[0],l[1],l[2]),Sr(u,o,i),yr(u,u,s),br(u,u),e.setViewUp(u[0],u[1],u[2]),e.setDistance(c)},e.computeViewParametersFromPhysicalMatrix=t=>{e.getWorldToPhysicalMatrix(i),b(i,t,i),e.computeViewParametersFromViewMatrix(i)},e.setModelTransformMatrix=e=>{t.modelTransformMatrix=e},e.getModelTransformMatrix=()=>t.modelTransformMatrix,e.setViewMatrix=r=>{t.viewMatrix=r,t.viewMatrix&&(d(i,t.viewMatrix),e.computeViewParametersFromViewMatrix(i),m(t.viewMatrix,t.viewMatrix))},e.getViewMatrix=()=>{if(t.viewMatrix)return t.modelTransformMatrix?(b(i,t.viewMatrix,t.modelTransformMatrix),i):t.viewMatrix;$(i,t.position,t.focalPoint,t.viewUp),m(i,i);const e=new Float64Array(16);return t.modelTransformMatrix?b(e,i,t.modelTransformMatrix):d(e,i),e},e.setProjectionMatrix=e=>{t.projectionMatrix=e},e.getProjectionMatrix=(e,r,n)=>{const o=new Float64Array(16);if(h(o),t.projectionMatrix){const e=1/t.physicalScale;return mr(s,e,e,e),d(o,t.projectionMatrix),_(o,o,s),m(o,o),o}h(i);const a=t.clippingRange[1]-t.clippingRange[0],l=[t.clippingRange[0]+(r+1)*a/2,t.clippingRange[0]+(n+1)*a/2];if(t.parallelProjection){const r=t.parallelScale*e,n=t.parallelScale,o=(t.windowCenter[0]-1)*r,a=(t.windowCenter[0]+1)*r,s=(t.windowCenter[1]-1)*n,u=(t.windowCenter[1]+1)*n;K(i,o,a,s,u,l[0],l[1]),m(i,i)}else{if(t.useOffAxisProjection)throw new Error("Off-Axis projection is not supported at this time");{const r=Math.tan(yo(t.viewAngle)/2);let n,o;!0===t.useHorizontalViewAngle?(n=t.clippingRange[0]*r,o=t.clippingRange[0]*r/e):(n=t.clippingRange[0]*r*e,o=t.clippingRange[0]*r);const a=(t.windowCenter[0]-1)*n,s=(t.windowCenter[0]+1)*n,u=(t.windowCenter[1]-1)*o,c=(t.windowCenter[1]+1)*o,d=l[0],p=l[1];i[0]=2*d/(s-a),i[5]=2*d/(c-u),i[2]=(a+s)/(s-a),i[6]=(u+c)/(c-u),i[10]=-(d+p)/(p-d),i[14]=-1,i[11]=-2*d*p/(p-d),i[15]=0}}return d(o,i),o},e.getCompositeProjectionMatrix=(t,r,n)=>{const o=e.getViewMatrix(),i=e.getProjectionMatrix(t,r,n);return b(i,o,i),i},e.setDirectionOfProjection=(e,r,n)=>{if(t.directionOfProjection[0]===e&&t.directionOfProjection[1]===r&&t.directionOfProjection[2]===n)return;t.directionOfProjection[0]=e,t.directionOfProjection[1]=r,t.directionOfProjection[2]=n;const o=t.directionOfProjection;t.focalPoint[0]=t.position[0]+o[0]*t.distance,t.focalPoint[1]=t.position[1]+o[1]*t.distance,t.focalPoint[2]=t.position[2]+o[2]*t.distance,v()},e.setDeviceAngles=(r,n,o,i)=>{const a=[3];Fo(t.physicalViewNorth,t.physicalViewUp,a);const s=h(new Float64Array(16));S(s,s,yo(r),t.physicalViewUp),S(s,s,yo(n),a),S(s,s,yo(o),t.physicalViewNorth),S(s,s,yo(-i),t.physicalViewUp);const l=new Float64Array([-t.physicalViewUp[0],-t.physicalViewUp[1],-t.physicalViewUp[2]]),u=new Float64Array(t.physicalViewNorth);Sr(l,l,s),Sr(u,u,s),e.setDirectionOfProjection(l[0],l[1],l[2]),e.setViewUp(u[0],u[1],u[2]),e.modified()},e.setOrientationWXYZ=(t,r,n,o)=>{const i=h(new Float64Array(16));if(0!==t&&(0!==r||0!==n||0!==o)){const e=yo(t),a=Mi();Ri(a,[r,n,o],e),U(i,a)}const a=new Float64Array(3);Sr(a,[0,0,-1],i);const s=new Float64Array(3);Sr(s,[0,1,0],i),e.setDirectionOfProjection(...a),e.setViewUp(...s),e.modified()},e.computeClippingRange=e=>{let r=null,n=null;r=t.viewPlaneNormal,n=t.position;const o=-r[0],i=-r[1],a=-r[2],s=-(o*n[0]+i*n[1]+a*n[2]),l=[o*e[0]+i*e[2]+a*e[4]+s,1e-18];for(let t=0;t<2;t++)for(let r=0;r<2;r++)for(let n=0;n<2;n++){const u=o*e[n]+i*e[2+r]+a*e[4+t]+s;l[0]=ul[1]?u:l[1]}return l}}(e,t)}var Lh={newInstance:zt.newInstance(Bh,"vtkCamera"),extend:Bh};const kh={switch:!0,intensity:1,color:[1,1,1],position:[0,0,1],focalPoint:[0,0,0],positional:!1,exponent:1,coneAngle:30,coneFalloff:5,attenuationValues:[1,0,0],transformMatrix:null,lightType:"SceneLight",shadowAttenuation:1,direction:[0,0,0],directionMTime:0};function Uh(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,kh,r),zt.obj(e,t),zt.setGet(e,t,["intensity","switch","positional","exponent","coneAngle","coneFalloff","transformMatrix","lightType","shadowAttenuation","attenuationValues"]),zt.setGetArray(e,t,["color","position","focalPoint","attenuationValues"],3),function(e,t){t.classHierarchy.push("vtkLight");const r=new Float64Array(3);e.getTransformedPosition=()=>(t.transformMatrix?Sr(r,t.position,t.transformMatrix):mr(r,t.position[0],t.position[1],t.position[2]),r),e.getTransformedFocalPoint=()=>(t.transformMatrix?Sr(r,t.focalPoint,t.transformMatrix):mr(r,t.focalPoint[0],t.focalPoint[1],t.focalPoint[2]),r),e.getDirection=()=>(t.directionMTime{const r=new Float64Array(3);wr(r,t.position,e),t.focalPoint=r},e.setDirectionAngle=(t,r)=>{const n=yo(t),o=yo(r);e.setPosition(Math.cos(n)*Math.sin(o),Math.sin(n),Math.cos(n)*Math.cos(o)),e.setFocalPoint(0,0,0),e.setPositional(0)},e.setLightTypeToHeadLight=()=>{e.setLightType("HeadLight")},e.setLightTypeToCameraLight=()=>{e.setLightType("CameraLight")},e.setLightTypeToSceneLight=()=>{e.setTransformMatrix(null),e.setLightType("SceneLight")},e.lightTypeIsHeadLight=()=>"HeadLight"===t.lightType,e.lightTypeIsSceneLight=()=>"SceneLight"===t.lightType,e.lightTypeIsCameraLight=()=>"CameraLight"===t.lightType}(e,t)}var Vh={newInstance:zt.newInstance(Uh,"vtkLight"),extend:Uh,LIGHT_TYPES:["HeadLight","CameraLight","SceneLight"]};const{vtkErrorMacro:Gh}=zt;const zh={background:[0,0,0],background2:[.2,.2,.2],gradientBackground:!1,viewport:[0,0,1,1],aspect:[1,1],pixelAspect:[1,1],props:[],actors2D:[]};function jh(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,zh,r),zt.obj(e,t),zt.event(e,t,"event"),zt.setGetArray(e,t,["viewport"],4),zt.setGetArray(e,t,["background","background2"],3),function(e,t){function r(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];t.push(e);const n=e.getNestedProps();if(n&&n.length)for(let e=0;et.props,e.hasViewProp=e=>t.props.includes(e),e.addViewProp=r=>{r&&!e.hasViewProp(r)&&t.props.push(r)},e.removeViewProp=e=>{const r=t.props.filter(t=>t!==e);t.props.length!==r.length&&(t.props=r)},e.removeAllViewProps=()=>{t.props=[]},e.getViewPropsWithNestedProps=()=>{let e=[];t.actors2D=[];for(let n=0;n0)?t.actors2D=t.actors2D.concat(o):r(t.props[n],e)}return t.actors2D.sort((e,t)=>e.getLayerNumber()-t.getLayerNumber()),e=e.concat(t.actors2D),e},e.addActor2D=e.addViewProp,e.removeActor2D=t=>{e.removeViewProp(t)},e.getActors2D=()=>(t.actors2D=[],t.props.forEach(e=>{t.actors2D=t.actors2D.concat(e.getActors2D())}),t.actors2D),e.displayToView=()=>Gh("call displayToView on your view instead"),e.viewToDisplay=()=>Gh("callviewtodisplay on your view instead"),e.getSize=()=>Gh("call getSize on your View instead"),e.normalizedDisplayToProjection=(t,r,n)=>{const o=e.normalizedDisplayToNormalizedViewport(t,r,n);return e.normalizedViewportToProjection(o[0],o[1],o[2])},e.normalizedDisplayToNormalizedViewport=(e,r,n)=>{const o=[t.viewport[2]-t.viewport[0],t.viewport[3]-t.viewport[1]];return[(e-t.viewport[0])/o[0],(r-t.viewport[1])/o[1],n]},e.normalizedViewportToProjection=(e,t,r)=>[2*e-1,2*t-1,2*r-1],e.projectionToNormalizedDisplay=(t,r,n)=>{const o=e.projectionToNormalizedViewport(t,r,n);return e.normalizedViewportToNormalizedDisplay(o[0],o[1],o[2])},e.normalizedViewportToNormalizedDisplay=(e,r,n)=>{const o=[t.viewport[2]-t.viewport[0],t.viewport[3]-t.viewport[1]];return[e*o[0]+t.viewport[0],r*o[1]+t.viewport[1],n]},e.projectionToNormalizedViewport=(e,t,r)=>[.5*(e+1),.5*(t+1),.5*(r+1)],e.PickPropFrom=()=>Gh("vtkViewport::PickPropFrom - NOT IMPLEMENTED")}(e,t)}var Wh={newInstance:zt.newInstance(jh,"vtkViewport"),extend:jh};const{vtkDebugMacro:Hh,vtkErrorMacro:Kh,vtkWarningMacro:Xh}=jt;function $h(e){return()=>Kh(`vtkRenderer::${e} - NOT IMPLEMENTED`)}const qh={pickedProp:null,activeCamera:null,allBounds:[],ambient:[1,1,1],allocatedRenderTime:100,timeFactor:1,automaticLightCreation:!0,twoSidedLighting:!0,lastRenderTimeInSeconds:-1,renderWindow:null,lights:[],actors:[],volumes:[],lightFollowCamera:!0,numberOfPropsRendered:0,propArray:null,pathArray:null,layer:0,preserveColorBuffer:!1,preserveDepthBuffer:!1,computeVisiblePropBounds:Ei(),interactive:!0,nearClippingPlaneTolerance:0,clippingRangeExpansion:.05,erase:!0,draw:!0,useShadows:!1,useDepthPeeling:!1,occlusionRatio:0,maximumNumberOfPeels:4,selector:null,delegate:null,texturedBackground:!1,backgroundTexture:null,environmentTexture:null,environmentTextureDiffuseStrength:1,environmentTextureSpecularStrength:1,useEnvironmentTextureAsBackground:!1,pass:0};function Yh(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};for(Object.assign(t,qh,r),Wh.extend(e,t,r),t.background||(t.background=[0,0,0,1]);t.background.length<3;)t.background.push(0);3===t.background.length&&t.background.push(1),yt(e,t,["_renderWindow","allocatedRenderTime","timeFactor","lastRenderTimeInSeconds","numberOfPropsRendered","lastRenderingUsedDepthPeeling","selector"]),_t(e,t,["twoSidedLighting","lightFollowCamera","automaticLightCreation","erase","draw","nearClippingPlaneTolerance","clippingRangeExpansion","backingStore","interactive","layer","preserveColorBuffer","preserveDepthBuffer","useDepthPeeling","occlusionRatio","maximumNumberOfPeels","delegate","backgroundTexture","texturedBackground","environmentTexture","environmentTextureDiffuseStrength","environmentTextureSpecularStrength","useEnvironmentTextureAsBackground","useShadows","pass"]),St(e,t,["actors","volumes","lights"]),Tt(e,t,["background"],4,1),wt(0,t,["renderWindow"]),function(e,t){t.classHierarchy.push("vtkRenderer");const r={type:"ComputeVisiblePropBoundsEvent",renderer:e},n={type:"ResetCameraClippingRangeEvent",renderer:e},o={type:"ResetCameraEvent",renderer:e};e.updateCamera=()=>(t.activeCamera||(Hh("No cameras are on, creating one."),e.getActiveCameraAndResetIfCreated()),t.activeCamera.render(e),!0),e.updateLightsGeometryToFollowCamera=()=>{const r=e.getActiveCameraAndResetIfCreated();t.lights.forEach(e=>{e.lightTypeIsSceneLight()||(e.lightTypeIsHeadLight()?(e.setPositionFrom(r.getPositionByReference()),e.setFocalPointFrom(r.getFocalPointByReference()),e.modified(r.getMTime())):e.lightTypeIsCameraLight()?e.setTransformMatrix(r.getCameraLightTransformMatrix(u())):Kh("light has unknown light type",e.get()))})},e.updateLightGeometry=()=>!t.lightFollowCamera||e.updateLightsGeometryToFollowCamera(),e.allocateTime=$h("allocateTime"),e.updateGeometry=$h("updateGeometry"),e.getVTKWindow=()=>t._renderWindow,e.setLayer=r=>{Hh(e.getClassName(),e,"setting Layer to ",r),t.layer!==r&&(t.layer=r,e.modified()),e.setPreserveColorBuffer(!!r)},e.setActiveCamera=r=>t.activeCamera!==r&&(t.activeCamera=r,e.modified(),e.invokeEvent({type:"ActiveCameraEvent",camera:r}),!0),e.makeCamera=()=>{const t=Lh.newInstance();return e.invokeEvent({type:"CreateCameraEvent",camera:t}),t},e.getActiveCamera=()=>(t.activeCamera||(t.activeCamera=e.makeCamera()),t.activeCamera),e.getActiveCameraAndResetIfCreated=()=>(t.activeCamera||(e.getActiveCamera(),e.resetCamera()),t.activeCamera),e.getActors=()=>(t.actors=[],t.props.forEach(e=>{t.actors=t.actors.concat(e.getActors())}),t.actors),e.addActor=e.addViewProp,e.removeActor=r=>{t.actors=t.actors.filter(e=>e!==r),e.removeViewProp(r),e.modified()},e.removeAllActors=()=>{e.getActors().forEach(t=>{e.removeViewProp(t)}),t.actors=[],e.modified()},e.getVolumes=()=>(t.volumes=[],t.props.forEach(e=>{t.volumes=t.volumes.concat(e.getVolumes())}),t.volumes),e.addVolume=e.addViewProp,e.removeVolume=r=>{t.volumes=t.volumes.filter(e=>e!==r),e.removeViewProp(r),e.modified()},e.removeAllVolumes=()=>{e.getVolumes().forEach(t=>{e.removeViewProp(t)}),t.volumes=[],e.modified()},e.hasLight=e=>t.lights.includes(e),e.addLight=r=>{r&&!e.hasLight(r)&&(t.lights.push(r),e.modified())},e.removeLight=r=>{t.lights=t.lights.filter(e=>e!==r),e.modified()},e.removeAllLights=()=>{t.lights=[],e.modified()},e.setLightCollection=r=>{t.lights=r,e.modified()},e.makeLight=Vh.newInstance,e.createLight=()=>{t.automaticLightCreation&&(t._createdLight&&(e.removeLight(t._createdLight),t._createdLight.delete(),t._createdLight=null),t._createdLight=e.makeLight(),e.addLight(t._createdLight),t._createdLight.setLightTypeToHeadLight(),t._createdLight.setPosition(e.getActiveCamera().getPosition()),t._createdLight.setFocalPoint(e.getActiveCamera().getFocalPoint()))},e.normalizedDisplayToWorld=(t,r,n,o)=>{let i=e.normalizedDisplayToProjection(t,r,n);return i=e.projectionToView(i[0],i[1],i[2],o),e.viewToWorld(i[0],i[1],i[2])},e.worldToNormalizedDisplay=(t,r,n,o)=>{let i=e.worldToView(t,r,n);return i=e.viewToProjection(i[0],i[1],i[2],o),e.projectionToNormalizedDisplay(i[0],i[1],i[2])},e.viewToWorld=(e,r,n)=>{if(null===t.activeCamera)return Kh("ViewToWorld: no active camera, cannot compute view to world, returning 0,0,0"),[0,0,0];const o=t.activeCamera.getViewMatrix();g(o,o),m(o,o);const i=new Float64Array([e,r,n]);return Sr(i,i,o),i},e.projectionToView=(e,r,n,o)=>{if(null===t.activeCamera)return Kh("ProjectionToView: no active camera, cannot compute projection to view, returning 0,0,0"),[0,0,0];const i=t.activeCamera.getProjectionMatrix(o,-1,1);g(i,i),m(i,i);const a=new Float64Array([e,r,n]);return Sr(a,a,i),a},e.worldToView=(e,r,n)=>{if(null===t.activeCamera)return Kh("WorldToView: no active camera, cannot compute view to world, returning 0,0,0"),[0,0,0];const o=t.activeCamera.getViewMatrix();m(o,o);const i=new Float64Array([e,r,n]);return Sr(i,i,o),i},e.viewToProjection=(e,r,n,o)=>{if(null===t.activeCamera)return Kh("ViewToProjection: no active camera, cannot compute view to projection, returning 0,0,0"),[0,0,0];const i=t.activeCamera.getProjectionMatrix(o,-1,1);m(i,i);const a=new Float64Array([e,r,n]);return Sr(a,a,i),a},e.computeVisiblePropBounds=()=>{t.allBounds[0]=Va.INIT_BOUNDS[0],t.allBounds[1]=Va.INIT_BOUNDS[1],t.allBounds[2]=Va.INIT_BOUNDS[2],t.allBounds[3]=Va.INIT_BOUNDS[3],t.allBounds[4]=Va.INIT_BOUNDS[4],t.allBounds[5]=Va.INIT_BOUNDS[5];let n=!0;e.invokeEvent(r);for(let e=0;et.allBounds[1]&&(t.allBounds[1]=e[1]),e[2]t.allBounds[3]&&(t.allBounds[3]=e[3]),e[4]t.allBounds[5]&&(t.allBounds[5]=e[5]))}}return n&&(yi(t.allBounds),Hh("Can't compute bounds, no 3D props are visible")),t.allBounds},e.resetCamera=function(){const r=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:null)||e.computeVisiblePropBounds(),n=[0,0,0];if(!vi(r))return Hh("Cannot reset camera!"),!1;let i=null;if(!e.getActiveCamera())return Kh("Trying to reset non-existent camera"),!1;i=t.activeCamera.getViewPlaneNormal(),t.activeCamera.setViewAngle(30),n[0]=(r[0]+r[1])/2,n[1]=(r[2]+r[3])/2,n[2]=(r[4]+r[5])/2;let a=r[1]-r[0],s=r[3]-r[2],l=r[5]-r[4];a*=a,s*=s,l*=l;let u=a+s+l;u=0===u?1:u,u=.5*Math.sqrt(u);const c=yo(t.activeCamera.getViewAngle()),d=u,p=u/Math.sin(.5*c),f=t.activeCamera.getViewUp();return Math.abs(Ro(f,i))>.999&&(Xh("Resetting view-up since view plane normal is parallel"),t.activeCamera.setViewUp(-f[2],f[0],f[1])),t.activeCamera.setFocalPoint(n[0],n[1],n[2]),t.activeCamera.setPosition(n[0]+p*i[0],n[1]+p*i[1],n[2]+p*i[2]),e.resetCameraClippingRange(r),t.activeCamera.setParallelScale(d),t.activeCamera.setPhysicalScale(u),t.activeCamera.setPhysicalTranslation(-n[0],-n[1],-n[2]),e.invokeEvent(o),!0},e.resetCameraClippingRange=function(){const r=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:null)||e.computeVisiblePropBounds();if(!vi(r))return Hh("Cannot reset camera clipping range!"),!1;if(e.getActiveCameraAndResetIfCreated(),!t.activeCamera)return Kh("Trying to reset clipping range of non-existent camera"),!1;const o=t.activeCamera.computeClippingRange(r);let i=0;if(t.activeCamera.getParallelProjection())i=.2*t.activeCamera.getParallelScale();else{const e=yo(t.activeCamera.getViewAngle());i=.2*Math.tan(e/2)*o[1]}return o[1]-o[0]=o[1]?.01*o[1]:o[0],t.nearClippingPlaneTolerance||(t.nearClippingPlaneTolerance=.01),o[0]{e!==t._renderWindow&&(t._vtkWindow=e,t._renderWindow=e)},e.visibleActorCount=()=>t.props.filter(e=>e.getVisibility()).length,e.visibleVolumeCount=e.visibleActorCount,e.getMTime=()=>{let e=t.mtime;const r=t.activeCamera?t.activeCamera.getMTime():0;r>e&&(e=r);const n=t._createdLight?t._createdLight.getMTime():0;return n>e&&(e=n),e},e.getTransparent=()=>!!t.preserveColorBuffer,e.isActiveCameraCreated=()=>!!t.activeCamera}(e,t)}var Jh={newInstance:Pt(Yh,"vtkRenderer"),extend:Yh};const Qh=Object.create(null);function Zh(e,t){Qh[e]=t}function em(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Qh[e]&&Qh[e](t)}const tm={defaultViewAPI:"WebGL",renderers:[],views:[],interactor:null,neverRendered:!0,numberOfLayers:1,childRenderWindows:[]};function rm(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,tm,r),zt.obj(e,t),zt.setGet(e,t,["interactor","numberOfLayers","_views","defaultViewAPI"]),zt.get(e,t,["neverRendered"]),zt.getArray(e,t,["renderers","childRenderWindows"]),zt.moveToProtected(e,t,["views"]),zt.event(e,t,"completion"),function(e,t){t.classHierarchy.push("vtkRenderWindow"),e.addRenderer=r=>{e.hasRenderer(r)||(r.setRenderWindow(e),t.renderers.push(r),e.modified())},e.removeRenderer=r=>{t.renderers=t.renderers.filter(e=>e!==r),e.modified()},e.hasRenderer=e=>-1!==t.renderers.indexOf(e),e.newAPISpecificView=function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return em(e||t.defaultViewAPI,r)},e.addView=r=>{e.hasView(r)||(r.setRenderable(e),t._views.push(r),e.modified())},e.removeView=r=>{t._views=t._views.filter(e=>e!==r),e.modified()},e.hasView=e=>-1!==t._views.indexOf(e),e.preRender=()=>{t.renderers.forEach(e=>{e.isActiveCameraCreated()||e.resetCamera()})},e.render=()=>{e.preRender(),t.interactor?t.interactor.render():t._views.forEach(e=>e.traverseAllPasses())},e.getStatistics=()=>{const e={propCount:0,invisiblePropCount:0,gpuMemoryMB:0};return t._views.forEach(t=>{t.getGraphicsMemoryInfo&&(e.gpuMemoryMB+=t.getGraphicsMemoryInfo()/1e6)}),t.renderers.forEach(r=>{const n=r.getViewProps(),o=t._views[0].getViewNodeFor(r);n.forEach(t=>{if(t.getVisibility()){e.propCount+=1;const r=t.getMapper&&t.getMapper();if(r&&r.getPrimitiveCount){const t=o.getViewNodeFor(r);if(t){t.getAllocatedGPUMemoryInBytes&&(e.gpuMemoryMB+=t.getAllocatedGPUMemoryInBytes()/1e6);const n=r.getPrimitiveCount();Object.keys(n).forEach(t=>{e[t]||(e[t]=0),e[t]+=n[t]})}}}else e.invisiblePropCount+=1})}),e.str=Object.keys(e).map(t=>`${t}: ${e[t]}`).join("\n"),e},e.captureImages=function(){let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"image/png",n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return zt.setImmediate(e.render),t._views.map(e=>e.captureNextImage?e.captureNextImage(r,n):void 0).filter(e=>!!e)},e.addRenderWindow=r=>!t.childRenderWindows.includes(r)&&(t.childRenderWindows.push(r),e.modified(),!0),e.removeRenderWindow=r=>{const n=t.childRenderWindows.findIndex(e=>e===r);return!(n<0||(t.childRenderWindows.splice(n,1),e.modified(),0))}}(e,t)}var nm={newInstance:zt.newInstance(rm,"vtkRenderWindow"),extend:rm,registerViewConstructor:Zh,listViewAPIs:function(){return Object.keys(Qh)},newAPISpecificView:em};const om={Unknown:0,LeftController:1,RightController:2},im={Unknown:0,Trigger:1,TrackPad:2,Grip:3,Thumbstick:4,A:5,B:6,ApplicationMenu:7};var am={Device:om,Input:im,Axis:{Unknown:0,TouchpadX:1,TouchpadY:2,ThumbstickX:3,ThumbstickY:4},MouseButton:{LeftButton:1,MiddleButton:2,RightButton:3}};const{Device:sm,Input:lm}=am,{vtkWarningMacro:um,vtkErrorMacro:cm,normalizeWheel:dm,vtkOnceErrorMacro:pm}=zt,fm={ctrlKey:!1,altKey:!1,shiftKey:!1},hm={"xr-standard":[lm.Trigger,lm.Grip,lm.TrackPad,lm.Thumbstick,lm.A,lm.B]},mm=["StartAnimation","Animation","EndAnimation","PointerEnter","PointerLeave","MouseEnter","MouseLeave","StartMouseMove","MouseMove","EndMouseMove","LeftButtonPress","LeftButtonRelease","MiddleButtonPress","MiddleButtonRelease","RightButtonPress","RightButtonRelease","KeyPress","KeyDown","KeyUp","StartMouseWheel","MouseWheel","EndMouseWheel","StartPinch","Pinch","EndPinch","StartPan","Pan","EndPan","StartRotate","Rotate","EndRotate","Button3D","Move3D","StartPointerLock","EndPointerLock","StartInteraction","Interaction","EndInteraction","AnimationFrameRateUpdate"];function gm(e){e.cancelable&&e.preventDefault()}function ym(e){const t=Object.create(null);return e.forEach(e=>{let{pointerId:r,position:n}=e;t[r]=n}),t}const vm={renderWindow:null,interactorStyle:null,picker:null,pickingManager:null,initialized:!1,enabled:!1,enableRender:!0,currentRenderer:null,lightFollowCamera:!0,desiredUpdateRate:30,stillUpdateRate:2,container:null,recognizeGestures:!0,currentGesture:"Start",animationRequest:null,lastFrameTime:.1,recentAnimationFrameRate:10,wheelTimeoutID:0,moveTimeoutID:0,lastGamepadValues:{},preventDefaultOnPointerDown:!1,preventDefaultOnPointerUp:!1,mouseScrollDebounceByPass:!1};function bm(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,vm,r),zt.obj(e,t),t._animationExtendedEnd=0,zt.event(e,t,"RenderEvent"),mm.forEach(r=>zt.event(e,t,r)),zt.get(e,t,["initialized","interactorStyle","lastFrameTime","recentAnimationFrameRate","_view"]),zt.setGet(e,t,["container","lightFollowCamera","enabled","enableRender","recognizeGestures","desiredUpdateRate","stillUpdateRate","picker","preventDefaultOnPointerDown","preventDefaultOnPointerUp","mouseScrollDebounceByPass"]),zt.moveToProtected(e,t,["view"]),function(e,t){t.classHierarchy.push("vtkRenderWindowInteractor");const r={...e},n=new Set,o=new Map;let i=1;function a(r,n){t._forcedRenderer||(t.currentRenderer=e.findPokedRenderer(r,n))}e.start=()=>{(t.initialized||(e.initialize(),t.initialized))&&e.startEventLoop()},e.setRenderWindow=e=>{cm("you want to call setView(view) instead of setRenderWindow on a vtk.js interactor")},e.setInteractorStyle=r=>{t.interactorStyle!==r&&(null!=t.interactorStyle&&t.interactorStyle.setInteractor(null),t.interactorStyle=r,null!=t.interactorStyle&&t.interactorStyle.getInteractor()!==e&&t.interactorStyle.setInteractor(e))},e.initialize=()=>{t.initialized=!0,e.enable(),e.render()},e.enable=()=>e.setEnabled(!0),e.disable=()=>e.setEnabled(!1),e.startEventLoop=()=>um("empty event loop"),e.getCurrentRenderer=()=>(t.currentRenderer||a(0,0),t.currentRenderer);const s=t._getScreenEventPositionFor||function(e){const r=t._view.getCanvas(),n=r.getBoundingClientRect(),i=r.width/n.width,s=r.height/n.height,l={x:i*(e.clientX-n.left),y:s*(n.height-e.clientY+n.top),z:0,movementX:i*e.movementX,movementY:s*e.movementY};return(o.size<=1||!t.currentRenderer)&&a(l.x,l.y),l};function l(e){return{controlKey:e.ctrlKey,altKey:e.altKey,shiftKey:e.shiftKey}}function u(e){const t=l(e);return{key:e.key,keyCode:e.charCode,...t}}function c(e){return e.pointerType||""}const d=()=>{if(null===t.container)return;const{container:r}=t;r.addEventListener("contextmenu",gm),r.addEventListener("wheel",e.handleWheel),r.addEventListener("DOMMouseScroll",e.handleWheel),r.addEventListener("pointerenter",e.handlePointerEnter),r.addEventListener("pointerleave",e.handlePointerLeave),r.addEventListener("pointermove",e.handlePointerMove,{passive:!1}),r.addEventListener("pointerdown",e.handlePointerDown,{passive:!1}),r.addEventListener("pointerup",e.handlePointerUp),r.addEventListener("pointercancel",e.handlePointerCancel),r.addEventListener("keypress",e.handleKeyPress),r.addEventListener("keydown",e.handleKeyDown),document.addEventListener("keyup",e.handleKeyUp),document.addEventListener("pointerlockchange",e.handlePointerLockChange),r.tabIndex=0,r.style.touchAction="none",r.style.userSelect="none",r.style.webkitTapHighlightColor="rgba(0,0,0,0)"};e.bindEvents=e=>{null!==e&&r.setContainer(e)&&d()};const p=()=>{clearTimeout(t.moveTimeoutID),clearTimeout(t.wheelTimeoutID),t.moveTimeoutID=0,t.wheelTimeoutID=0,i=1;const{container:r}=t;r&&(r.removeEventListener("contextmenu",gm),r.removeEventListener("wheel",e.handleWheel),r.removeEventListener("DOMMouseScroll",e.handleWheel),r.removeEventListener("pointerenter",e.handlePointerEnter),r.removeEventListener("pointerleave",e.handlePointerLeave),r.removeEventListener("pointermove",e.handlePointerMove,{passive:!1}),r.removeEventListener("pointerdown",e.handlePointerDown,{passive:!1}),r.removeEventListener("pointerup",e.handlePointerUp),r.removeEventListener("pointercancel",e.handlePointerCancel),r.removeEventListener("keypress",e.handleKeyPress),r.removeEventListener("keydown",e.handleKeyDown)),document.removeEventListener("keyup",e.handleKeyUp),document.removeEventListener("pointerlockchange",e.handlePointerLockChange),o.clear()};function f(){t._view&&t.enabled&&t.enableRender&&(t.inRender=!0,t._view.traverseAllPasses(),t.inRender=!1),e.invokeRenderEvent()}e.unbindEvents=()=>{p(),r.setContainer(null)},e.handleKeyPress=t=>{const r=u(t);e.keyPressEvent(r)},e.handleKeyDown=t=>{const r=u(t);e.keyDownEvent(r)},e.handleKeyUp=t=>{const r=u(t);e.keyUpEvent(r)},e.handlePointerEnter=t=>{const r={...l(t),position:s(t),deviceType:c(t)};e.pointerEnterEvent(r),"mouse"===r.deviceType&&e.mouseEnterEvent(r)},e.handlePointerLeave=t=>{const r={...l(t),position:s(t),deviceType:c(t)};e.pointerLeaveEvent(r),"mouse"===r.deviceType&&e.mouseLeaveEvent(r)},e.handlePointerDown=r=>{if(!(r.button>2||e.isPointerLocked()))switch(t.preventDefaultOnPointerDown&&gm(r),r.target.hasPointerCapture(r.pointerId)&&r.target.releasePointerCapture(r.pointerId),t.container.setPointerCapture(r.pointerId),o.has(r.pointerId)&&um("[RenderWindowInteractor] duplicate pointerId detected"),o.set(r.pointerId,{pointerId:r.pointerId,position:s(r)}),r.pointerType){case"pen":case"touch":e.handleTouchStart(r);break;default:e.handleMouseDown(r)}},e.handlePointerUp=r=>{if(o.has(r.pointerId))switch(t.preventDefaultOnPointerUp&&gm(r),o.delete(r.pointerId),t.container.releasePointerCapture(r.pointerId),r.pointerType){case"pen":case"touch":e.handleTouchEnd(r);break;default:e.handleMouseUp(r)}},e.handlePointerCancel=t=>{if(o.has(t.pointerId))switch(o.delete(t.pointerId),t.pointerType){case"pen":case"touch":e.handleTouchEnd(t);break;default:e.handleMouseUp(t)}},e.handlePointerMove=t=>{switch(o.has(t.pointerId)&&(o.get(t.pointerId).position=s(t)),t.pointerType){case"pen":case"touch":e.handleTouchMove(t);break;default:e.handleMouseMove(t)}},e.handleMouseDown=t=>{const r={...l(t),position:s(t),deviceType:c(t)};switch(t.button){case 0:e.leftButtonPressEvent(r);break;case 1:e.middleButtonPressEvent(r);break;case 2:e.rightButtonPressEvent(r);break;default:cm(`Unknown mouse button pressed: ${t.button}`)}},e.requestPointerLock=()=>{t.container&&t.container.requestPointerLock()},e.exitPointerLock=()=>document.exitPointerLock?.(),e.isPointerLocked=()=>!!t.container&&document.pointerLockElement===t.container,e.handlePointerLockChange=()=>{e.isPointerLocked()?e.startPointerLockEvent():e.endPointerLockEvent()},e.requestAnimation=r=>{void 0!==r?n.has(r)?um("requester is already registered for animating"):(n.add(r),t.animationRequest||1!==n.size||t.xrAnimation||(t._animationStartTime=Date.now(),t._animationFrameCount=0,t.animationRequest=requestAnimationFrame(e.handleAnimation),e.startAnimationEvent())):cm("undefined requester, can not start animating")},e.extendAnimation=r=>{const o=Date.now()+r;t._animationExtendedEnd=Math.max(t._animationExtendedEnd,o),t.animationRequest||0!==n.size||t.xrAnimation||(t._animationStartTime=Date.now(),t._animationFrameCount=0,t.animationRequest=requestAnimationFrame(e.handleAnimation),e.startAnimationEvent())},e.isAnimating=()=>t.xrAnimation||null!==t.animationRequest,e.cancelAnimation=function(r){let o=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(n.has(r))n.delete(r),t.animationRequest&&0===n.size&&Date.now()>t._animationExtendedEnd&&(cancelAnimationFrame(t.animationRequest),t.animationRequest=null,e.endAnimationEvent(),e.render());else if(!o){const e=r&&r.getClassName?r.getClassName():r;um(`${e} did not request an animation`)}},e.switchToXRAnimation=()=>{t.animationRequest&&(cancelAnimationFrame(t.animationRequest),t.animationRequest=null),t.xrAnimation=!0},e.returnFromXRAnimation=()=>{t.xrAnimation=!1,0!==n.size&&(t.recentAnimationFrameRate=10,t.animationRequest=requestAnimationFrame(e.handleAnimation))},e.updateXRGamepads=(r,n,o)=>{r.inputSources.forEach(r=>{const i=null==r.gripSpace?null:n.getPose(r.gripSpace,o),a=null==r.gripSpace?null:n.getPose(r.targetRaySpace,o),s=r.gamepad,l=r.handedness;if(s){s.index in t.lastGamepadValues||(t.lastGamepadValues[s.index]={left:{buttons:{}},right:{buttons:{}},none:{buttons:{}}});for(let n=0;n{const n={...l(r),position:s(r),deviceType:c(r)};0===t.moveTimeoutID?e.startMouseMoveEvent(n):(e.mouseMoveEvent(n),clearTimeout(t.moveTimeoutID)),t.moveTimeoutID=setTimeout(()=>{e.endMouseMoveEvent(),t.moveTimeoutID=0},200)},e.handleAnimation=()=>{const r=Date.now();t._animationFrameCount++,r-t._animationStartTime>1e3&&t._animationFrameCount>1&&(t.recentAnimationFrameRate=1e3*(t._animationFrameCount-1)/(r-t._animationStartTime),t.lastFrameTime=1/t.recentAnimationFrameRate,e.animationFrameRateUpdateEvent(),t._animationStartTime=r,t._animationFrameCount=1),e.animationEvent(),f(),n.size>0||Date.now(){gm(r);const n={...dm(r),...l(r),position:s(r),deviceType:c(r)};0===t.wheelTimeoutID&&(i=Math.abs(n.spinY)>=.3?Math.abs(n.spinY):1),n.spinY/=i,0===t.wheelTimeoutID?(e.startMouseWheelEvent(n),e.mouseWheelEvent(n)):(e.mouseWheelEvent(n),clearTimeout(t.wheelTimeoutID)),t.mouseScrollDebounceByPass?(e.extendAnimation(600),e.endMouseWheelEvent(),t.wheelTimeoutID=0):t.wheelTimeoutID=setTimeout(()=>{e.extendAnimation(600),e.endMouseWheelEvent(),t.wheelTimeoutID=0},200)},e.handleMouseUp=t=>{const r={...l(t),position:s(t),deviceType:c(t)};switch(t.button){case 0:e.leftButtonReleaseEvent(r);break;case 1:e.middleButtonReleaseEvent(r);break;case 2:e.rightButtonReleaseEvent(r);break;default:cm(`Unknown mouse button released: ${t.button}`)}},e.handleTouchStart=r=>{const n=[...o.values()];if(t.recognizeGestures&&n.length>1){const t=ym(o);if(2===n.length){const t={...l(fm),position:n[0].position,deviceType:c(r)};e.leftButtonReleaseEvent(t)}e.recognizeGesture("TouchStart",t)}else if(1===n.length){const t={...l(fm),position:s(r),deviceType:c(r)};e.leftButtonPressEvent(t)}},e.handleTouchMove=r=>{const n=[...o.values()];if(t.recognizeGestures&&n.length>1){const t=ym(o);e.recognizeGesture("TouchMove",t)}else if(1===n.length){const t={...l(fm),position:n[0].position,deviceType:c(r)};e.mouseMoveEvent(t)}},e.handleTouchEnd=r=>{const n=[...o.values()];if(t.recognizeGestures)if(0===n.length){const t={...l(fm),position:s(r),deviceType:c(r)};e.leftButtonReleaseEvent(t)}else if(1===n.length){const t=ym(o);e.recognizeGesture("TouchEnd",t);const i={...l(fm),position:n[0].position,deviceType:c(r)};e.leftButtonPressEvent(i)}else{const t=ym(o);e.recognizeGesture("TouchMove",t)}else if(1===n.length){const t={...l(fm),position:n[0].position,deviceType:c(r)};e.leftButtonReleaseEvent(t)}},e.setView=r=>{t._view!==r&&(t._view=r,t._view.getRenderable().setInteractor(e),e.modified())},e.getFirstRenderer=()=>t._view?.getRenderable()?.getRenderersByReference()?.[0],e.findPokedRenderer=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!t._view)return null;const n=t._view?.getRenderable()?.getRenderers();if(!n||0===n.length)return null;n.sort((e,t)=>e.getLayer()-t.getLayer());let o=null,i=null,a=null,s=n.length;for(;s--;){const l=n[s];if(t._view.isInViewport(e,r,l)&&l.getInteractive()){a=l;break}null===o&&l.getInteractive()&&(o=l),null===i&&t._view.isInViewport(e,r,l)&&(i=l)}return null===a&&(a=o),null===a&&(a=i),null==a&&(a=n[0]),a},e.render=()=>{e.isAnimating()||t.inRender||f()},mm.forEach(r=>{const n=r.charAt(0).toLowerCase()+r.slice(1);e[`${n}Event`]=n=>{if(!t.enabled)return;if(!e.getCurrentRenderer())return void pm("\n Can not forward events without a current renderer on the interactor.\n ");const o={type:r,pokedRenderer:t.currentRenderer,firstRenderer:e.getFirstRenderer(),...n};e[`invoke${r}`](o)}}),e.recognizeGesture=(r,n)=>{if(Object.keys(n).length>2)return;if(t.startingEventPositions||(t.startingEventPositions={}),"TouchStart"===r)return Object.keys(n).forEach(e=>{t.startingEventPositions[e]=n[e]}),void(t.currentGesture="Start");if("TouchEnd"===r)return"Pinch"===t.currentGesture&&(e.render(),e.endPinchEvent()),"Rotate"===t.currentGesture&&(e.render(),e.endRotateEvent()),"Pan"===t.currentGesture&&(e.render(),e.endPanEvent()),t.currentGesture="Start",void(t.startingEventPositions={});let o=0;const i=[],a=[];Object.keys(n).forEach(e=>{i[o]=n[e],a[o]=t.startingEventPositions[e],o++});const s=Math.sqrt((a[0].x-a[1].x)*(a[0].x-a[1].x)+(a[0].y-a[1].y)*(a[0].y-a[1].y)),l=Math.sqrt((i[0].x-i[1].x)*(i[0].x-i[1].x)+(i[0].y-i[1].y)*(i[0].y-i[1].y));let u=vo(Math.atan2(a[1].y-a[0].y,a[1].x-a[0].x)),c=vo(Math.atan2(i[1].y-i[0].y,i[1].x-i[0].x)),d=c-u;c=c+180>=360?c-180:c+180,u=u+180>=360?u-180:u+180,Math.abs(c-u)r&&o>i&&o>a){t.currentGesture="Pinch";const r={scale:1,touches:n};e.startPinchEvent(r)}else if(i>r&&i>a){t.currentGesture="Rotate";const r={rotation:0,touches:n};e.startRotateEvent(r)}else if(a>r){t.currentGesture="Pan";const r={translation:[0,0],touches:n};e.startPanEvent(r)}}else{if("Rotate"===t.currentGesture){const t={rotation:d,touches:n};e.rotateEvent(t)}if("Pinch"===t.currentGesture){const t={scale:l/s,touches:n};e.pinchEvent(t)}if("Pan"===t.currentGesture){const t={translation:p,touches:n};e.panEvent(t)}}},e.handleVisibilityChange=()=>{t._animationStartTime=Date.now(),t._animationFrameCount=0},e.setCurrentRenderer=e=>{t._forcedRenderer=!!e,t.currentRenderer=e},e.setContainer=e=>{p();const t=r.setContainer(e??null);return t&&d(),t},e.delete=()=>{for(;n.size;)e.cancelAnimation(n.values().next().value);void 0!==document.hidden&&document.removeEventListener("visibilitychange",e.handleVisibilityChange),t.container&&e.setContainer(null),r.delete()},void 0!==document.hidden&&document.addEventListener("visibilitychange",e.handleVisibilityChange,!1)}(e,t)}var xm={newInstance:zt.newInstance(bm,"vtkRenderWindowInteractor"),extend:bm,handledEvents:mm,...am};const{vtkErrorMacro:_m,VOID:Sm}=zt,Cm={enabled:!0,priority:0,processEvents:!0,subscribedEvents:[]};function Tm(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Cm,r),zt.obj(e,t),zt.event(e,t,"InteractionEvent"),zt.event(e,t,"StartInteractionEvent"),zt.event(e,t,"EndInteractionEvent"),zt.get(e,t,["_interactor","enabled"]),zt.setGet(e,t,["priority","processEvents"]),zt.moveToProtected(e,t,["interactor"]),function(e,t){t.classHierarchy.push("vtkInteractorObserver");const r={...e};function n(){for(;t.subscribedEvents.length;)t.subscribedEvents.pop().unsubscribe()}function o(){xm.handledEvents.forEach(r=>{e[`handle${r}`]&&t.subscribedEvents.push(t._interactor[`on${r}`](n=>t.processEvents?e[`handle${r}`](n):Sm,t.priority))})}e.setInteractor=r=>{r!==t._interactor&&(n(),t._interactor=r,r&&t.enabled&&o(),e.modified())},e.setEnabled=r=>{r!==t.enabled&&(n(),r&&(t._interactor?o():_m("\n The interactor must be set before subscribing to events\n ")),t.enabled=r,e.modified())},e.computeDisplayToWorld=(e,r,n,o)=>e?t._interactor.getView().displayToWorld(r,n,o,e):null,e.computeWorldToDisplay=(e,r,n,o)=>e?t._interactor.getView().worldToDisplay(r,n,o,e):null,e.setPriority=e=>{r.setPriority(e)&&t._interactor&&(n(),o())}}(e,t)}var wm={newInstance:zt.newInstance(Tm,"vtkInteractorObserver"),extend:Tm,computeWorldToDisplay:function(e,t,r,n){return e.getRenderWindow().getViews()[0].worldToDisplay(t,r,n,e)},computeDisplayToWorld:function(e,t,r,n){return e.getRenderWindow().getViews()[0].displayToWorld(t,r,n,e)}},Am={States:{IS_START:0,IS_NONE:0,IS_ROTATE:1,IS_PAN:2,IS_SPIN:3,IS_DOLLY:4,IS_CAMERA_POSE:11,IS_WINDOW_LEVEL:1024,IS_SLICE:1025}};const{States:Em}=Am,Dm={Rotate:Em.IS_ROTATE,Pan:Em.IS_PAN,Spin:Em.IS_SPIN,Dolly:Em.IS_DOLLY,CameraPose:Em.IS_CAMERA_POSE,WindowLevel:Em.IS_WINDOW_LEVEL,Slice:Em.IS_SLICE},Pm={state:Em.IS_NONE,handleObservers:1,autoAdjustCameraClippingRange:1};function Im(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Pm,r),wm.extend(e,t,r),zt.setGet(e,t,["focusedRenderer"]),function(e,t){t.classHierarchy.push("vtkInteractorStyle"),Object.keys(Dm).forEach(r=>{zt.event(e,t,`Start${r}Event`),e[`start${r}`]=()=>{t.state===Em.IS_NONE&&(t.state=Dm[r],t._interactor.requestAnimation(e),e.invokeStartInteractionEvent({type:"StartInteractionEvent"}),e[`invokeStart${r}Event`]({type:`Start${r}Event`}))},zt.event(e,t,`End${r}Event`),e[`end${r}`]=()=>{t.state===Dm[r]&&(t.state=Em.IS_NONE,t._interactor.cancelAnimation(e),e.invokeEndInteractionEvent({type:"EndInteractionEvent"}),e[`invokeEnd${r}Event`]({type:`End${r}Event`}),t._interactor.render())}}),t.getRenderer=e=>t.focusedRenderer||e.pokedRenderer,e.handleKeyPress=e=>{const r=t._interactor;let n=null;switch(e.key){case"r":case"R":t.getRenderer(e).resetCamera(),r.render();break;case"w":case"W":n=t.getRenderer(e).getActors(),n.forEach(e=>{const t=e.getProperty();t.setRepresentationToWireframe&&t.setRepresentationToWireframe()}),r.render();break;case"s":case"S":n=t.getRenderer(e).getActors(),n.forEach(e=>{const t=e.getProperty();t.setRepresentationToSurface&&t.setRepresentationToSurface()}),r.render();break;case"v":case"V":n=t.getRenderer(e).getActors(),n.forEach(e=>{const t=e.getProperty();t.setRepresentationToPoints&&t.setRepresentationToPoints()}),r.render()}}}(e,t)}var Om={newInstance:zt.newInstance(Im,"vtkInteractorStyle"),extend:Im,...Am};const{States:Nm}=Am,Mm={motionFactor:10,zoomFactor:10};function Rm(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Mm,r),Om.extend(e,t,r),zt.setGet(e,t,["motionFactor","zoomFactor"]),function(e,t){t.classHierarchy.push("vtkInteractorStyleTrackballCamera"),e.handleMouseMove=r=>{const n=r.position,o=t.getRenderer(r);switch(t.state){case Nm.IS_ROTATE:e.handleMouseRotate(o,n),e.invokeInteractionEvent({type:"InteractionEvent"});break;case Nm.IS_PAN:e.handleMousePan(o,n),e.invokeInteractionEvent({type:"InteractionEvent"});break;case Nm.IS_DOLLY:e.handleMouseDolly(o,n),e.invokeInteractionEvent({type:"InteractionEvent"});break;case Nm.IS_SPIN:e.handleMouseSpin(o,n),e.invokeInteractionEvent({type:"InteractionEvent"})}t.previousPosition=n},e.handleButton3D=r=>{!r||!r.pressed||r.device!==om.RightController||r.input!==im.Trigger&&r.input!==im.TrackPad?!r||r.pressed||r.device!==om.RightController||r.input!==im.Trigger&&r.input!==im.TrackPad||t.state!==Nm.IS_CAMERA_POSE||e.endCameraPose():e.startCameraPose()},e.handleMove3D=r=>{t.state===Nm.IS_CAMERA_POSE&&e.updateCameraPose(r)},e.updateCameraPose=e=>{const r=t.getRenderer(e).getActiveCamera(),n=r.getPhysicalTranslation(),o=.025*r.getPhysicalScale(),i=r.physicalOrientationToWorldDirection([e.orientation.x,e.orientation.y,e.orientation.z,e.orientation.w]);r.setPhysicalTranslation(n[0]+i[0]*o,n[1]+i[1]*o,n[2]+i[2]*o)},e.handleLeftButtonPress=r=>{const n=r.position;t.previousPosition=n,r.shiftKey?r.controlKey||r.altKey?e.startDolly():e.startPan():r.controlKey||r.altKey?e.startSpin():e.startRotate()},e.handleLeftButtonRelease=()=>{switch(t.state){case Nm.IS_DOLLY:e.endDolly();break;case Nm.IS_PAN:e.endPan();break;case Nm.IS_SPIN:e.endSpin();break;case Nm.IS_ROTATE:e.endRotate()}},e.handleStartMouseWheel=()=>{e.startDolly()},e.handleEndMouseWheel=()=>{e.endDolly()},e.handleStartPinch=r=>{t.previousScale=r.scale,e.startDolly()},e.handleEndPinch=()=>{e.endDolly()},e.handleStartRotate=r=>{t.previousRotation=r.rotation,e.startRotate()},e.handleEndRotate=()=>{e.endRotate()},e.handleStartPan=r=>{t.previousTranslation=r.translation,e.startPan()},e.handleEndPan=()=>{e.endPan()},e.handlePinch=r=>{e.dollyByFactor(t.getRenderer(r),r.scale/t.previousScale),t.previousScale=r.scale},e.handlePan=r=>{const n=t.getRenderer(r).getActiveCamera();let o=n.getFocalPoint();o=e.computeWorldToDisplay(t.getRenderer(r),o[0],o[1],o[2]);const i=o[2],a=r.translation,s=t.previousTranslation,l=e.computeDisplayToWorld(t.getRenderer(r),o[0]+a[0]-s[0],o[1]+a[1]-s[1],i),u=e.computeDisplayToWorld(t.getRenderer(r),o[0],o[1],i),c=[];c[0]=u[0]-l[0],c[1]=u[1]-l[1],c[2]=u[2]-l[2],o=n.getFocalPoint();const d=n.getPosition();n.setFocalPoint(c[0]+o[0],c[1]+o[1],c[2]+o[2]),n.setPosition(c[0]+d[0],c[1]+d[1],c[2]+d[2]),t._interactor.getLightFollowCamera()&&t.getRenderer(r).updateLightsGeometryToFollowCamera(),n.orthogonalizeViewUp(),t.previousTranslation=r.translation},e.handleRotate=e=>{const r=t.getRenderer(e).getActiveCamera();r.roll(e.rotation-t.previousRotation),r.orthogonalizeViewUp(),t.previousRotation=e.rotation},e.handleMouseRotate=(e,r)=>{if(!t.previousPosition)return;const n=t._interactor,o=r.x-t.previousPosition.x,i=r.y-t.previousPosition.y,a=n.getView().getViewportSize(e);let s=-.1,l=-.1;a[0]&&a[1]&&(s=-20/a[1],l=-20/a[0]);const u=o*l*t.motionFactor,c=i*s*t.motionFactor,d=e.getActiveCamera();Number.isNaN(u)||Number.isNaN(c)||(d.azimuth(u),d.elevation(c),d.orthogonalizeViewUp()),t.autoAdjustCameraClippingRange&&e.resetCameraClippingRange(),n.getLightFollowCamera()&&e.updateLightsGeometryToFollowCamera()},e.handleMouseSpin=(e,r)=>{if(!t.previousPosition)return;const n=t._interactor,o=e.getActiveCamera(),i=n.getView().getViewportCenter(e),a=vo(Math.atan2(t.previousPosition.y-i[1],t.previousPosition.x-i[0])),s=vo(Math.atan2(r.y-i[1],r.x-i[0]))-a;Number.isNaN(s)||(o.roll(s),o.orthogonalizeViewUp())},e.handleMousePan=(r,n)=>{if(!t.previousPosition)return;const o=r.getActiveCamera();let i=o.getFocalPoint();i=e.computeWorldToDisplay(r,i[0],i[1],i[2]);const a=i[2],s=e.computeDisplayToWorld(r,n.x,n.y,a),l=e.computeDisplayToWorld(r,t.previousPosition.x,t.previousPosition.y,a),u=[];u[0]=l[0]-s[0],u[1]=l[1]-s[1],u[2]=l[2]-s[2],i=o.getFocalPoint();const c=o.getPosition();o.setFocalPoint(u[0]+i[0],u[1]+i[1],u[2]+i[2]),o.setPosition(u[0]+c[0],u[1]+c[1],u[2]+c[2]),t._interactor.getLightFollowCamera()&&r.updateLightsGeometryToFollowCamera()},e.handleMouseDolly=(r,n)=>{if(!t.previousPosition)return;const o=n.y-t.previousPosition.y,i=t._interactor.getView().getViewportCenter(r),a=t.motionFactor*o/i[1];e.dollyByFactor(r,1.1**a)},e.handleMouseWheel=r=>{const n=1-r.spinY/t.zoomFactor;e.dollyByFactor(t.getRenderer(r),n)},e.dollyByFactor=(e,r)=>{if(Number.isNaN(r))return;const n=e.getActiveCamera();n.getParallelProjection()?n.setParallelScale(n.getParallelScale()/r):(n.dolly(r),t.autoAdjustCameraClippingRange&&e.resetCameraClippingRange()),t._interactor.getLightFollowCamera()&&e.updateLightsGeometryToFollowCamera()}}(e,t)}var Fm={newInstance:zt.newInstance(Rm,"vtkInteractorStyleTrackballCamera"),extend:Rm};function Bm(e){return e}function Lm(e){return null===e||"null"===e?null:"true"===e||"false"!==e&&(void 0!==e&&"undefined"!==e?"["===e[0]&&"]"===e[e.length-1]?e.substring(1,e.length-1).split(",").map(e=>Lm(e.trim())):""===e||Number.isNaN(Number(e))?e:Number(e):void 0)}var km=function(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:window.location.search;const r={},n=e?Lm:Bm;return new URLSearchParams(t).forEach((e,t)=>{t&&(r[t]=!e||n(e))}),r};const Um={glFramebuffer:null,colorBuffers:null,depthTexture:null,previousDrawBinding:0,previousReadBinding:0,previousDrawBuffer:0,previousReadBuffer:0,previousActiveFramebuffer:null};function Vm(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Um,r),mt(e,t),t.colorBuffers&&Ze("you cannot initialize colorBuffers through the constructor. You should call setColorBuffer() instead."),t.colorBuffers=[],St(e,t,["colorBuffers"]),function(e,t){t.classHierarchy.push("vtkFramebuffer"),e.getBothMode=()=>t.context.FRAMEBUFFER,e.saveCurrentBindingsAndBuffers=t=>{const r=void 0!==t?t:e.getBothMode();e.saveCurrentBindings(r),e.saveCurrentBuffers(r)},e.saveCurrentBindings=e=>{if(!t.context)return void Ze("you must set the OpenGLRenderWindow before calling saveCurrentBindings");const r=t.context;t.previousDrawBinding=r.getParameter(t.context.FRAMEBUFFER_BINDING),t.previousActiveFramebuffer=t._openGLRenderWindow.getActiveFramebuffer()},e.saveCurrentBuffers=e=>{},e.restorePreviousBindingsAndBuffers=t=>{const r=void 0!==t?t:e.getBothMode();e.restorePreviousBindings(r),e.restorePreviousBuffers(r)},e.restorePreviousBindings=e=>{if(!t.context)return void Ze("you must set the OpenGLRenderWindow before calling restorePreviousBindings");const r=t.context;r.bindFramebuffer(r.FRAMEBUFFER,t.previousDrawBinding),t._openGLRenderWindow.setActiveFramebuffer(t.previousActiveFramebuffer)},e.restorePreviousBuffers=e=>{},e.bind=function(){let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;null===r&&(r=t.context.FRAMEBUFFER),t.context.bindFramebuffer(r,t.glFramebuffer);for(let e=0;e{t.context?(t.glFramebuffer=t.context.createFramebuffer(),t.glFramebuffer.width=e,t.glFramebuffer.height=r):Ze("you must set the OpenGLRenderWindow before calling create")},e.setColorBuffer=function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;const n=t.context;if(!n)return void Ze("you must set the OpenGLRenderWindow before calling setColorBuffer");let o=n.COLOR_ATTACHMENT0;if(r>0){if(!t._openGLRenderWindow.getWebgl2())return void Ze("Using multiple framebuffer attachments requires WebGL 2");o+=r}t.colorBuffers[r]=e,n.framebufferTexture2D(n.FRAMEBUFFER,o,n.TEXTURE_2D,e.getHandle(),0)},e.removeColorBuffer=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;const r=t.context;if(!r)return void Ze("you must set the OpenGLRenderWindow before calling removeColorBuffer");let n=r.COLOR_ATTACHMENT0;if(e>0){if(!t._openGLRenderWindow.getWebgl2())return void Ze("Using multiple framebuffer attachments requires WebGL 2");n+=e}r.framebufferTexture2D(r.FRAMEBUFFER,n,r.TEXTURE_2D,null,0),t.colorBuffers=t.colorBuffers.splice(e,1)},e.setDepthBuffer=e=>{if(t.context)if(t._openGLRenderWindow.getWebgl2()){const r=t.context;r.framebufferTexture2D(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.TEXTURE_2D,e.getHandle(),0)}else Ze("Attaching depth buffer textures to fbo requires WebGL 2");else Ze("you must set the OpenGLRenderWindow before calling setDepthBuffer")},e.removeDepthBuffer=()=>{if(t.context)if(t._openGLRenderWindow.getWebgl2()){const e=t.context;e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,null,0)}else Ze("Attaching depth buffer textures to framebuffers requires WebGL 2");else Ze("you must set the OpenGLRenderWindow before calling removeDepthBuffer")},e.getGLFramebuffer=()=>t.glFramebuffer,e.setOpenGLRenderWindow=r=>{t._openGLRenderWindow!==r&&(e.releaseGraphicsResources(),t._openGLRenderWindow=r,t.context=null,r&&(t.context=t._openGLRenderWindow.getContext()))},e.releaseGraphicsResources=()=>{t.glFramebuffer&&t.context.deleteFramebuffer(t.glFramebuffer)},e.getSize=()=>null==t.glFramebuffer?null:[t.glFramebuffer.width,t.glFramebuffer.height],e.populateFramebuffer=()=>{if(!t.context)return void Ze("you must set the OpenGLRenderWindow before calling populateFrameBuffer");e.bind();const r=t.context,n=Dd.newInstance();n.setOpenGLRenderWindow(t._openGLRenderWindow),n.setMinificationFilter(cd.LINEAR),n.setMagnificationFilter(cd.LINEAR),n.create2DFromRaw({width:t.glFramebuffer.width,height:t.glFramebuffer.height,numComps:4,dataType:us.UNSIGNED_CHAR,data:null}),e.setColorBuffer(n),t.depthTexture=r.createRenderbuffer(),r.bindRenderbuffer(r.RENDERBUFFER,t.depthTexture),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_COMPONENT16,t.glFramebuffer.width,t.glFramebuffer.height),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,t.depthTexture)},e.getColorTexture=()=>t.colorBuffers[0]}(e,t)}var Gm={newInstance:Pt(Vm,"vtkFramebuffer"),extend:Vm};const zm={delegates:[],currentOperation:null,preDelegateOperations:[],postDelegateOperations:[],currentParent:null};function jm(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,zm,r),zt.obj(e,t),zt.get(e,t,["currentOperation"]),zt.setGet(e,t,["delegates","_currentParent","preDelegateOperations","postDelegateOperations"]),zt.moveToProtected(e,t,["currentParent"]),function(e,t){t.classHierarchy.push("vtkRenderPass"),e.getOperation=()=>t.currentOperation,e.setCurrentOperation=e=>{t.currentOperation=e,t.currentTraverseOperation=`traverse${zt.capitalize(t.currentOperation)}`},e.getTraverseOperation=()=>t.currentTraverseOperation,e.traverse=function(r){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;t.deleted||(t._currentParent=n,t.preDelegateOperations.forEach(t=>{e.setCurrentOperation(t),r.traverse(e)}),t.delegates.forEach(t=>{t.traverse(r,e)}),t.postDelegateOperations.forEach(t=>{e.setCurrentOperation(t),r.traverse(e)}))}}(e,t)}var Wm={newInstance:zt.newInstance(jm,"vtkRenderPass"),extend:jm};const{Representation:Hm}=os,{vtkErrorMacro:Km}=zt;function Xm(e){const t=rd.substitute(e.Fragment,"//VTK::RenderPassFragmentShader::Impl","\n float weight = gl_FragData[0].a * pow(max(1.1 - gl_FragCoord.z, 0.0), 2.0);\n gl_FragData[0] = vec4(gl_FragData[0].rgb*weight, gl_FragData[0].a);\n gl_FragData[1].r = weight;\n ",!1);e.Fragment=t.result}const $m={framebuffer:null,copyShader:null,tris:null};function qm(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,$m,r),Wm.extend(e,t,r),t.VBOBuildTime={},zt.obj(t.VBOBuildTime,{mtime:0}),t.tris=ud.newInstance(),zt.get(e,t,["framebuffer"]),function(e,t){t.classHierarchy.push("vtkOpenGLOrderIndependentTranslucentPass"),e.createVertexBuffer=()=>{const e=new Float32Array([-1,-1,-1,1,-1,-1,-1,1,-1,1,1,-1]),r=new Float32Array([0,0,1,0,0,1,1,1]),n=new Uint16Array([4,0,1,3,2]),o=_s.newInstance({numberOfComponents:3,values:e});o.setName("points");const i=_s.newInstance({numberOfComponents:2,values:r});i.setName("tcoords");const a=_s.newInstance({numberOfComponents:1,values:n});t.tris.getCABO().createVBO(a,"polys",Hm.SURFACE,{points:o,tcoords:i,cellOffset:0}),t.VBOBuildTime.modified()},e.createFramebuffer=e=>{const r=e.getSize(),n=e.getContext();t.framebuffer=Gm.newInstance(),t.framebuffer.setOpenGLRenderWindow(e),t.framebuffer.create(...r),t.framebuffer.saveCurrentBindingsAndBuffers(),t.framebuffer.bind(),t.translucentRGBATexture=Dd.newInstance(),t.translucentRGBATexture.setInternalFormat(n.RGBA16F),t.translucentRGBATexture.setFormat(n.RGBA),t.translucentRGBATexture.setOpenGLDataType(n.HALF_FLOAT),t.translucentRGBATexture.setOpenGLRenderWindow(e),t.translucentRGBATexture.create2DFromRaw({width:r[0],height:r[1],numComps:4,dataType:"Float32Array",data:null}),t.translucentRTexture=Dd.newInstance(),t.translucentRTexture.setInternalFormat(n.R16F),t.translucentRTexture.setFormat(n.RED),t.translucentRTexture.setOpenGLDataType(n.HALF_FLOAT),t.translucentRTexture.setOpenGLRenderWindow(e),t.translucentRTexture.create2DFromRaw({width:r[0],height:r[1],numComps:1,dataType:"Float32Array",data:null}),t.translucentZTexture=Dd.newInstance(),t.translucentZTexture.setOpenGLRenderWindow(e),t.translucentZTexture.createDepthFromRaw({width:r[0],height:r[1],dataType:"Float32Array",data:null}),t.framebuffer.setColorBuffer(t.translucentRGBATexture,0),t.framebuffer.setColorBuffer(t.translucentRTexture,1),t.framebuffer.setDepthBuffer(t.translucentZTexture)},e.createCopyShader=e=>{t.copyShader=e.getShaderCache().readyShaderProgramArray(["//VTK::System::Dec","attribute vec4 vertexDC;","attribute vec2 tcoordTC;","varying vec2 tcoord;","void main() { tcoord = tcoordTC; gl_Position = vertexDC; }"].join("\n"),"//VTK::System::Dec\n\nin vec2 tcoord;\n\nuniform sampler2D translucentRTexture;\nuniform sampler2D translucentRGBATexture;\n\n// the output of this shader\n//VTK::Output::Dec\n\nvoid main()\n{\n vec4 t1Color = texture(translucentRGBATexture, tcoord);\n float t2Color = texture(translucentRTexture, tcoord).r;\n gl_FragData[0] = vec4(t1Color.rgb/max(t2Color,0.01), 1.0 - t1Color.a);\n}\n","")},e.createVBO=r=>{const n=r.getContext();t.tris.setOpenGLRenderWindow(r),e.createVertexBuffer();const o=t.copyShader;t.tris.getCABO().bind(),t.copyVAO.addAttributeArray(o,t.tris.getCABO(),"vertexDC",t.tris.getCABO().getVertexOffset(),t.tris.getCABO().getStride(),n.FLOAT,3,n.FALSE)||Km("Error setting vertexDC in copy shader VAO."),t.copyVAO.addAttributeArray(o,t.tris.getCABO(),"tcoordTC",t.tris.getCABO().getTCoordOffset(),t.tris.getCABO().getStride(),n.FLOAT,2,n.FALSE)||Km("Error setting vertexDC in copy shader VAO.")},e.traverse=(r,n,o)=>{if(t.deleted)return;const i=r.getSize(),a=r.getContext();if(t._supported=!1,n.getSelector()||!a||!r.getWebgl2()||!a.getExtension("EXT_color_buffer_half_float")&&!a.getExtension("EXT_color_buffer_float"))return e.setCurrentOperation("translucentPass"),void n.traverse(e);if(t._supported=!0,null===t.framebuffer)e.createFramebuffer(r);else{const n=t.framebuffer.getSize();null===n||n[0]!==i[0]||n[1]!==i[1]?(t.framebuffer.releaseGraphicsResources(),t.translucentRGBATexture.releaseGraphicsResources(r),t.translucentRTexture.releaseGraphicsResources(r),t.translucentZTexture.releaseGraphicsResources(r),e.createFramebuffer(r)):(t.framebuffer.saveCurrentBindingsAndBuffers(),t.framebuffer.bind())}a.drawBuffers([a.COLOR_ATTACHMENT0]),a.clearBufferfv(a.COLOR,0,[0,0,0,0]),a.clearBufferfv(a.DEPTH,0,[1]),a.colorMask(!1,!1,!1,!1),o.getOpaqueActorCount()>0&&(o.setCurrentOperation("opaqueZBufferPass"),n.traverse(o)),a.colorMask(!0,!0,!0,!0),a.drawBuffers([a.COLOR_ATTACHMENT0,a.COLOR_ATTACHMENT1]),a.viewport(0,0,i[0],i[1]),a.scissor(0,0,i[0],i[1]),a.clearBufferfv(a.COLOR,0,[0,0,0,1]),a.clearBufferfv(a.COLOR,1,[0,0,0,0]),a.enable(a.DEPTH_TEST),a.enable(a.BLEND),a.blendFuncSeparate(a.ONE,a.ONE,a.ZERO,a.ONE_MINUS_SRC_ALPHA),e.setCurrentOperation("translucentPass"),n.traverse(e),a.drawBuffers([a.NONE]),t.framebuffer.restorePreviousBindingsAndBuffers(),null===t.copyShader?e.createCopyShader(r):r.getShaderCache().readyShaderProgram(t.copyShader),t.copyVAO||(t.copyVAO=id.newInstance(),t.copyVAO.setOpenGLRenderWindow(r)),t.copyVAO.bind(),t.VBOBuildTime.getMTime()t._supported?Xm:null,e.releaseGraphicsResources=r=>{t.framebuffer&&(t.framebuffer.releaseGraphicsResources(r),t.framebuffer=null),t.translucentRGBATexture&&(t.translucentRGBATexture.releaseGraphicsResources(r),t.translucentRGBATexture=null),t.translucentRTexture&&(t.translucentRTexture.releaseGraphicsResources(r),t.translucentRTexture=null),t.translucentZTexture&&(t.translucentZTexture.releaseGraphicsResources(r),t.translucentZTexture=null),t.copyVAO&&(t.copyVAO.releaseGraphicsResources(r),t.copyVAO=null),t.copyShader&&(t.copyShader.releaseGraphicsResources(r),t.copyShader=null),t.tris&&(t.tris.releaseGraphicsResources(r),t.tris=null),e.modified()}}(e,t)}var Ym={newInstance:zt.newInstance(qm,"vtkOpenGLOrderIndependentTranslucentPass"),extend:qm};const Jm={opaqueActorCount:0,translucentActorCount:0,volumeCount:0,overlayActorCount:0,framebuffer:null,depthRequested:!1};function Qm(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Jm,r),Wm.extend(e,t,r),zt.get(e,t,["framebuffer","opaqueActorCount","translucentActorCount","volumeCount"]),function(e,t){t.classHierarchy.push("vtkForwardPass"),e.traverse=function(r){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(t.deleted)return;t._currentParent=n,e.setCurrentOperation("buildPass"),r.traverse(e);const o=r.getRenderable().getNumberOfLayers(),i=r.getRenderable().getRenderersByReference();for(let n=0;n0||t.translucentActorCount>0)&&t.volumeCount>0||t.depthRequested){const n=r.getFramebufferSize();null===t.framebuffer&&(t.framebuffer=Gm.newInstance()),t.framebuffer.setOpenGLRenderWindow(r),t.framebuffer.saveCurrentBindingsAndBuffers();const o=t.framebuffer.getSize();null!==o&&o[0]===n[0]&&o[1]===n[1]||(t.framebuffer.create(n[0],n[1]),t.framebuffer.populateFramebuffer()),t.framebuffer.bind(),e.setCurrentOperation("zBufferPass"),s.traverse(e),t.framebuffer.restorePreviousBindingsAndBuffers(),t.depthRequested=!1}e.setCurrentOperation("cameraPass"),s.traverse(e),t.opaqueActorCount>0&&(e.setCurrentOperation("opaquePass"),s.traverse(e)),t.translucentActorCount>0&&(t.translucentPass||(t.translucentPass=Ym.newInstance()),t.translucentPass.traverse(r,s,e)),t.volumeCount>0&&(e.setCurrentOperation("volumePass"),s.traverse(e)),t.overlayActorCount>0&&(e.setCurrentOperation("overlayPass"),s.traverse(e))}}},e.getZBufferTexture=()=>t.framebuffer?t.framebuffer.getColorTexture():null,e.requestDepth=()=>{t.depthRequested=!0},e.incrementOpaqueActorCount=()=>t.opaqueActorCount++,e.incrementTranslucentActorCount=()=>t.translucentActorCount++,e.incrementVolumeCount=()=>t.volumeCount++,e.incrementOverlayActorCount=()=>t.overlayActorCount++}(e,t)}var Zm={newInstance:zt.newInstance(Qm,"vtkForwardPass"),extend:Qm};const{FieldAssociations:eg}=Gs,tg={fieldAssociation:eg.FIELD_ASSOCIATION_CELLS,captureZValues:!1};function rg(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,tg,r),zt.obj(e,t),zt.setGet(e,t,["fieldAssociation","captureZValues"]),function(e,t){t.classHierarchy.push("vtkHardwareSelector"),e.getSourceDataAsync=async(e,t,r,n,o)=>{},e.selectAsync=async(t,r,n,o,i)=>{const a=await e.getSourceDataAsync(t,r,n,o,i);return a?a.generateSelection(r,n,o,i):[]}}(e,t)}var ng={newInstance:zt.newInstance(rg,"vtkHardwareSelector"),extend:rg};const og={contentType:-1,fieldType:-1,properties:null,selectionList:[]};function ig(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,og,r),zt.obj(e,t),t.properties={},zt.setGet(e,t,["contentType","fieldType","properties","selectionList"]),function(e,t){t.classHierarchy.push("vtkSelectionNode"),e.getBounds=()=>t.points.getBounds()}(e,t)}var ag={newInstance:zt.newInstance(ig,"vtkSelectionNode"),extend:ig,SelectionContent:{GLOBALIDS:0,PEDIGREEIDS:1,VALUES:2,INDICES:3,FRUSTUM:4,LOCATIONS:5,THRESHOLDS:6,BLOCKS:7,QUERY:8},SelectionField:{CELL:0,POINT:1,FIELD:2,VERTEX:3,EDGE:4,ROW:5}};const{PassTypes:sg}=wl,{SelectionContent:lg,SelectionField:ug}=ag,{FieldAssociations:cg}=Gs,{vtkErrorMacro:dg}=zt;function pg(e){return`${e.propID} ${e.compositeID}`}function fg(e,t,r,n){return r?r[4*(t*(n[2]-n[0]+1)+e)+3]:0}function hg(e,t,r,n){if(!r)return 0;const o=4*(t*(n[2]-n[0]+1)+e),i=r[o],a=r[o+1];return 256*(256*r[o+2]+a)+i}function mg(e,t){let r=t;return r<<=24,r|=e,r}function gg(e,t,r,n){const o=r<0?0:r;if(0===o){if(n[0]=t[0],n[1]=t[1],t[0]e.area[2]||t[1]e.area[3])return null;const r=[t[0]-e.area[0],t[1]-e.area[1]],o=hg(r[0],r[1],e.pixBuffer[sg.ACTOR_PASS],e.area);if(o<=0||o-1>=e.props.length)return null;const i={valid:!0};i.propID=o-1,i.prop=e.props[i.propID];let a=hg(r[0],r[1],e.pixBuffer[sg.COMPOSITE_INDEX_PASS],e.area);if((a<0||a>16777215)&&(a=0),i.compositeID=a-1,e.captureZValues){const n=4*(r[1]*(e.area[2]-e.area[0]+1)+r[0]);i.zValue=(256*e.zBuffer[n]+e.zBuffer[n+1])/65535,i.displayPosition=t}if(e.pixBuffer[sg.ID_LOW24]&&0===fg(r[0],r[1],e.pixBuffer[sg.ID_LOW24],e.area))return i;const s=hg(r[0],r[1],e.pixBuffer[sg.ID_LOW24],e.area),l=hg(r[0],r[1],e.pixBuffer[sg.ID_HIGH24],e.area);return i.attributeID=mg(s,l),i}const i=[t[0],t[1]],a=[0,0];let s=gg(e,t,0,n);if(s&&s.valid)return s;for(let t=1;tt?i[1]-t:0;r<=i[1]+t;++r){if(a[1]=r,i[0]>=t&&(a[0]=i[0]-t,s=gg(e,a,0,n),s&&s.valid))return s;if(a[0]=i[0]+t,s=gg(e,a,0,n),s&&s.valid)return s}for(let r=i[0]>=t?i[0]-(t-1):0;r<=i[0]+(t-1);++r){if(a[0]=r,i[1]>=t&&(a[1]=i[1]-t,s=gg(e,a,0,n),s&&s.valid))return s;if(a[1]=i[1]+t,s=gg(e,a,0,n),s&&s.valid)return s}}return n[0]=t[0],n[1]=t[1],null}function yg(e,t,r,n,o){const i=[];let a=0;return t.forEach((t,s)=>{const l=ag.newInstance();switch(l.setContentType(lg.INDICES),e){case cg.FIELD_ASSOCIATION_CELLS:l.setFieldType(ug.CELL);break;case cg.FIELD_ASSOCIATION_POINTS:l.setFieldType(ug.POINT);break;default:dg("Unknown field association")}l.getProperties().propID=t.info.propID,l.getProperties().prop=t.info.prop,l.getProperties().compositeID=t.info.compositeID,l.getProperties().attributeID=t.info.attributeID,l.getProperties().pixelCount=t.pixelCount,r&&(l.getProperties().displayPosition=[t.info.displayPosition[0],t.info.displayPosition[1],t.info.zValue],l.getProperties().worldPosition=o.displayToWorld(t.info.displayPosition[0],t.info.displayPosition[1],t.info.zValue,n)),l.setSelectionList(t.attributeIDs),i[a]=l,a++}),i}const vg={area:void 0,currentPass:-1,propColorValue:null,props:null,maximumPointId:0,maximumCellId:0,idOffset:1};function bg(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,vg,r),ng.extend(e,t,r),t.propColorValue=[0,0,0],t.props=[],t.area||(t.area=[0,0,0,0]),zt.setGetArray(e,t,["area"],4),zt.setGet(e,t,["_renderer","currentPass","_openGLRenderWindow","maximumPointId","maximumCellId"]),zt.setGetArray(e,t,["propColorValue"],3),zt.moveToProtected(e,t,["renderer","openGLRenderWindow"]),zt.event(e,t,"event"),function(e,t){t.classHierarchy.push("vtkOpenGLHardwareSelector"),e.releasePixBuffers=()=>{t.rawPixBuffer=[],t.pixBuffer=[],t.zBuffer=null},e.beginSelection=()=>{t._openGLRenderer=t._openGLRenderWindow.getViewNodeFor(t._renderer,t._openGLRenderer),t.maxAttributeId=0;const r=t._openGLRenderWindow.getSize();if(t.framebuffer){t.framebuffer.setOpenGLRenderWindow(t._openGLRenderWindow),t.framebuffer.saveCurrentBindingsAndBuffers();const e=t.framebuffer.getSize();e&&e[0]===r[0]&&e[1]===r[1]?t.framebuffer.bind():(t.framebuffer.create(r[0],r[1]),t.framebuffer.populateFramebuffer())}else t.framebuffer=Gm.newInstance(),t.framebuffer.setOpenGLRenderWindow(t._openGLRenderWindow),t.framebuffer.saveCurrentBindingsAndBuffers(),t.framebuffer.create(r[0],r[1]),t.framebuffer.populateFramebuffer();if(t._openGLRenderer.clear(),t._openGLRenderer.setSelector(e),t.hitProps={},t.propPixels={},t.props=[],e.releasePixBuffers(),t.fieldAssociation===cg.FIELD_ASSOCIATION_POINTS){const e=t._openGLRenderWindow.getContext(),r=e.isEnabled(e.BLEND);e.disable(e.BLEND),t._openGLRenderWindow.traverseAllPasses(),r&&e.enable(e.BLEND)}},e.endSelection=()=>{t.hitProps={},t._openGLRenderer.setSelector(null),t.framebuffer.restorePreviousBindingsAndBuffers()},e.preCapturePass=()=>{const e=t._openGLRenderWindow.getContext();t.originalBlending=e.isEnabled(e.BLEND),e.disable(e.BLEND)},e.postCapturePass=()=>{const e=t._openGLRenderWindow.getContext();t.originalBlending&&e.enable(e.BLEND)},e.select=()=>{let r=null;return e.captureBuffers()&&(r=e.generateSelection(t.area[0],t.area[1],t.area[2],t.area[3]),e.releasePixBuffers()),r},e.getSourceDataAsync=async(r,n,o,i,a)=>{if(t._renderer=r,void 0===n){const r=t._openGLRenderWindow.getSize();e.setArea(0,0,r[0]-1,r[1]-1)}else e.setArea(n,o,i,a);if(!e.captureBuffers())return!1;const s={area:[...t.area],pixBuffer:[...t.pixBuffer],captureZValues:t.captureZValues,zBuffer:t.zBuffer,props:[...t.props],fieldAssociation:t.fieldAssociation,renderer:r,openGLRenderWindow:t._openGLRenderWindow,generateSelection:function(){for(var e=arguments.length,t=new Array(e),r=0;r{if(!t._renderer||!t._openGLRenderWindow)return dg("Renderer and view must be set before calling Select."),!1;t._openGLRenderer=t._openGLRenderWindow.getViewNodeFor(t._renderer,t._openGLRenderer),t._openGLRenderWindow.getRenderable().preRender(),e.invokeEvent({type:"StartEvent"}),t.originalBackground=t._renderer.getBackgroundByReference(),t._renderer.setBackground(0,0,0,0);const r=t._openGLRenderWindow.getRenderPasses();e.beginSelection();const n=[];for(t.currentPass=sg.MIN_KNOWN_PASS;t.currentPass<=sg.MAX_KNOWN_PASS;t.currentPass++)e.passRequired(t.currentPass)&&(e.preCapturePass(t.currentPass),t.captureZValues&&t.currentPass===sg.ACTOR_PASS&&"function"==typeof r[0].requestDepth&&"function"==typeof r[0].getFramebuffer?(r[0].requestDepth(),t._openGLRenderWindow.traverseAllPasses()):t._openGLRenderWindow.traverseAllPasses(),e.postCapturePass(t.currentPass),e.savePixelBuffer(t.currentPass),n.push(t.currentPass));return n.forEach(r=>{t.currentPass=r,e.processPixelBuffers()}),t.currentPass=sg.MAX_KNOWN_PASS,e.endSelection(),t._renderer.setBackground(t.originalBackground),e.invokeEvent({type:"EndEvent"}),!0},e.processPixelBuffers=()=>{t.props.forEach((r,n)=>{e.isPropHit(n)&&r.processSelectorPixelBuffers(e,t.propPixels[n])})},e.passRequired=e=>{if(e===sg.ID_HIGH24){if(t.fieldAssociation===cg.FIELD_ASSOCIATION_POINTS)return t.maximumPointId>16777215;if(t.fieldAssociation===cg.FIELD_ASSOCIATION_CELLS)return t.maximumCellId>16777215}return!0},e.savePixelBuffer=r=>{if(t.pixBuffer[r]=t._openGLRenderWindow.getPixelData(t.area[0],t.area[1],t.area[2],t.area[3]),!t.rawPixBuffer[r]){const e=(t.area[2]-t.area[0]+1)*(t.area[3]-t.area[1]+1)*4;t.rawPixBuffer[r]=new Uint8Array(e),t.rawPixBuffer[r].set(t.pixBuffer[r])}if(r===sg.ACTOR_PASS){if(t.captureZValues){const e=t._openGLRenderWindow.getRenderPasses();if("function"==typeof e[0].requestDepth&&"function"==typeof e[0].getFramebuffer){const r=e[0].getFramebuffer();r.saveCurrentBindingsAndBuffers(),r.bind(),t.zBuffer=t._openGLRenderWindow.getPixelData(t.area[0],t.area[1],t.area[2],t.area[3]),r.restorePreviousBindingsAndBuffers()}}e.buildPropHitList(t.rawPixBuffer[r])}},e.buildPropHitList=e=>{let r=0;for(let n=0;n<=t.area[3]-t.area[1];n++)for(let o=0;o<=t.area[2]-t.area[0];o++){let i=hg(o,n,e,t.area);i>0&&(i--,i in t.hitProps||(t.hitProps[i]=!0,t.propPixels[i]=[]),t.propPixels[i].push(4*r)),++r}},e.renderProp=r=>{t.currentPass===sg.ACTOR_PASS&&(e.setPropColorValueFromInt(t.props.length+1),t.props.push(r))},e.renderCompositeIndex=r=>{t.currentPass===sg.COMPOSITE_INDEX_PASS&&e.setPropColorValueFromInt(r+1)},e.renderAttributeId=e=>{e<0||(t.maxAttributeId=e>t.maxAttributeId?e:t.maxAttributeId)},e.passTypeToString=e=>zt.enumToString(sg,e),e.isPropHit=e=>Boolean(t.hitProps[e]),e.setPropColorValueFromInt=e=>{t.propColorValue[0]=e%256/255,t.propColorValue[1]=Math.floor(e/256)%256/255,t.propColorValue[2]=Math.floor(e/65536)%256/255},e.getPixelInformation=(r,n,o)=>{const i=n<0?0:n;if(console.log("getPixelInformation called",i),0===i){if(o[0]=r[0],o[1]=r[1],r[0]t.area[2]||r[1]t.area[3])return null;console.log(r),console.log(t.area);const e=[r[0]-t.area[0],r[1]-t.area[1]];console.log("adjusted displayPosition",e);const n=hg(e[0],e[1],t.pixBuffer[sg.ACTOR_PASS],t.area);if(console.log("actorid",n),n<=0||n-1>=t.props.length)return null;const i={valid:!0};i.propID=n-1,i.prop=t.props[i.propID];let a=hg(e[0],e[1],t.pixBuffer[sg.COMPOSITE_INDEX_PASS],t.area);if((a<0||a>16777215)&&(a=0),i.compositeID=a-1,t.captureZValues){const n=4*(e[1]*(t.area[2]-t.area[0]+1)+e[0]);i.zValue=(256*t.zBuffer[n]+t.zBuffer[n+1])/65535,i.displayPosition=r}if(t.pixBuffer[sg.ID_LOW24]&&0===fg(e[0],e[1],t.pixBuffer[sg.ID_LOW24],t.area))return i;const s=hg(e[0],e[1],t.pixBuffer[sg.ID_LOW24],t.area),l=hg(e[0],e[1],t.pixBuffer[sg.ID_HIGH24],t.area);return i.attributeID=mg(s,l),i}const a=[r[0],r[1]],s=[0,0];let l=e.getPixelInformation(r,0,o);if(l&&l.valid)return l;for(let t=1;tt?a[1]-t:0;r<=a[1]+t;++r){if(s[1]=r,a[0]>=t&&(s[0]=a[0]-t,l=e.getPixelInformation(s,0,o),l&&l.valid))return l;if(s[0]=a[0]+t,l=e.getPixelInformation(s,0,o),l&&l.valid)return l}for(let r=a[0]>=t?a[0]-(t-1):0;r<=a[0]+(t-1);++r){if(s[0]=r,a[1]>=t&&(s[1]=a[1]-t,l=e.getPixelInformation(s,0,o),l&&l.valid))return l;if(s[1]=a[1]+t,l=e.getPixelInformation(s,0,o),l&&l.valid)return l}}return o[0]=r[0],o[1]=r[1],null},e.generateSelection=(r,n,o,i)=>{const a=Math.floor(r),s=Math.floor(n),l=Math.floor(o),u=Math.floor(i),c=new Map,d=[0,0];for(let r=s;r<=u;r++)for(let n=a;n<=l;n++){const o=[n,r],i=e.getPixelInformation(o,0,d);if(i&&i.valid){const e=pg(i);if(c.has(e)){const r=c.get(e);r.pixelCount++,t.captureZValues&&i.zValuet.rawPixBuffer[e],e.getPixelBuffer=e=>t.pixBuffer[e],e.attach=(e,r)=>{t._openGLRenderWindow=e,t._renderer=r};const r=e.setArea;e.setArea=function(){return!!r(...arguments)&&(t.area[0]=Math.floor(t.area[0]),t.area[1]=Math.floor(t.area[1]),t.area[2]=Math.floor(t.area[2]),t.area[3]=Math.floor(t.area[3]),!0)}}(e,t)}var xg={newInstance:zt.newInstance(bg,"vtkOpenGLHardwareSelector"),extend:bg,...wl},_g=r(735);const Sg=["lastShaderProgramBound","context","_openGLRenderWindow"],Cg={lastShaderProgramBound:null,shaderPrograms:null,context:null};function Tg(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Cg,r),t.shaderPrograms={},zt.obj(e,t),zt.setGet(e,t,Sg),zt.moveToProtected(e,t,["openGLRenderWindow"]),function(e,t){t.classHierarchy.push("vtkShaderCache"),e.replaceShaderValues=(e,r,n)=>{let o=r;n.length>0&&(o=rd.substitute(o,"VSOut","GSOut").result);const i=t._openGLRenderWindow.getWebgl2();let a="\n",s="#version 100\n";i?s="#version 300 es\n#define attribute in\n#define textureCube texture\n#define texture2D texture\n#define textureCubeLod textureLod\n#define texture2DLod textureLod\n":(t.context.getExtension("OES_standard_derivatives"),t.context.getExtension("EXT_frag_depth")&&(a="#extension GL_EXT_frag_depth : enable\n"),t.context.getExtension("EXT_shader_texture_lod")&&(a+="#extension GL_EXT_shader_texture_lod : enable\n#define textureCubeLod textureCubeLodEXT\n#define texture2DLod texture2DLodEXT")),o=rd.substitute(o,"//VTK::System::Dec",[`${s}\n`,i?"":"#extension GL_OES_standard_derivatives : enable\n",a,"#ifdef GL_FRAGMENT_PRECISION_HIGH","precision highp float;","precision highp int;","#else","precision mediump float;","precision mediump int;","#endif"]).result;let l=rd.substitute(e,"//VTK::System::Dec",[`${s}\n`,"#ifdef GL_FRAGMENT_PRECISION_HIGH","precision highp float;","precision highp int;","#else","precision mediump float;","precision mediump int;","#endif"]).result;if(i){l=rd.substitute(l,"varying","out").result,o=rd.substitute(o,"varying","in").result;let e="",t=0;for(;o.includes(`gl_FragData[${t}]`);)o=rd.substitute(o,`gl_FragData\\[${t}\\]`,`fragOutput${t}`).result,e+=`layout(location = ${t}) out vec4 fragOutput${t};\n`,t++;o=rd.substitute(o,"//VTK::Output::Dec",e).result}return{VSSource:l,FSSource:o,GSSource:rd.substitute(n,"//VTK::System::Dec",s).result}},e.readyShaderProgramArray=(t,r,n)=>{const o=e.replaceShaderValues(t,r,n),i=e.getShaderProgram(o.VSSource,o.FSSource,o.GSSource);return e.readyShaderProgram(i)},e.readyShaderProgram=t=>t&&(t.getCompiled()||t.compileShader())&&e.bindShaderProgram(t)?t:null,e.getShaderProgram=(e,r,n)=>{const o=`${e}${r}${n}`,i=_g.hash(o);if(!(i in t.shaderPrograms)){const o=rd.newInstance();return o.setContext(t.context),o.getVertexShader().setSource(e),o.getFragmentShader().setSource(r),n&&o.getGeometryShader().setSource(n),o.setMd5Hash(i),t.shaderPrograms[i]=o,o}return t.shaderPrograms[i]},e.releaseGraphicsResources=r=>{e.releaseCurrentShaderProgram(),Object.keys(t.shaderPrograms).map(e=>t.shaderPrograms[e]).forEach(e=>e.cleanup()),t.shaderPrograms={}},e.releaseCurrentShaderProgram=()=>{t.lastShaderProgramBound&&(t.lastShaderProgramBound.cleanup(),t.lastShaderProgramBound=null)},e.bindShaderProgram=e=>(t.lastShaderProgramBound===e||(t.lastShaderProgramBound&&t.lastShaderProgramBound.release(),e.bind(),t.lastShaderProgramBound=e),1)}(e,t)}var wg={newInstance:zt.newInstance(Tg,"vtkShaderCache"),extend:Tg};const{vtkErrorMacro:Ag}=zt,Eg={context:null,numberOfTextureUnits:0,textureUnits:0};function Dg(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Eg,r),zt.obj(e,t),t.textureUnits=[],zt.get(e,t,["numberOfTextureUnits"]),zt.setGet(e,t,["context"]),function(e,t){t.classHierarchy.push("vtkOpenGLTextureUnitManager"),e.deleteTable=()=>{for(let e=0;e{if(t.context!==r){if(0!==t.context&&e.deleteTable(),t.context=r,t.context){t.numberOfTextureUnits=r.getParameter(r.MAX_TEXTURE_IMAGE_UNITS);for(let e=0;e{for(let r=0;re.isAllocated(r)?-1:(t.textureUnits[r]=!0,r),e.isAllocated=e=>t.textureUnits[e],e.free=e=>{t.textureUnits[e]=!1},e.freeAll=()=>{for(let e=0;e2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Ig,r),t.size||(t.size=[300,300]),zt.getArray(e,t,["size"],2),zt.get(e,t,["selector"]),Xt.extend(e,t,r),function(e,t){t.classHierarchy.push("vtkRenderWindowViewNode"),e.getViewNodeFactory=()=>null,e.getAspectRatio=()=>t.size[0]/t.size[1],e.getAspectRatioForRenderer=e=>{const r=e.getViewportByReference();return t.size[0]*(r[2]-r[0])/((r[3]-r[1])*t.size[1])},e.isInViewport=(t,r,n)=>{const o=n.getViewportByReference(),i=e.getFramebufferSize();return o[0]*i[0]<=t&&o[2]*i[0]>=t&&o[1]*i[1]<=r&&o[3]*i[1]>=r},e.getViewportSize=t=>{const r=t.getViewportByReference(),n=e.getFramebufferSize();return[(r[2]-r[0])*n[0],(r[3]-r[1])*n[1]]},e.getViewportCenter=t=>{const r=e.getViewportSize(t);return[.5*r[0],.5*r[1]]},e.displayToNormalizedDisplay=(t,r,n)=>{const o=e.getFramebufferSize();return[t/o[0],r/o[1],n]},e.normalizedDisplayToDisplay=(t,r,n)=>{const o=e.getFramebufferSize();return[t*o[0],r*o[1],n]},e.worldToView=(e,t,r,n)=>n.worldToView(e,t,r),e.viewToWorld=(e,t,r,n)=>n.viewToWorld(e,t,r),e.worldToDisplay=(t,r,n,o)=>{const i=o.worldToView(t,r,n),a=e.getViewportSize(o),s=o.viewToProjection(i[0],i[1],i[2],a[0]/a[1]),l=o.projectionToNormalizedDisplay(s[0],s[1],s[2]);return e.normalizedDisplayToDisplay(l[0],l[1],l[2])},e.displayToWorld=(t,r,n,o)=>{const i=e.displayToNormalizedDisplay(t,r,n),a=o.normalizedDisplayToProjection(i[0],i[1],i[2]),s=e.getViewportSize(o),l=o.projectionToView(a[0],a[1],a[2],s[0]/s[1]);return o.viewToWorld(l[0],l[1],l[2])},e.normalizedDisplayToViewport=(t,r,n,o)=>{let i=o.getViewportByReference();i=e.normalizedDisplayToDisplay(i[0],i[1],0);const a=e.normalizedDisplayToDisplay(t,r,n);return[a[0]-i[0]-.5,a[1]-i[1]-.5,n]},e.viewportToNormalizedViewport=(t,r,n,o)=>{const i=e.getViewportSize(o);return i&&0!==i[0]&&0!==i[1]?[t/(i[0]-1),r/(i[1]-1),n]:[t,r,n]},e.normalizedViewportToViewport=(t,r,n,o)=>{const i=e.getViewportSize(o);return[t*(i[0]-1),r*(i[1]-1),n]},e.displayToLocalDisplay=(t,r,n)=>[t,e.getFramebufferSize()[1]-r-1,n],e.viewportToNormalizedDisplay=(t,r,n,o)=>{let i=o.getViewportByReference();i=e.normalizedDisplayToDisplay(i[0],i[1],0);const a=t+i[0]+.5,s=r+i[1]+.5;return e.displayToNormalizedDisplay(a,s,n)},e.getComputedDevicePixelRatio=()=>t.size[0]/e.getContainerSize()[0],e.getContainerSize=()=>{zt.vtkErrorMacro("not implemented")},e.getPixelData=(e,t,r,n)=>{zt.vtkErrorMacro("not implemented")},e.createSelector=()=>{zt.vtkErrorMacro("not implemented")}}(e,t)}var Ng={newInstance:zt.newInstance(Og,"vtkRenderWindowViewNode"),extend:Og};const{vtkDebugMacro:Mg,vtkErrorMacro:Rg}=zt,Fg={position:"absolute",top:0,left:0,width:"100%",height:"100%"},Bg=["activateTexture","deactivateTexture","disableCullFace","enableCullFace","get3DContext","getActiveFramebuffer","getContext","getDefaultTextureByteSize","getDefaultTextureInternalFormat","getDefaultToWebgl2","getGLInformations","getGraphicsMemoryInfo","getGraphicsResourceForObject","getHardwareMaximumLineWidth","getPixelData","getShaderCache","getTextureUnitForTexture","getTextureUnitManager","getWebgl2","makeCurrent","releaseGraphicsResources","registerGraphicsResourceUser","unregisterGraphicsResourceUser","restoreContext","setActiveFramebuffer","setContext","setDefaultToWebgl2","setGraphicsResourceForObject"];function Lg(e,t,r){const n=e.createFramebuffer(),o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.texImage2D(e.TEXTURE_2D,0,t,2,2,0,t,r,null),e.bindFramebuffer(e.FRAMEBUFFER,n),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,o,0);const i=e.checkFramebufferStatus(e.FRAMEBUFFER);return e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindTexture(e.TEXTURE_2D,null),i===e.FRAMEBUFFER_COMPLETE}let kg=0;const Ug=[];function Vg(e){e.preventDefault()}function Gg(e,t){let r;t.classHierarchy.push("vtkOpenGLRenderWindow"),e.getViewNodeFactory=()=>t.myFactory,t.canvas.addEventListener("webglcontextlost",Vg,!1),t.canvas.addEventListener("webglcontextrestored",e.restoreContext,!1);const n=[0,0];let o;e.onModified(function(){t.renderable&&(t.size[0]===n[0]&&t.size[1]===n[1]||(n[0]=t.size[0],n[1]=t.size[1],t.canvas.setAttribute("width",t.size[0]),t.canvas.setAttribute("height",t.size[1]))),t.viewStream&&t.viewStream.setSize(t.size[0],t.size[1]),t.canvas.style.display=t.useOffScreen?"none":"block",t.el&&(t.el.style.cursor=t.cursorVisibility?t.cursor:"none"),t.containerSize=null}),e.buildPass=r=>{if(r){if(!t.renderable)return;e.prepareNodes(),e.addMissingNodes(t.renderable.getRenderersByReference()),e.addMissingNodes(t.renderable.getChildRenderWindowsByReference()),e.removeUnusedNodes(),e.initialize(),t.children.forEach(t=>{t.setOpenGLRenderWindow?.(e)})}},e.initialize=()=>{if(!t.initialized){if(t.rootOpenGLRenderWindow=e.getLastAncestorOfType("vtkOpenGLRenderWindow"),t.rootOpenGLRenderWindow)t.context2D=e.get2DContext();else{t.context=e.get3DContext(),e.resizeFromChildRenderWindows(),t.context&&(kg++,Ug.forEach(e=>e(kg))),t.textureUnitManager=Pg.newInstance(),t.textureUnitManager.setContext(t.context),t.shaderCache.setContext(t.context);const r=t.context;r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA),r.depthFunc(r.LEQUAL),r.enable(r.BLEND)}t.initialized=!0}},e.makeCurrent=()=>{t.context.makeCurrent()},e.setContainer=r=>{t.el&&t.el!==r&&(t.canvas.parentNode!==t.el&&Rg("Error: canvas parent node does not match container"),t.el.removeChild(t.canvas),t.el.contains(t.bgImage)&&t.el.removeChild(t.bgImage)),t.el!==r&&(t.el=r,t.el&&(t.el.appendChild(t.canvas),t.useBackgroundImage&&t.el.appendChild(t.bgImage)),e.modified())},e.getContainer=()=>t.el,e.getContainerSize=()=>{if(!t.containerSize&&t.el){const{width:e,height:r}=t.el.getBoundingClientRect();t.containerSize=[e,r]}return t.containerSize||t.size},e.getFramebufferSize=()=>{const e=t.activeFramebuffer?.getSize();return e||t.size},e.getPixelData=(e,r,n,o)=>{const i=new Uint8Array((n-e+1)*(o-r+1)*4);return t.context.readPixels(e,r,n-e+1,o-r+1,t.context.RGBA,t.context.UNSIGNED_BYTE,i),i},e.get3DContext=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{preserveDrawingBuffer:!1,depth:!0,alpha:!0,powerPreference:"high-performance"},n=null;const o="undefined"!=typeof WebGL2RenderingContext;return t.webgl2=!1,t.defaultToWebgl2&&o&&(n=t.canvas.getContext("webgl2",e),n&&(t.webgl2=!0,Mg("using webgl2"))),n||(Mg("using webgl1"),n=t.canvas.getContext("webgl",e)||t.canvas.getContext("experimental-webgl",e)),n||Rg("no webgl context"),new Proxy(n,(r||(r=function(){const e=new Map,t={apply:(t,r,n)=>e.has(n[0])?e.get(n[0]):t.apply(r,n)},r=Object.create(null);return r.getParameter=(e,r,n,o)=>new Proxy(o.bind(e),t),r.depthMask=(t,r,n,o)=>{return new Proxy(o.bind(t),(i=t.DEPTH_WRITEMASK,{apply:(t,r,n)=>(e.set(i,n[0]),t.apply(r,n))}));var i},{get(e,t,n){if("__getUnderlyingContext"===t)return()=>e;let o=Reflect.get(e,t,e);o instanceof Function&&(o=o.bind(e));const i=r[t];return i?i(e,t,n,o):o}}}()),r))},e.get2DContext=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t.canvas.getContext("2d",e)},e.restoreContext=()=>{const t=Wm.newInstance();t.setCurrentOperation("Release"),t.traverse(e,null)},e.activateTexture=r=>{const n=t._textureResourceIds.get(r);if(void 0!==n)return void t.context.activeTexture(t.context.TEXTURE0+n);const o=e.getTextureUnitManager().allocate();o<0?Rg("Hardware does not support the number of textures defined."):(t._textureResourceIds.set(r,o),t.context.activeTexture(t.context.TEXTURE0+o))},e.deactivateTexture=r=>{const n=t._textureResourceIds.get(r);void 0!==n&&(e.getTextureUnitManager().free(n),t._textureResourceIds.delete(r))},e.getTextureUnitForTexture=e=>{const r=t._textureResourceIds.get(e);return void 0!==r?r:-1},e.getDefaultTextureByteSize=function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(t.webgl2)switch(e){case us.CHAR:case us.SIGNED_CHAR:case us.UNSIGNED_CHAR:return 1;case r:case n:case us.UNSIGNED_SHORT:case us.SHORT:case us.VOID:return 2;default:return 4}return 1},e.getDefaultTextureInternalFormat=function(e,r){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,o=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(t.webgl2)switch(e){case us.UNSIGNED_CHAR:switch(r){case 1:return t.context.R8;case 2:return t.context.RG8;case 3:return t.context.RGB8;default:return t.context.RGBA8}case n&&!o&&us.UNSIGNED_SHORT:switch(r){case 1:return n.R16_EXT;case 2:return n.RG16_EXT;case 3:return n.RGB16_EXT;default:return n.RGBA16_EXT}case n&&!o&&us.SHORT:switch(r){case 1:return n.R16_SNORM_EXT;case 2:return n.RG16_SNORM_EXT;case 3:return n.RGB16_SNORM_EXT;default:return n.RGBA16_SNORM_EXT}default:switch(r){case 1:return o?t.context.R16F:t.context.R32F;case 2:return o?t.context.RG16F:t.context.RG32F;case 3:return o?t.context.RGB16F:t.context.RGB32F;default:return o?t.context.RGBA16F:t.context.RGBA32F}}switch(r){case 1:return t.context.LUMINANCE;case 2:return t.context.LUMINANCE_ALPHA;case 3:return t.context.RGB;default:return t.context.RGBA}},e.setBackgroundImage=e=>{t.bgImage.src=e.src},e.setUseBackgroundImage=e=>{t.useBackgroundImage=e,t.useBackgroundImage&&!t.el.contains(t.bgImage)?t.el.appendChild(t.bgImage):!t.useBackgroundImage&&t.el.contains(t.bgImage)&&t.el.removeChild(t.bgImage)},e.captureNextImage=function(){let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"image/png",{resetCamera:n=!1,size:o=null,scale:i=1}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(t.deleted)return null;t.imageFormat=r;const a=t.notifyStartCaptureImage;return t.notifyStartCaptureImage=!0,t._screenshot={size:o||1!==i?o||t.size.map(e=>e*i):null},new Promise((r,o)=>{const i=e.onImageReady(o=>{if(null===t._screenshot.size)t.notifyStartCaptureImage=a,i.unsubscribe(),t._screenshot.placeHolder&&(t.size=t._screenshot.originalSize,e.modified(),t._screenshot.cameras&&t._screenshot.cameras.forEach(e=>{let{restoreParamsFn:t,arg:r}=e;return t(r)}),e.traverseAllPasses(),t.el.removeChild(t._screenshot.placeHolder),t._screenshot.placeHolder.remove(),t._screenshot=null),r(o);else{const r=document.createElement("img");if(r.style=Fg,r.src=o,t._screenshot.placeHolder=t.el.appendChild(r),t.canvas.style.display="none",t._screenshot.originalSize=t.size,t.size=t._screenshot.size,t.rootOpenGLRenderWindow?.resizeFromChildRenderWindows(),t._screenshot.size=null,e.modified(),n){const e=!0!==n;t._screenshot.cameras=t.renderable.getRenderers().map(t=>{const r=t.getActiveCamera(),o=r.get("focalPoint","position","parallelScale");return{resetCameraArgs:e?{renderer:t}:void 0,resetCameraFn:e?n:t.resetCamera,restoreParamsFn:r.set,arg:JSON.parse(JSON.stringify(o))}}),t._screenshot.cameras.forEach(e=>{let{resetCameraFn:t,resetCameraArgs:r}=e;return t(r)})}e.traverseAllPasses()}})})},e.getHardwareMaximumLineWidth=()=>{if(null!=o)return o;const t=e.get3DContext(),r=t.getParameter(t.ALIASED_LINE_WIDTH_RANGE);return o=r[1],r[1]},e.getGLInformations=()=>{if(t._glInformation)return t._glInformation;const r=e.get3DContext(),n=r.getExtension("OES_texture_float"),o=r.getExtension("OES_texture_half_float"),i=r.getExtension("WEBGL_debug_renderer_info"),a=r.getExtension("WEBGL_draw_buffers"),s=r.getExtension("EXT_texture_filter_anisotropic")||r.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),l=[["Max Vertex Attributes","MAX_VERTEX_ATTRIBS",r.getParameter(r.MAX_VERTEX_ATTRIBS)],["Max Varying Vectors","MAX_VARYING_VECTORS",r.getParameter(r.MAX_VARYING_VECTORS)],["Max Vertex Uniform Vectors","MAX_VERTEX_UNIFORM_VECTORS",r.getParameter(r.MAX_VERTEX_UNIFORM_VECTORS)],["Max Fragment Uniform Vectors","MAX_FRAGMENT_UNIFORM_VECTORS",r.getParameter(r.MAX_FRAGMENT_UNIFORM_VECTORS)],["Max Fragment Texture Image Units","MAX_TEXTURE_IMAGE_UNITS",r.getParameter(r.MAX_TEXTURE_IMAGE_UNITS)],["Max Vertex Texture Image Units","MAX_VERTEX_TEXTURE_IMAGE_UNITS",r.getParameter(r.MAX_VERTEX_TEXTURE_IMAGE_UNITS)],["Max Combined Texture Image Units","MAX_COMBINED_TEXTURE_IMAGE_UNITS",r.getParameter(r.MAX_COMBINED_TEXTURE_IMAGE_UNITS)],["Max 2D Texture Size","MAX_TEXTURE_SIZE",r.getParameter(r.MAX_TEXTURE_SIZE)],["Max Cube Texture Size","MAX_CUBE_MAP_TEXTURE_SIZE",r.getParameter(r.MAX_CUBE_MAP_TEXTURE_SIZE)],["Max Texture Anisotropy","MAX_TEXTURE_MAX_ANISOTROPY_EXT",s&&r.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT)],["Point Size Range","ALIASED_POINT_SIZE_RANGE",r.getParameter(r.ALIASED_POINT_SIZE_RANGE).join(" - ")],["Line Width Range","ALIASED_LINE_WIDTH_RANGE",r.getParameter(r.ALIASED_LINE_WIDTH_RANGE).join(" - ")],["Max Viewport Dimensions","MAX_VIEWPORT_DIMS",r.getParameter(r.MAX_VIEWPORT_DIMS).join(" - ")],["Max Renderbuffer Size","MAX_RENDERBUFFER_SIZE",r.getParameter(r.MAX_RENDERBUFFER_SIZE)],["Framebuffer Red Bits","RED_BITS",r.getParameter(r.RED_BITS)],["Framebuffer Green Bits","GREEN_BITS",r.getParameter(r.GREEN_BITS)],["Framebuffer Blue Bits","BLUE_BITS",r.getParameter(r.BLUE_BITS)],["Framebuffer Alpha Bits","ALPHA_BITS",r.getParameter(r.ALPHA_BITS)],["Framebuffer Depth Bits","DEPTH_BITS",r.getParameter(r.DEPTH_BITS)],["Framebuffer Stencil Bits","STENCIL_BITS",r.getParameter(r.STENCIL_BITS)],["Framebuffer Subpixel Bits","SUBPIXEL_BITS",r.getParameter(r.SUBPIXEL_BITS)],["MSAA Samples","SAMPLES",r.getParameter(r.SAMPLES)],["MSAA Sample Buffers","SAMPLE_BUFFERS",r.getParameter(r.SAMPLE_BUFFERS)],["Supported Formats for UByte Render Targets ","UNSIGNED_BYTE RENDER TARGET FORMATS",[n&&Lg(r,r.RGBA,r.UNSIGNED_BYTE)?"RGBA":"",n&&Lg(r,r.RGB,r.UNSIGNED_BYTE)?"RGB":"",n&&Lg(r,r.LUMINANCE,r.UNSIGNED_BYTE)?"LUMINANCE":"",n&&Lg(r,r.ALPHA,r.UNSIGNED_BYTE)?"ALPHA":"",n&&Lg(r,r.LUMINANCE_ALPHA,r.UNSIGNED_BYTE)?"LUMINANCE_ALPHA":""].join(" ")],["Supported Formats for Half Float Render Targets","HALF FLOAT RENDER TARGET FORMATS",[o&&Lg(r,r.RGBA,o.HALF_FLOAT_OES)?"RGBA":"",o&&Lg(r,r.RGB,o.HALF_FLOAT_OES)?"RGB":"",o&&Lg(r,r.LUMINANCE,o.HALF_FLOAT_OES)?"LUMINANCE":"",o&&Lg(r,r.ALPHA,o.HALF_FLOAT_OES)?"ALPHA":"",o&&Lg(r,r.LUMINANCE_ALPHA,o.HALF_FLOAT_OES)?"LUMINANCE_ALPHA":""].join(" ")],["Supported Formats for Full Float Render Targets","FLOAT RENDER TARGET FORMATS",[n&&Lg(r,r.RGBA,r.FLOAT)?"RGBA":"",n&&Lg(r,r.RGB,r.FLOAT)?"RGB":"",n&&Lg(r,r.LUMINANCE,r.FLOAT)?"LUMINANCE":"",n&&Lg(r,r.ALPHA,r.FLOAT)?"ALPHA":"",n&&Lg(r,r.LUMINANCE_ALPHA,r.FLOAT)?"LUMINANCE_ALPHA":""].join(" ")],["Max Multiple Render Targets Buffers","MAX_DRAW_BUFFERS_WEBGL",a?r.getParameter(a.MAX_DRAW_BUFFERS_WEBGL):0],["High Float Precision in Vertex Shader","HIGH_FLOAT VERTEX_SHADER",[r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.HIGH_FLOAT).precision," (-2",r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.HIGH_FLOAT).rangeMin," - 2",r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.HIGH_FLOAT).rangeMax,")"].join("")],["Medium Float Precision in Vertex Shader","MEDIUM_FLOAT VERTEX_SHADER",[r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.MEDIUM_FLOAT).precision," (-2",r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.MEDIUM_FLOAT).rangeMin," - 2",r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.MEDIUM_FLOAT).rangeMax,")"].join("")],["Low Float Precision in Vertex Shader","LOW_FLOAT VERTEX_SHADER",[r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.LOW_FLOAT).precision," (-2",r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.LOW_FLOAT).rangeMin," - 2",r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.LOW_FLOAT).rangeMax,")"].join("")],["High Float Precision in Fragment Shader","HIGH_FLOAT FRAGMENT_SHADER",[r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.HIGH_FLOAT).precision," (-2",r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.HIGH_FLOAT).rangeMin," - 2",r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.HIGH_FLOAT).rangeMax,")"].join("")],["Medium Float Precision in Fragment Shader","MEDIUM_FLOAT FRAGMENT_SHADER",[r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.MEDIUM_FLOAT).precision," (-2",r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.MEDIUM_FLOAT).rangeMin," - 2",r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.MEDIUM_FLOAT).rangeMax,")"].join("")],["Low Float Precision in Fragment Shader","LOW_FLOAT FRAGMENT_SHADER",[r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.LOW_FLOAT).precision," (-2",r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.LOW_FLOAT).rangeMin," - 2",r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.LOW_FLOAT).rangeMax,")"].join("")],["High Int Precision in Vertex Shader","HIGH_INT VERTEX_SHADER",[r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.HIGH_INT).precision," (-2",r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.HIGH_INT).rangeMin," - 2",r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.HIGH_INT).rangeMax,")"].join("")],["Medium Int Precision in Vertex Shader","MEDIUM_INT VERTEX_SHADER",[r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.MEDIUM_INT).precision," (-2",r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.MEDIUM_INT).rangeMin," - 2",r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.MEDIUM_INT).rangeMax,")"].join("")],["Low Int Precision in Vertex Shader","LOW_INT VERTEX_SHADER",[r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.LOW_INT).precision," (-2",r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.LOW_INT).rangeMin," - 2",r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.LOW_INT).rangeMax,")"].join("")],["High Int Precision in Fragment Shader","HIGH_INT FRAGMENT_SHADER",[r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.HIGH_INT).precision," (-2",r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.HIGH_INT).rangeMin," - 2",r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.HIGH_INT).rangeMax,")"].join("")],["Medium Int Precision in Fragment Shader","MEDIUM_INT FRAGMENT_SHADER",[r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.MEDIUM_INT).precision," (-2",r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.MEDIUM_INT).rangeMin," - 2",r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.MEDIUM_INT).rangeMax,")"].join("")],["Low Int Precision in Fragment Shader","LOW_INT FRAGMENT_SHADER",[r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.LOW_INT).precision," (-2",r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.LOW_INT).rangeMin," - 2",r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.LOW_INT).rangeMax,")"].join("")],["Supported Extensions","EXTENSIONS",r.getSupportedExtensions().join("
\t\t\t\t\t ")],["WebGL Renderer","RENDERER",r.getParameter(r.RENDERER)],["WebGL Vendor","VENDOR",r.getParameter(r.VENDOR)],["WebGL Version","VERSION",r.getParameter(r.VERSION)],["Shading Language Version","SHADING_LANGUAGE_VERSION",r.getParameter(r.SHADING_LANGUAGE_VERSION)],["Unmasked Renderer","UNMASKED_RENDERER",i&&r.getParameter(i.UNMASKED_RENDERER_WEBGL)],["Unmasked Vendor","UNMASKED_VENDOR",i&&r.getParameter(i.UNMASKED_VENDOR_WEBGL)],["WebGL Version","WEBGL_VERSION",t.webgl2?2:1]],u={};for(;l.length;){const[e,t,r]=l.pop();t&&(u[t]={label:e,value:r})}return t._glInformation=u,u},e.traverseAllPasses=()=>{if(t.renderPasses)for(let r=0;r0&&void 0!==arguments[0]?arguments[0]:t.imageFormat;const n=document.createElement("canvas"),o=n.getContext("2d");n.width=t.canvas.width,n.height=t.canvas.height,o.drawImage(t.canvas,0,0);const i=t.canvas.getBoundingClientRect();t.renderable.getRenderers().forEach(e=>{e.getViewProps().forEach(e=>{if(e.getContainer){const t=e.getContainer().getElementsByTagName("canvas");for(let e=0;e{const e=t.rootOpenGLRenderWindow;if(!e||!t.context2D||t.children.some(e=>!!e.getSelector?.()))return;const r=e.getCanvas(),n=t.canvas;t.context2D.drawImage(r,0,r.height-n.height,n.width,n.height,0,0,n.width,n.height)},e.resizeFromChildRenderWindows=()=>{const r=t.renderable.getChildRenderWindowsByReference();if(r.length>0){const t=[0,0];for(let n=0;nt[0]?o[0]:t[0],t[1]=o[1]>t[1]?o[1]:t[1])}e.setSize(...t)}},e.disableCullFace=()=>{t.cullFaceEnabled&&(t.context.disable(t.context.CULL_FACE),t.cullFaceEnabled=!1)},e.enableCullFace=()=>{t.cullFaceEnabled||(t.context.enable(t.context.CULL_FACE),t.cullFaceEnabled=!0)},e.setViewStream=r=>t.viewStream!==r&&(t.subscription&&(t.subscription.unsubscribe(),t.subscription=null),t.viewStream=r,t.viewStream&&(t.renderable.getRenderers()[0].getBackgroundByReference()[3]=0,e.setUseBackgroundImage(!0),t.subscription=t.viewStream.onImageReady(t=>e.setBackgroundImage(t.image)),t.viewStream.setSize(t.size[0],t.size[1]),t.viewStream.invalidateCache(),t.viewStream.render(),e.modified()),!0),e.createSelector=()=>{const t=xg.newInstance();return t.setOpenGLRenderWindow(e),t},e.delete=zt.chain(()=>{t.context&&(kg--,Ug.forEach(e=>e(kg))),e.setContainer(),e.setViewStream()},function(){t.canvas.removeEventListener("webglcontextlost",Vg),t.canvas.removeEventListener("webglcontextrestored",e.restoreContext)},e.delete),e.setActiveFramebuffer=e=>{t.activeFramebuffer=e};const i=e.setSize;e.setSize=(t,r)=>{const n=i(t,r);return n&&e.invokeWindowResizeEvent({width:t,height:r}),n},e.registerGraphicsResourceUser=(r,n)=>{t._graphicsResources.has(r)||e.setGraphicsResourceForObject(r,null,null);const o=t._graphicsResources.get(r);o?.users.add(n)},e.unregisterGraphicsResourceUser=(r,n)=>{const o=t._graphicsResources.get(r);o&&(o.users.delete(n),o.users.size||(o.oglObject?.releaseGraphicsResources(e),t._graphicsResources.delete(r)))},e.getGraphicsResourceForObject=e=>t._graphicsResources.get(e),e.setGraphicsResourceForObject=(r,n,o)=>{if(!r)return;const i=t._graphicsResources.get(r);i?.oglObject?.releaseGraphicsResources(e),t._graphicsResources.set(r,{coreObject:r,oglObject:n,hash:o,users:i?.users??new Set})},e.getGraphicsMemoryInfo=()=>{let e=0;return t._graphicsResources.forEach(t=>{let{oglObject:r}=t;e+=r.getAllocatedGPUMemoryInBytes()}),e},e.releaseGraphicsResources=()=>{null!==t.shaderCache&&t.shaderCache.releaseGraphicsResources(e),t._graphicsResources.forEach(t=>{let{oglObject:r}=t;r.releaseGraphicsResources(e)}),t._graphicsResources.clear(),null!==t.textureUnitManager&&t.textureUnitManager.freeAll(),t.renderable.getRenderersByReference().forEach(t=>{const r=e.getViewNodeFor(t);r?.releaseGraphicsResources()})};const a={...e};Bg.forEach(r=>{e[r]=function(){return t.rootOpenGLRenderWindow?t.rootOpenGLRenderWindow[r](...arguments):a[r](...arguments)}})}const zg={cullFaceEnabled:!1,shaderCache:null,initialized:!1,context:null,context2D:null,canvas:null,cursorVisibility:!0,cursor:"pointer",textureUnitManager:null,textureResourceIds:null,containerSize:null,renderPasses:[],notifyStartCaptureImage:!1,webgl2:!1,defaultToWebgl2:!0,activeFramebuffer:null,imageFormat:"image/png",useOffScreen:!1,useBackgroundImage:!1};function jg(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,zg,r),Ng.extend(e,t,r),t.canvas||(t.canvas=document.createElement("canvas"),t.canvas.style.width="100%"),t.selector||(t.selector=xg.newInstance(),t.selector.setOpenGLRenderWindow(e)),t.bgImage=new Image,t.bgImage.style.position="absolute",t.bgImage.style.left="0",t.bgImage.style.top="0",t.bgImage.style.width="100%",t.bgImage.style.height="100%",t.bgImage.style.zIndex="-1",t._textureResourceIds=new Map,t._graphicsResources=new Map,t._glInformation=null,t.myFactory=tr.newInstance(),t.shaderCache=wg.newInstance(),t.shaderCache.setOpenGLRenderWindow(e),t.renderPasses[0]=Zm.newInstance(),zt.get(e,t,["shaderCache","textureUnitManager","webgl2","useBackgroundImage","activeFramebuffer","rootOpenGLRenderWindow"]),zt.setGet(e,t,["initialized","context","context2D","canvas","renderPasses","notifyStartCaptureImage","defaultToWebgl2","cursor","useOffScreen"]),zt.setGetArray(e,t,["size"],2),zt.event(e,t,"imageReady"),zt.event(e,t,"windowResizeEvent"),Gg(e,t)}const Wg=zt.newInstance(jg,"vtkOpenGLRenderWindow");Zh("WebGL",Wg);var Hg={newInstance:Wg,extend:jg,pushMonitorGLContextCount:function(e){Ug.push(e)},popMonitorGLContextCount:function(e){return Ug.pop()}};Qt("vtkRenderWindow",Wg);const Kg=["setBindGroup","setIndexBuffer","setVertexBuffer","draw","drawIndexed"],Xg={description:null,handle:null,boundPipeline:null,pipelineHash:null,pipelineSettings:null,replaceShaderCodeFunction:null,depthTextureView:null,label:null};function $g(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Xg,r),mt(e,t),t.description={colorAttachments:[{view:void 0,loadOp:"load",storeOp:"store"}],depthStencilAttachment:{view:void 0,depthLoadOp:"clear",depthClearValue:0,depthStoreOp:"store"}},t.replaceShaderCodeFunction=e=>{const t=e.getShaderDescription("fragment");t.addOutput("vec4","outColor");let r=t.getCode();r=Np.substitute(r,"//VTK::RenderEncoder::Impl",["output.outColor = computedColor;"]).result,t.setCode(r)},t.pipelineSettings={primitive:{cullMode:"none"},depthStencil:{depthWriteEnabled:!0,depthCompare:"greater-equal",format:"depth32float"},fragment:{targets:[{format:"rgba16float",blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha"}}}]}},t.colorTextureViews=[],yt(e,t,["boundPipeline","colorTextureViews"]),_t(e,t,["depthTextureView","description","handle","label","pipelineHash","pipelineSettings","replaceShaderCodeFunction"]),function(e,t){t.classHierarchy.push("vtkWebGPURenderEncoder"),e.begin=e=>{t.drawCallbacks=[],t.handle=e.beginRenderPass(t.description),t.label&&t.handle.pushDebugGroup(t.label)},e.end=()=>{for(let r=0;r{if(t.boundPipeline===e)return;t.handle.setPipeline(e.getHandle());const r=e.getPipelineDescription();if(t.colorTextureViews.length!==r.fragment.targets.length)console.log(`mismatched attachment counts on pipeline ${r.fragment.targets.length} while encoder has ${t.colorTextureViews.length}`),console.trace();else for(let e=0;e{t.replaceShaderCodeFunction(e)},e.setColorTextureView=(e,r)=>{t.colorTextureViews[e]!==r&&(t.colorTextureViews[e]=r)},e.activateBindGroup=e=>{const r=t.boundPipeline.getDevice(),n=t.boundPipeline.getBindGroupLayoutCount(e.getLabel());t.handle.setBindGroup(n,e.getBindGroup(r));const o=r.getBindGroupLayoutDescription(e.getBindGroupLayout(r)),i=r.getBindGroupLayoutDescription(t.boundPipeline.getBindGroupLayout(n));o!==i&&(console.log(`renderEncoder ${t.pipelineHash} mismatched bind group layouts bind group has\n${o}\n versus pipeline\n${i}\n`),console.trace())},e.attachTextureViews=()=>{for(let e=0;e{for(let n=0;n2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Yg,r),Wm.extend(e,t,r),zt.get(e,t,["colorTexture","depthTexture"]),function(e,t){t.classHierarchy.push("vtkWebGPUOpaquePass"),e.traverse=(r,n)=>{if(t.deleted)return;t._currentParent=n;const o=n.getDevice();if(t.renderEncoder)t.colorTexture.resize(n.getCanvas().width,n.getCanvas().height),t.depthTexture.resize(n.getCanvas().width,n.getCanvas().height);else{e.createRenderEncoder(),t.colorTexture=Oh.newInstance({label:"opaquePassColor"}),t.colorTexture.create(o,{width:n.getCanvas().width,height:n.getCanvas().height,format:"rgba16float",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC});const r=t.colorTexture.createView("opaquePassColorTexture");t.renderEncoder.setColorTextureView(0,r),t.depthFormat="depth32float",t.depthTexture=Oh.newInstance({label:"opaquePassDepth"}),t.depthTexture.create(o,{width:n.getCanvas().width,height:n.getCanvas().height,format:t.depthFormat,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC});const i=t.depthTexture.createView("opaquePassDepthTexture");t.renderEncoder.setDepthTextureView(i)}t.renderEncoder.attachTextureViews(),e.setCurrentOperation("opaquePass"),r.setRenderEncoder(t.renderEncoder),r.traverse(e)},e.getColorTextureView=()=>t.renderEncoder.getColorTextureViews()[0],e.getDepthTextureView=()=>t.renderEncoder.getDepthTextureView(),e.createRenderEncoder=()=>{t.renderEncoder=qg.newInstance({label:"OpaquePass"}),t.renderEncoder.setPipelineHash("op")}}(e,t)}var Qg={newInstance:zt.newInstance(Jg,"vtkWebGPUOpaquePass"),extend:Jg};const Zg={colorTextureView:null,depthTextureView:null};function ey(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Zg,r),Wm.extend(e,t,r),zt.setGet(e,t,["colorTextureView","depthTextureView"]),function(e,t){t.classHierarchy.push("vtkWebGPUOrderIndependentTranslucentPass"),e.traverse=(r,n)=>{if(t.deleted)return;t._currentParent=n;const o=n.getDevice();if(t.translucentRenderEncoder)t.translucentColorTexture.resizeToMatch(t.colorTextureView.getTexture()),t.translucentAccumulateTexture.resizeToMatch(t.colorTextureView.getTexture());else{e.createRenderEncoder(),e.createFinalEncoder(),t.translucentColorTexture=Oh.newInstance({label:"translucentPassColor"}),t.translucentColorTexture.create(o,{width:n.getCanvas().width,height:n.getCanvas().height,format:"rgba16float",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING});const r=t.translucentColorTexture.createView("oitpColorTexture");t.translucentRenderEncoder.setColorTextureView(0,r),t.translucentAccumulateTexture=Oh.newInstance({label:"translucentPassAccumulate"}),t.translucentAccumulateTexture.create(o,{width:n.getCanvas().width,height:n.getCanvas().height,format:"r16float",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING});const i=t.translucentAccumulateTexture.createView("oitpAccumTexture");t.translucentRenderEncoder.setColorTextureView(1,i),t.fullScreenQuad=rf.newInstance(),t.fullScreenQuad.setDevice(n.getDevice()),t.fullScreenQuad.setPipelineHash("oitpfsq"),t.fullScreenQuad.setTextureViews(t.translucentRenderEncoder.getColorTextureViews()),t.fullScreenQuad.setFragmentShaderTemplate("\n//VTK::Mapper::Dec\n\n//VTK::TCoord::Dec\n\n//VTK::RenderEncoder::Dec\n\n//VTK::IOStructs::Dec\n\n@fragment\nfn main(\n//VTK::IOStructs::Input\n)\n//VTK::IOStructs::Output\n{\n var output: fragmentOutput;\n\n var tcoord: vec2 = vec2(i32(input.fragPos.x), i32(input.fragPos.y));\n var reveal: f32 = textureLoad(oitpAccumTexture, tcoord, 0).r;\n if (reveal == 1.0) { discard; }\n var tcolor: vec4 = textureLoad(oitpColorTexture, tcoord, 0);\n var total: f32 = max(tcolor.a, 0.01);\n var computedColor: vec4 = vec4(tcolor.r/total, tcolor.g/total, tcolor.b/total, 1.0 - reveal);\n\n //VTK::RenderEncoder::Impl\n return output;\n}\n")}t.translucentRenderEncoder.setDepthTextureView(t.depthTextureView),t.translucentRenderEncoder.attachTextureViews(),e.setCurrentOperation("translucentPass"),r.setRenderEncoder(t.translucentRenderEncoder),r.traverse(e),e.finalPass(n,r)},e.finalPass=(e,r)=>{t.translucentFinalEncoder.setColorTextureView(0,t.colorTextureView),t.translucentFinalEncoder.attachTextureViews(),t.translucentFinalEncoder.begin(e.getCommandEncoder()),r.scissorAndViewport(t.translucentFinalEncoder),t.fullScreenQuad.prepareAndDraw(t.translucentFinalEncoder),t.translucentFinalEncoder.end()},e.getTextures=()=>[t.translucentColorTexture,t.translucentAccumulateTexture],e.createRenderEncoder=()=>{t.translucentRenderEncoder=qg.newInstance({label:"translucentRender"});const e=t.translucentRenderEncoder.getDescription();e.colorAttachments=[{view:void 0,clearValue:[0,0,0,0],loadOp:"clear",storeOp:"store"},{view:void 0,clearValue:[1,0,0,0],loadOp:"clear",storeOp:"store"}],e.depthStencilAttachment={view:void 0,depthLoadOp:"load",depthStoreOp:"store"},t.translucentRenderEncoder.setReplaceShaderCodeFunction(e=>{const t=e.getShaderDescription("fragment");t.addOutput("vec4","outColor"),t.addOutput("f32","outAccum"),t.addBuiltinInput("vec4","@builtin(position) fragPos");let r=t.getCode();r=Np.substitute(r,"//VTK::RenderEncoder::Impl",["var w: f32 = computedColor.a * pow(0.1 + input.fragPos.z, 2.0);","output.outColor = vec4(computedColor.rgb*w, w);","output.outAccum = computedColor.a;"]).result,t.setCode(r)}),t.translucentRenderEncoder.setPipelineHash("oitpr"),t.translucentRenderEncoder.setPipelineSettings({primitive:{cullMode:"none"},depthStencil:{depthWriteEnabled:!1,depthCompare:"greater",format:"depth32float"},fragment:{targets:[{format:"rgba16float",blend:{color:{srcFactor:"one",dstFactor:"one"},alpha:{srcFactor:"one",dstFactor:"one"}}},{format:"r16float",blend:{color:{srcFactor:"zero",dstFactor:"one-minus-src"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha"}}}]}})},e.createFinalEncoder=()=>{t.translucentFinalEncoder=qg.newInstance({label:"translucentFinal"}),t.translucentFinalEncoder.setDescription({colorAttachments:[{view:null,loadOp:"load",storeOp:"store"}]}),t.translucentFinalEncoder.setReplaceShaderCodeFunction(e=>{const t=e.getShaderDescription("fragment");t.addOutput("vec4","outColor"),t.addBuiltinInput("vec4","@builtin(position) fragPos");let r=t.getCode();r=Np.substitute(r,"//VTK::RenderEncoder::Impl",["output.outColor = vec4(computedColor.rgb, computedColor.a);"]).result,t.setCode(r)}),t.translucentFinalEncoder.setPipelineHash("oitpf"),t.translucentFinalEncoder.setPipelineSettings({primitive:{cullMode:"none"},fragment:{targets:[{format:"rgba16float",blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha"}}}]}})}}(e,t)}var ty={newInstance:zt.newInstance(ey,"vtkWebGPUOrderIndependentTranslucentPass"),extend:ey};const ry=0,ny=1,oy=2,iy=3,ay=4,sy=new Float64Array(16),ly=new Float64Array(16),uy={volumes:null,rowLength:1024,lastVolumeLength:0};function cy(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,uy,r),rf.extend(e,t,r),t.fragmentShaderTemplate="\n//VTK::Renderer::Dec\n\n//VTK::Mapper::Dec\n\n//VTK::TCoord::Dec\n\n//VTK::Volume::TraverseDec\n\n//VTK::RenderEncoder::Dec\n\n//VTK::IOStructs::Dec\n\nfn getTextureValue(vTex: texture_3d, tpos: vec4) -> f32\n{\n // todo multicomponent support\n return textureSampleLevel(vTex, clampSampler, tpos.xyz, 0.0).r;\n}\n\nfn getGradient(vTex: texture_3d, tpos: vec4, vNum: i32, scalar: f32) -> vec4\n{\n var result: vec4;\n\n var tstep: vec4 = volumeSSBO.values[vNum].tstep;\n result.x = getTextureValue(vTex, tpos + vec4(tstep.x, 0.0, 0.0, 1.0)) - scalar;\n result.y = getTextureValue(vTex, tpos + vec4(0.0, tstep.y, 0.0, 1.0)) - scalar;\n result.z = getTextureValue(vTex, tpos + vec4(0.0, 0.0, tstep.z, 1.0)) - scalar;\n result.w = 0.0;\n\n // divide by spacing as that is our delta\n result = result / volumeSSBO.values[vNum].spacing;\n // now we have a gradient in unit tcoords\n\n var grad: f32 = length(result.xyz);\n if (grad > 0.0)\n {\n // rotate to View Coords, needed for lighting and shading\n var nMat: mat4x4 = rendererUBO.SCVCMatrix * volumeSSBO.values[vNum].planeNormals;\n result = nMat * result;\n result = result / length(result);\n }\n\n // store gradient magnitude in .w\n result.w = grad;\n\n return result;\n}\n\nfn processVolume(vTex: texture_3d, vNum: i32, cNum: i32, posSC: vec4, tfunRows: f32) -> vec4\n{\n var outColor: vec4 = vec4(0.0, 0.0, 0.0, 0.0);\n\n // convert to tcoords and reject if outside the volume\n var tpos: vec4 = volumeSSBO.values[vNum].SCTCMatrix*posSC;\n if (tpos.x < 0.0 || tpos.y < 0.0 || tpos.z < 0.0 ||\n tpos.x > 1.0 || tpos.y > 1.0 || tpos.z > 1.0) { return outColor; }\n\n var scalar: f32 = getTextureValue(vTex, tpos);\n\n var coord: vec2 =\n vec2(scalar * componentSSBO.values[cNum].cScale + componentSSBO.values[cNum].cShift,\n (0.5 + 2.0 * f32(vNum)) / tfunRows);\n var color: vec4 = textureSampleLevel(tfunTexture, clampSampler, coord, 0.0);\n\n var gofactor: f32 = 1.0;\n var normal: vec4 = vec4(0.0,0.0,0.0,0.0);\n if (componentSSBO.values[cNum].gomin < 1.0 || volumeSSBO.values[vNum].shade[0] > 0.0)\n {\n normal = getGradient(vTex, tpos, vNum, scalar);\n if (componentSSBO.values[cNum].gomin < 1.0)\n {\n gofactor = clamp(normal.a*componentSSBO.values[cNum].goScale + componentSSBO.values[cNum].goShift,\n componentSSBO.values[cNum].gomin, componentSSBO.values[cNum].gomax);\n }\n }\n\n coord.x = (scalar * componentSSBO.values[cNum].oScale + componentSSBO.values[cNum].oShift);\n var opacity: f32 = textureSampleLevel(ofunTexture, clampSampler, coord, 0.0).r;\n\n if (volumeSSBO.values[vNum].shade[0] > 0.0)\n {\n color = color*abs(normal.z);\n }\n\n outColor = vec4(color.rgb, gofactor * opacity);\n\n return outColor;\n}\n\n// adjust the start and end point of a raycast such that it intersects the unit cube.\n// This function is used to take a raycast starting point and step vector\n// and numSteps and return the startijng and ending steps for intersecting the\n// unit cube. Recall for a 3D texture, the unit cube is the range of texture coordsinates\n// that have valid values. So this funtion can be used to take a ray in texture coordinates\n// and bound it to intersecting the texture.\n//\nfn adjustBounds(tpos: vec4, tstep: vec4, numSteps: f32) -> vec2\n{\n var result: vec2 = vec2(0.0, numSteps);\n var tpos2: vec4 = tpos + tstep*numSteps;\n\n // move tpos to the start of the volume\n var adjust: f32 =\n min(\n max(tpos.x/tstep.x, (tpos.x - 1.0)/tstep.x),\n min(\n max((tpos.y - 1.0)/tstep.y, tpos.y/tstep.y),\n max((tpos.z - 1.0)/tstep.z, tpos.z/tstep.z)));\n if (adjust < 0.0)\n {\n result.x = result.x - adjust;\n }\n\n // adjust length to the end\n adjust =\n max(\n min(tpos2.x/tstep.x, (tpos2.x - 1.0)/tstep.x),\n max(\n min((tpos2.y - 1.0)/tstep.y, tpos2.y/tstep.y),\n min((tpos2.z - 1.0)/tstep.z, tpos2.z/tstep.z)));\n if (adjust > 0.0)\n {\n result.y = result.y - adjust;\n }\n\n return result;\n}\n\nfn getSimpleColor(scalar: f32, vNum: i32, cNum: i32) -> vec4\n{\n // how many rows (tfuns) do we have in our tfunTexture\n var tfunRows: f32 = f32(textureDimensions(tfunTexture).y);\n\n var coord: vec2 =\n vec2(scalar * componentSSBO.values[cNum].cScale + componentSSBO.values[cNum].cShift,\n (0.5 + 2.0 * f32(vNum)) / tfunRows);\n var color: vec4 = textureSampleLevel(tfunTexture, clampSampler, coord, 0.0);\n coord.x = (scalar * componentSSBO.values[cNum].oScale + componentSSBO.values[cNum].oShift);\n var opacity: f32 = textureSampleLevel(ofunTexture, clampSampler, coord, 0.0).r;\n return vec4(color.rgb, opacity);\n}\n\nfn traverseMax(vTex: texture_3d, vNum: i32, cNum: i32, rayLengthSC: f32, minPosSC: vec4, rayStepSC: vec4)\n{\n // convert to tcoords and reject if outside the volume\n var numSteps: f32 = rayLengthSC/mapperUBO.SampleDistance;\n var tpos: vec4 = volumeSSBO.values[vNum].SCTCMatrix*minPosSC;\n var tpos2: vec4 = volumeSSBO.values[vNum].SCTCMatrix*(minPosSC + rayStepSC);\n var tstep: vec4 = tpos2 - tpos;\n\n var rayBounds: vec2 = adjustBounds(tpos, tstep, numSteps);\n\n // did we hit anything\n if (rayBounds.x >= rayBounds.y)\n {\n traverseVals[vNum] = vec4(0.0,0.0,0.0,0.0);\n return;\n }\n\n tpos = tpos + tstep*rayBounds.x;\n var curDist: f32 = rayBounds.x;\n var maxVal: f32 = -1.0e37;\n loop\n {\n var scalar: f32 = getTextureValue(vTex, tpos);\n if (scalar > maxVal)\n {\n maxVal = scalar;\n }\n\n // increment position\n curDist = curDist + 1.0;\n tpos = tpos + tstep;\n\n // check if we have reached a terminating condition\n if (curDist > rayBounds.y) { break; }\n }\n\n // process to get the color and opacity\n traverseVals[vNum] = getSimpleColor(maxVal, vNum, cNum);\n}\n\nfn traverseMin(vTex: texture_3d, vNum: i32, cNum: i32, rayLengthSC: f32, minPosSC: vec4, rayStepSC: vec4)\n{\n // convert to tcoords and reject if outside the volume\n var numSteps: f32 = rayLengthSC/mapperUBO.SampleDistance;\n var tpos: vec4 = volumeSSBO.values[vNum].SCTCMatrix*minPosSC;\n var tpos2: vec4 = volumeSSBO.values[vNum].SCTCMatrix*(minPosSC + rayStepSC);\n var tstep: vec4 = tpos2 - tpos;\n\n var rayBounds: vec2 = adjustBounds(tpos, tstep, numSteps);\n\n // did we hit anything\n if (rayBounds.x >= rayBounds.y)\n {\n traverseVals[vNum] = vec4(0.0,0.0,0.0,0.0);\n return;\n }\n\n tpos = tpos + tstep*rayBounds.x;\n var curDist: f32 = rayBounds.x;\n var minVal: f32 = 1.0e37;\n loop\n {\n var scalar: f32 = getTextureValue(vTex, tpos);\n if (scalar < minVal)\n {\n minVal = scalar;\n }\n\n // increment position\n curDist = curDist + 1.0;\n tpos = tpos + tstep;\n\n // check if we have reached a terminating condition\n if (curDist > rayBounds.y) { break; }\n }\n\n // process to get the color and opacity\n traverseVals[vNum] = getSimpleColor(minVal, vNum, cNum);\n}\n\nfn traverseAverage(vTex: texture_3d, vNum: i32, cNum: i32, rayLengthSC: f32, minPosSC: vec4, rayStepSC: vec4)\n{\n // convert to tcoords and reject if outside the volume\n var numSteps: f32 = rayLengthSC/mapperUBO.SampleDistance;\n var tpos: vec4 = volumeSSBO.values[vNum].SCTCMatrix*minPosSC;\n var tpos2: vec4 = volumeSSBO.values[vNum].SCTCMatrix*(minPosSC + rayStepSC);\n var tstep: vec4 = tpos2 - tpos;\n\n var rayBounds: vec2 = adjustBounds(tpos, tstep, numSteps);\n\n // did we hit anything\n if (rayBounds.x >= rayBounds.y)\n {\n traverseVals[vNum] = vec4(0.0,0.0,0.0,0.0);\n return;\n }\n\n let ipRange: vec4 = volumeSSBO.values[vNum].ipScalarRange;\n tpos = tpos + tstep*rayBounds.x;\n var curDist: f32 = rayBounds.x;\n var avgVal: f32 = 0.0;\n var sampleCount: f32 = 0.0;\n loop\n {\n var sample: f32 = getTextureValue(vTex, tpos);\n // right now leave filtering off until WebGL changes get merged\n // if (ipRange.z == 0.0 || sample >= ipRange.x && sample <= ipRange.y)\n // {\n avgVal = avgVal + sample;\n sampleCount = sampleCount + 1.0;\n // }\n\n // increment position\n curDist = curDist + 1.0;\n tpos = tpos + tstep;\n\n // check if we have reached a terminating condition\n if (curDist > rayBounds.y) { break; }\n }\n\n if (sampleCount <= 0.0)\n {\n traverseVals[vNum] = vec4(0.0,0.0,0.0,0.0);\n }\n\n // process to get the color and opacity\n traverseVals[vNum] = getSimpleColor(avgVal/sampleCount, vNum, cNum);\n}\n\nfn traverseAdditive(vTex: texture_3d, vNum: i32, cNum: i32, rayLengthSC: f32, minPosSC: vec4, rayStepSC: vec4)\n{\n // convert to tcoords and reject if outside the volume\n var numSteps: f32 = rayLengthSC/mapperUBO.SampleDistance;\n var tpos: vec4 = volumeSSBO.values[vNum].SCTCMatrix*minPosSC;\n var tpos2: vec4 = volumeSSBO.values[vNum].SCTCMatrix*(minPosSC + rayStepSC);\n var tstep: vec4 = tpos2 - tpos;\n\n var rayBounds: vec2 = adjustBounds(tpos, tstep, numSteps);\n\n // did we hit anything\n if (rayBounds.x >= rayBounds.y)\n {\n traverseVals[vNum] = vec4(0.0,0.0,0.0,0.0);\n return;\n }\n\n let ipRange: vec4 = volumeSSBO.values[vNum].ipScalarRange;\n tpos = tpos + tstep*rayBounds.x;\n var curDist: f32 = rayBounds.x;\n var sumVal: f32 = 0.0;\n loop\n {\n var sample: f32 = getTextureValue(vTex, tpos);\n // right now leave filtering off until WebGL changes get merged\n // if (ipRange.z == 0.0 || sample >= ipRange.x && sample <= ipRange.y)\n // {\n sumVal = sumVal + sample;\n // }\n\n // increment position\n curDist = curDist + 1.0;\n tpos = tpos + tstep;\n\n // check if we have reached a terminating condition\n if (curDist > rayBounds.y) { break; }\n }\n\n // process to get the color and opacity\n traverseVals[vNum] = getSimpleColor(sumVal, vNum, cNum);\n}\n\nfn composite(rayLengthSC: f32, minPosSC: vec4, rayStepSC: vec4) -> vec4\n{\n // initial ray position is at the beginning\n var rayPosSC: vec4 = minPosSC;\n\n // how many rows (tfuns) do we have in our tfunTexture\n var tfunRows: f32 = f32(textureDimensions(tfunTexture).y);\n\n var curDist: f32 = 0.0;\n var computedColor: vec4 = vec4(0.0, 0.0, 0.0, 0.0);\n var sampleColor: vec4;\n//VTK::Volume::TraverseCalls\n\n loop\n {\n // for each volume, sample and accumulate color\n//VTK::Volume::CompositeCalls\n\n // increment position\n curDist = curDist + mapperUBO.SampleDistance;\n rayPosSC = rayPosSC + rayStepSC;\n\n // check if we have reached a terminating condition\n if (curDist > rayLengthSC) { break; }\n if (computedColor.a > 0.98) { break; }\n }\n return computedColor;\n}\n\n@fragment\nfn main(\n//VTK::IOStructs::Input\n)\n//VTK::IOStructs::Output\n{\n var output: fragmentOutput;\n\n var rayMax: f32 = textureSampleLevel(maxTexture, clampSampler, input.tcoordVS, 0.0).r;\n var rayMin: f32 = textureSampleLevel(minTexture, clampSampler, input.tcoordVS, 0.0).r;\n\n // discard empty rays\n if (rayMax <= rayMin) { discard; }\n else\n {\n // compute start and end ray positions in view coordinates\n var minPosSC: vec4 = rendererUBO.PCSCMatrix*vec4(2.0 * input.tcoordVS.x - 1.0, 1.0 - 2.0 * input.tcoordVS.y, rayMax, 1.0);\n minPosSC = minPosSC * (1.0 / minPosSC.w);\n var maxPosSC: vec4 = rendererUBO.PCSCMatrix*vec4(2.0 * input.tcoordVS.x - 1.0, 1.0 - 2.0 * input.tcoordVS.y, rayMin, 1.0);\n maxPosSC = maxPosSC * (1.0 / maxPosSC.w);\n\n var rayLengthSC: f32 = distance(minPosSC.xyz, maxPosSC.xyz);\n var rayStepSC: vec4 = (maxPosSC - minPosSC)*(mapperUBO.SampleDistance/rayLengthSC);\n rayStepSC.w = 0.0;\n\n var computedColor: vec4;\n\n//VTK::Volume::Loop\n\n//VTK::RenderEncoder::Impl\n }\n\n return output;\n}\n",t.UBO=Vf.newInstance({label:"mapperUBO"}),t.UBO.addEntry("SampleDistance","f32"),t.SSBO=Ff.newInstance({label:"volumeSSBO"}),t.componentSSBO=Ff.newInstance({label:"componentSSBO"}),t.lutBuildTime={},zt.obj(t.lutBuildTime,{mtime:0}),function(e,t){t.classHierarchy.push("vtkWebGPUVolumePassFSQ"),e.replaceShaderPosition=(e,t,r)=>{const n=t.getShaderDescription("vertex");n.addBuiltinOutput("vec4","@builtin(position) Position");let o=n.getCode();o=Np.substitute(o,"//VTK::Position::Impl",["output.tcoordVS = vec2(vertexBC.x * 0.5 + 0.5, 1.0 - vertexBC.y * 0.5 - 0.5);","output.Position = vec4(vertexBC, 1.0);"]).result,n.setCode(o),t.getShaderDescription("fragment").addBuiltinInput("vec4","@builtin(position) fragPos")},t.shaderReplacements.set("replaceShaderPosition",e.replaceShaderPosition),e.replaceShaderVolume=(e,r,n)=>{const o=r.getShaderDescription("fragment");let i=o.getCode();const a=[],s=[];for(let e=0;e(\n sampleColor.a * sampleColor.rgb * (1.0 - computedColor.a) + computedColor.rgb,\n (1.0 - computedColor.a)*sampleColor.a + computedColor.a);")):(s.push(` sampleColor = traverseVals[${e}];`),s.push(" computedColor = vec4(\n sampleColor.a * sampleColor.rgb * (1.0 - computedColor.a) + computedColor.rgb,\n (1.0 - computedColor.a)*sampleColor.a + computedColor.a);"));i=Np.substitute(i,"//VTK::Volume::CompositeCalls",a).result,i=Np.substitute(i,"//VTK::Volume::TraverseCalls",s).result,i=Np.substitute(i,"//VTK::Volume::TraverseDec",[`var traverseVals: array,${t.volumes.length}>;`]).result;let l=!1;for(let e=0;e{let n=e.getMTime();for(let e=0;e{let n=Math.max(e.getMTime(),t.WebGPURenderer.getStabilizedTime());for(let e=0;e"),t.SSBO.addEntry("planeNormals","mat4x4"),t.SSBO.addEntry("shade","vec4"),t.SSBO.addEntry("tstep","vec4"),t.SSBO.addEntry("spacing","vec4"),t.SSBO.addEntry("ipScalarRange","vec4"),t.SSBO.setAllInstancesFromArray("SCTCMatrix",i),t.SSBO.setAllInstancesFromArray("planeNormals",a),t.SSBO.setAllInstancesFromArray("shade",l),t.SSBO.setAllInstancesFromArray("tstep",s),t.SSBO.setAllInstancesFromArray("spacing",u),t.SSBO.setAllInstancesFromArray("ipScalarRange",c),t.SSBO.send(r),t.componentSSBO.clearData(),t.componentSSBO.setNumberOfInstances(t.numRows);const d=new Float64Array(t.numRows),p=new Float64Array(t.numRows),f=new Float64Array(t.numRows),y=new Float64Array(t.numRows),v=new Float64Array(t.numRows),S=new Float64Array(t.numRows),C=new Float64Array(t.numRows),T=new Float64Array(t.numRows);let w=0;for(let e=0;e{r();let n=t.volumes[0].getRenderable().getMapper().getSampleDistance();for(let e=0;e{t.pipelineHash="volfsq";for(let e=0;e{if(!t.volumes||t.volumes.length!==r.length)return t.volumes=[...r],void e.modified();for(let n=0;n{const e=n();return e.push(t.componentSSBO),e.push(t.clampSampler),e}}(e,t)}var dy={newInstance:zt.newInstance(cy,"vtkWebGPUVolumePassFSQ"),extend:cy};const{Representation:py}=os,{BufferUsage:fy,PrimitiveTypes:hy}=If,my=[[0,4,6],[0,6,2],[1,3,7],[1,7,5],[0,5,4],[0,1,5],[2,6,7],[2,7,3],[0,3,1],[0,2,3],[4,5,7],[4,7,6]],gy={colorTextureView:null,depthTextureView:null,volumes:null};function yy(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,gy,r),Wm.extend(e,t,r),t._mapper=Zp.newInstance(),t._mapper.setFragmentShaderTemplate("\n//VTK::Renderer::Dec\n\n//VTK::Select::Dec\n\n//VTK::VolumePass::Dec\n\n//VTK::TCoord::Dec\n\n//VTK::RenderEncoder::Dec\n\n//VTK::Mapper::Dec\n\n//VTK::IOStructs::Dec\n\n@fragment\nfn main(\n//VTK::IOStructs::Input\n)\n//VTK::IOStructs::Output\n{\n var output : fragmentOutput;\n\n //VTK::Select::Impl\n\n //VTK::TCoord::Impl\n\n //VTK::VolumePass::Impl\n\n // use the maximum (closest) of the current value and the zbuffer\n // the blend func will then take the min to find the farthest stop value\n var stopval: f32 = max(input.fragPos.z, textureLoad(opaquePassDepthTexture, vec2(i32(input.fragPos.x), i32(input.fragPos.y)), 0));\n\n //VTK::RenderEncoder::Impl\n return output;\n}\n"),t._mapper.getShaderReplacements().set("replaceShaderVolumePass",(e,t,r)=>{t.getShaderDescription("fragment").addBuiltinInput("vec4","@builtin(position) fragPos")}),t._boundsPoly=mc.newInstance(),t._lastMTimes=[],zt.setGet(e,t,["colorTextureView","depthTextureView"]),function(e,t){t.classHierarchy.push("vtkWebGPUVolumePass"),e.initialize=r=>{t._clearEncoder||e.createClearEncoder(r),t._mergeEncoder||e.createMergeEncoder(r),t._copyEncoder||e.createCopyEncoder(r),t._depthRangeEncoder||e.createDepthRangeEncoder(r),t.fullScreenQuad||(t.fullScreenQuad=dy.newInstance(),t.fullScreenQuad.setDevice(r.getDevice()),t.fullScreenQuad.setTextureViews([...t._depthRangeEncoder.getColorTextureViews()])),t._volumeCopyQuad||(t._volumeCopyQuad=rf.newInstance(),t._volumeCopyQuad.setPipelineHash("volpassfsq"),t._volumeCopyQuad.setDevice(r.getDevice()),t._volumeCopyQuad.setFragmentShaderTemplate("\n//VTK::Renderer::Dec\n\n//VTK::Mapper::Dec\n\n//VTK::TCoord::Dec\n\n//VTK::RenderEncoder::Dec\n\n//VTK::IOStructs::Dec\n\n@fragment\nfn main(\n//VTK::IOStructs::Input\n)\n//VTK::IOStructs::Output\n{\n var output: fragmentOutput;\n\n var computedColor: vec4 = textureSample(volumePassColorTexture,\n volumePassColorTextureSampler, mapperUBO.tscale*input.tcoordVS);\n\n //VTK::RenderEncoder::Impl\n return output;\n}\n"),t._copyUBO=Vf.newInstance({label:"mapperUBO"}),t._copyUBO.addEntry("tscale","vec2"),t._volumeCopyQuad.setUBO(t._copyUBO),t._volumeCopyQuad.setTextureViews([t._colorTextureView]))},e.traverse=(r,n)=>{if(t.deleted)return;t._currentParent=n,e.initialize(n),e.computeTiming(n),e.renderDepthBounds(r,n),t._firstGroup=!0;const o=n.getDevice(),i=o.getHandle().limits.maxSampledTexturesPerShaderStage-4;if(t.volumes.length>i){const o=r.getRenderable().getActiveCamera().getPosition(),a=[];for(let e=0;ea[t]-a[e]);let l=[],u=s.length%i;for(let o=0;o=u&&(e.rayCastPass(n,r,l),l=[],u=i,t._firstGroup=!1)}else e.rayCastPass(n,r,t.volumes);if(t._volumeCopyQuad.setWebGPURenderer(r),t._useSmallViewport){const e=t._colorTextureView.getTexture().getWidth(),r=t._colorTextureView.getTexture().getHeight();t._copyUBO.setArray("tscale",[t._smallViewportWidth/e,t._smallViewportHeight/r])}else t._copyUBO.setArray("tscale",[1,1]);t._copyUBO.sendIfNeeded(o),t._copyEncoder.setColorTextureView(0,t.colorTextureView),t._copyEncoder.attachTextureViews(),t._copyEncoder.begin(n.getCommandEncoder()),r.scissorAndViewport(t._copyEncoder),t._volumeCopyQuad.prepareAndDraw(t._copyEncoder),t._copyEncoder.end()},e.delete=zt.chain(()=>{t._animationRateSubscription&&(t._animationRateSubscription.unsubscribe(),t._animationRateSubscription=null)},e.delete),e.computeTiming=e=>{const r=e.getRenderable().getInteractor();if(null==t._lastScale){const e=t.volumes[0].getRenderable().getMapper();t._lastScale=e.getInitialInteractionScale()||1}t._useSmallViewport=!1,r.isAnimating()&&t._lastScale>1.5&&(t._useSmallViewport=!0),t._colorTexture.resize(e.getCanvas().width,e.getCanvas().height),t._animationRateSubscription||(t._animationRateSubscription=r.onAnimationFrameRateUpdate(()=>{const e=t.volumes[0].getRenderable().getMapper();if(e.getAutoAdjustSampleDistances()){const e=r.getRecentAnimationFrameRate(),n=t._lastScale*r.getDesiredUpdateRate()/e;t._lastScale=n,t._lastScale>400&&(t._lastScale=400)}else t._lastScale=e.getImageSampleDistance()*e.getImageSampleDistance();t._lastScale<1.5&&(t._lastScale=1.5)}))},e.rayCastPass=(e,r,n)=>{const o=t._firstGroup?t._clearEncoder:t._mergeEncoder;o.attachTextureViews(),o.begin(e.getCommandEncoder());let i=t._colorTextureView.getTexture().getWidth(),a=t._colorTextureView.getTexture().getHeight();if(t._useSmallViewport){const r=e.getCanvas(),n=1/Math.sqrt(t._lastScale);t._smallViewportWidth=Math.ceil(n*r.width),t._smallViewportHeight=Math.ceil(n*r.height),i=t._smallViewportWidth,a=t._smallViewportHeight}o.getHandle().setViewport(0,0,i,a,0,1),o.getHandle().setScissorRect(0,0,i,a),t.fullScreenQuad.setWebGPURenderer(r),t.fullScreenQuad.setVolumes(n),t.fullScreenQuad.prepareAndDraw(o),o.end()},e.renderDepthBounds=(r,n)=>{e.updateDepthPolyData(r);const o=t._boundsPoly,i=o.getPoints(),a=o.getPolys();let s={hash:`vp${a.getMTime()}`,usage:fy.Index,cells:a,numberOfPoints:i.getNumberOfPoints(),primitiveType:hy.Triangles,representation:py.SURFACE};const l=n.getDevice().getBufferManager().getBuffer(s);t._mapper.getVertexInput().setIndexBuffer(l),s={usage:fy.PointArray,format:"float32x4",hash:`vp${i.getMTime()}${a.getMTime()}`,dataArray:i,indexBuffer:l,packExtra:!0};const u=n.getDevice().getBufferManager().getBuffer(s);t._mapper.getVertexInput().addBuffer(u,["vertexBC"]),t._mapper.setNumberOfVertices(u.getSizeInBytes()/u.getStrideInBytes()),e.drawDepthRange(r,n)},e.updateDepthPolyData=e=>{let r=!1;for(let e=0;e{t._depthRangeTexture.resizeToMatch(t.colorTextureView.getTexture()),t._depthRangeTexture2.resizeToMatch(t.colorTextureView.getTexture()),t._depthRangeEncoder.attachTextureViews(),e.setCurrentOperation("volumeDepthRangePass"),r.setRenderEncoder(t._depthRangeEncoder),r.volumeDepthRangePass(!0),t._mapper.setWebGPURenderer(r),t._mapper.prepareToDraw(t._depthRangeEncoder),t._mapper.registerDrawCallback(t._depthRangeEncoder),r.volumeDepthRangePass(!1)},e.createDepthRangeEncoder=e=>{const r=e.getDevice();t._depthRangeEncoder=qg.newInstance({label:"VolumePass DepthRange"}),t._depthRangeEncoder.setPipelineHash("volr"),t._depthRangeEncoder.setReplaceShaderCodeFunction(e=>{const t=e.getShaderDescription("fragment");t.addOutput("vec4","outColor1"),t.addOutput("vec4","outColor2");let r=t.getCode();r=Np.substitute(r,"//VTK::RenderEncoder::Impl",["output.outColor1 = vec4(input.fragPos.z, 0.0, 0.0, 0.0);","output.outColor2 = vec4(stopval, 0.0, 0.0, 0.0);"]).result,t.setCode(r)}),t._depthRangeEncoder.setDescription({colorAttachments:[{view:null,clearValue:[0,0,0,0],loadOp:"clear",storeOp:"store"},{view:null,clearValue:[1,1,1,1],loadOp:"clear",storeOp:"store"}]}),t._depthRangeEncoder.setPipelineSettings({primitive:{cullMode:"none"},fragment:{targets:[{format:"r16float",blend:{color:{srcFactor:"one",dstFactor:"one",operation:"max"},alpha:{srcFactor:"one",dstFactor:"one",operation:"max"}}},{format:"r16float",blend:{color:{srcFactor:"one",dstFactor:"one",operation:"min"},alpha:{srcFactor:"one",dstFactor:"one",operation:"min"}}}]}}),t._depthRangeTexture=Oh.newInstance({label:"volumePassMaxDepth"}),t._depthRangeTexture.create(r,{width:e.getCanvas().width,height:e.getCanvas().height,format:"r16float",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING});const n=t._depthRangeTexture.createView("maxTexture");t._depthRangeEncoder.setColorTextureView(0,n),t._depthRangeTexture2=Oh.newInstance({label:"volumePassDepthMin"}),t._depthRangeTexture2.create(r,{width:e.getCanvas().width,height:e.getCanvas().height,format:"r16float",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING});const o=t._depthRangeTexture2.createView("minTexture");t._depthRangeEncoder.setColorTextureView(1,o),t._mapper.setDevice(e.getDevice()),t._mapper.setTextureViews([t.depthTextureView])},e.createClearEncoder=e=>{t._colorTexture=Oh.newInstance({label:"volumePassColor"}),t._colorTexture.create(e.getDevice(),{width:e.getCanvas().width,height:e.getCanvas().height,format:"bgra8unorm",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC}),t._colorTextureView=t._colorTexture.createView("volumePassColorTexture"),t._colorTextureView.addSampler(e.getDevice(),{minFilter:"linear",magFilter:"linear"}),t._clearEncoder=qg.newInstance({label:"VolumePass Clear"}),t._clearEncoder.setColorTextureView(0,t._colorTextureView),t._clearEncoder.setDescription({colorAttachments:[{view:null,clearValue:[0,0,0,0],loadOp:"clear",storeOp:"store"}]}),t._clearEncoder.setPipelineHash("volpf"),t._clearEncoder.setPipelineSettings({primitive:{cullMode:"none"},fragment:{targets:[{format:"bgra8unorm",blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha"}}}]}})},e.createCopyEncoder=e=>{t._copyEncoder=qg.newInstance({label:"volumePassCopy"}),t._copyEncoder.setDescription({colorAttachments:[{view:null,loadOp:"load",storeOp:"store"}]}),t._copyEncoder.setPipelineHash("volcopypf"),t._copyEncoder.setPipelineSettings({primitive:{cullMode:"none"},fragment:{targets:[{format:"rgba16float",blend:{color:{srcFactor:"one",dstFactor:"one-minus-src-alpha"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha"}}}]}})},e.createMergeEncoder=e=>{t._mergeEncoder=qg.newInstance({label:"volumePassMerge"}),t._mergeEncoder.setColorTextureView(0,t._colorTextureView),t._mergeEncoder.setDescription({colorAttachments:[{view:null,loadOp:"load",storeOp:"store"}]}),t._mergeEncoder.setReplaceShaderCodeFunction(e=>{const t=e.getShaderDescription("fragment");t.addOutput("vec4","outColor");let r=t.getCode();r=Np.substitute(r,"//VTK::RenderEncoder::Impl",["output.outColor = vec4(computedColor.rgb, computedColor.a);"]).result,t.setCode(r)}),t._mergeEncoder.setPipelineHash("volpf"),t._mergeEncoder.setPipelineSettings({primitive:{cullMode:"none"},fragment:{targets:[{format:"bgra8unorm",blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha"}}}]}})},e.setVolumes=r=>{if(!t.volumes||t.volumes.length!==r.length)return t.volumes=[...r],void e.modified();for(let n=0;n2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,by,r),Wm.extend(e,t,r),zt.setGet(e,t,["opaquePass","translucentPass","volumePass"]),function(e,t){t.classHierarchy.push("vtkForwardPass"),e.traverse=function(r){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(t.deleted)return;t._currentParent=n,e.setCurrentOperation("buildPass"),r.traverse(e),t.opaquePass||(t.opaquePass=Qg.newInstance());const o=r.getRenderable().getNumberOfLayers(),i=r.getChildren();for(let n=0;n0&&(t.translucentPass||(t.translucentPass=ty.newInstance()),t.translucentPass.setColorTextureView(t.opaquePass.getColorTextureView()),t.translucentPass.setDepthTextureView(t.opaquePass.getDepthTextureView()),t.translucentPass.traverse(a,r)),t.volumes.length>0&&(t.volumePass||(t.volumePass=vy.newInstance()),t.volumePass.setColorTextureView(t.opaquePass.getColorTextureView()),t.volumePass.setDepthTextureView(t.opaquePass.getDepthTextureView()),t.volumePass.setVolumes(t.volumes),t.volumePass.traverse(a,r)),e.finalPass(r,a))}},e.finalPass=(r,n)=>{t._finalBlitEncoder||e.createFinalBlitEncoder(r),t._finalBlitOutputTextureView.createFromTextureHandle(r.getCurrentTexture(),{depth:1,format:r.getPresentationFormat()}),t._finalBlitEncoder.attachTextureViews(),t._finalBlitEncoder.begin(r.getCommandEncoder()),n.scissorAndViewport(t._finalBlitEncoder),t._fullScreenQuad.prepareAndDraw(t._finalBlitEncoder),t._finalBlitEncoder.end()},e.createFinalBlitEncoder=e=>{t._finalBlitEncoder=qg.newInstance({label:"forwardPassBlit"}),t._finalBlitEncoder.setDescription({colorAttachments:[{view:null,loadOp:"load",storeOp:"store"}]}),t._finalBlitEncoder.setPipelineHash("fpf"),t._finalBlitEncoder.setPipelineSettings({primitive:{cullMode:"none"},fragment:{targets:[{format:e.getPresentationFormat(),blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha"}}}]}}),t._fsqSampler=wh.newInstance({label:"finalPassSampler"}),t._fsqSampler.create(e.getDevice(),{minFilter:"linear",magFilter:"linear"}),t._fullScreenQuad=rf.newInstance(),t._fullScreenQuad.setDevice(e.getDevice()),t._fullScreenQuad.setPipelineHash("fpfsq"),t._fullScreenQuad.setTextureViews([t.opaquePass.getColorTextureView()]),t._fullScreenQuad.setAdditionalBindables([t._fsqSampler]),t._fullScreenQuad.setFragmentShaderTemplate("\n//VTK::Mapper::Dec\n\n//VTK::TCoord::Dec\n\n//VTK::RenderEncoder::Dec\n\n//VTK::IOStructs::Dec\n\n@fragment\nfn main(\n//VTK::IOStructs::Input\n)\n//VTK::IOStructs::Output\n{\n var output: fragmentOutput;\n\n var computedColor: vec4 = clamp(textureSampleLevel(opaquePassColorTexture, finalPassSampler, input.tcoordVS, 0.0),vec4(0.0),vec4(1.0));\n\n //VTK::RenderEncoder::Impl\n return output;\n}\n"),t._finalBlitOutputTextureView=Dh.newInstance(),t._finalBlitEncoder.setColorTextureView(0,t._finalBlitOutputTextureView)},e.incrementOpaqueActorCount=()=>t.opaqueActorCount++,e.incrementTranslucentActorCount=()=>t.translucentActorCount++,e.addVolume=e=>{t.volumes.push(e)}}(e,t)}var _y={newInstance:zt.newInstance(xy,"vtkForwardPass"),extend:xy};const{VtkDataTypes:Sy}=_s,Cy={handle:null,device:null};function Ty(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Cy,r),zt.obj(e,t),zt.setGet(e,t,["device"]),function(e,t){function r(e){if(e.imageData){e.dataArray=e.imageData.getPointData().getScalars(),e.time=e.dataArray.getMTime(),e.nativeArray=e.dataArray.getData();const t=e.imageData.getDimensions();switch(e.width=t[0],e.height=t[1],e.depth=t[2],e.dataArray.getNumberOfComponents()){case 1:e.format="r";break;case 2:e.format="rg";break;default:e.format="rgba"}switch(e.dataArray.getDataType()){case Sy.UNSIGNED_CHAR:e.format+="8unorm";break;case Sy.FLOAT:case Sy.UNSIGNED_INT:case Sy.INT:case Sy.DOUBLE:case Sy.UNSIGNED_SHORT:case Sy.SHORT:default:e.format+="16float"}}e.image&&(e.width=e.image.width,e.height=e.image.height,e.depth=1,e.format="rgba8unorm",e.flip=!0,e.usage=GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT),e.jsImageData&&(e.width=e.jsImageData.width,e.height=e.jsImageData.height,e.depth=1,e.format="rgba8unorm",e.flip=!0,e.nativeArray=e.jsImageData.data,e.usage=GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT),e.imageBitmap&&(e.width=e.imageBitmap.width,e.height=e.imageBitmap.height,e.depth=1,e.format="rgba8unorm",e.flip=!0,e.usage=GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT),e.canvas&&(e.width=e.canvas.width,e.height=e.canvas.height,e.depth=1,e.format="rgba8unorm",e.flip=!0,e.usage=GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT)}function n(e){const r=Oh.newInstance({label:e.label});return r.create(t.device,{width:e.width,height:e.height,depth:e.depth,format:e.format,usage:e.usage,mipLevel:e.mipLevel}),(e.nativeArray||e.image||e.canvas||e.imageBitmap)&&r.writeImageData(e),r}t.classHierarchy.push("vtkWebGPUTextureManager"),e.getTexture=e=>e.hash?t.device.getCachedObject(e.hash,n,e):n(e),e.getTextureForImageData=e=>{const n={time:e.getMTime()};return n.imageData=e,r(n),n.hash=n.time+n.format+n.mipLevel,t.device.getTextureManager().getTexture(n)},e.getTextureForVTKTexture=function(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0;const o={time:e.getMTime(),label:n};return e.getInputData()?o.imageData=e.getInputData():e.getImage()?o.image=e.getImage():e.getJsImageData()?o.jsImageData=e.getJsImageData():e.getImageBitmap()?o.imageBitmap=e.getImageBitmap():e.getCanvas()&&(o.canvas=e.getCanvas()),r(o),o.mipLevel=e.getMipLevel(),o.hash=o.time+o.format+o.mipLevel,t.device.getTextureManager().getTexture(o)}}(e,t)}var wy={newInstance:zt.newInstance(Ty),extend:Ty};class Ay extends Map{constructor(){super(),this.registry=new FinalizationRegistry(e=>{const t=super.get(e);t&&t.deref&&void 0===t.deref()&&super.delete(e)})}getValue(e){const t=super.get(e);if(t){const r=t.deref();if(void 0!==r)return r;super.delete(e)}}setValue(e,t){let r;return t&&"object"==typeof t&&(r=new WeakRef(t),this.registry.register(t,e),super.set(e,r)),r}}const Ey={handle:null,pipelines:null,shaderCache:null,bindGroupLayouts:null,bufferManager:null,textureManager:null};function Dy(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Ey,r),mt(e,t),_t(e,t,["handle"]),yt(e,t,["bufferManager","shaderCache","textureManager"]),t.objectCache=new Ay,t.shaderCache=Np.newInstance(),t.shaderCache.setDevice(e),t.bindGroupLayouts=[],t.bufferManager=If.newInstance(),t.bufferManager.setDevice(e),t.textureManager=wy.newInstance(),t.textureManager.setDevice(e),t.pipelines={},function(e,t){t.classHierarchy.push("vtkWebGPUDevice"),e.initialize=e=>{t.handle=e},e.createCommandEncoder=()=>t.handle.createCommandEncoder(),e.submitCommandEncoder=e=>{t.handle.queue.submit([e.finish()])},e.getShaderModule=e=>t.shaderCache.getShaderModule(e),e.getBindGroupLayout=e=>{if(!e.entries)return null;for(let t=0;t{for(let r=0;re in t.pipelines?t.pipelines[e]:null,e.createPipeline=(r,n)=>{n.initialize(e,r),t.pipelines[r]=n},e.onSubmittedWorkDone=()=>t.handle.queue.onSubmittedWorkDone(),e.hasCachedObject=e=>t.objectCache.getValue(e),e.getCachedObject=function(e,r){if(!e)return vtkErrorMacro("attempt to cache an object without a hash"),null;const n=t.objectCache.getValue(e);if(n)return n;for(var o=arguments.length,i=new Array(o>2?o-2:0),a=2;a2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Iy,r),Wm.extend(e,t,r),zt.get(e,t,["colorTexture","depthTexture"]),function(e,t){t.classHierarchy.push("vtkWebGPUHardwareSelectionPass"),e.traverse=(r,n)=>{if(t.deleted)return;t._currentParent=null,e.setCurrentOperation("buildPass"),r.traverse(e);const o=r.getDevice();if(t.selectionRenderEncoder)t.colorTexture.resize(r.getCanvas().width,r.getCanvas().height),t.depthTexture.resizeToMatch(t.colorTexture);else{e.createRenderEncoder(),t.colorTexture=Oh.newInstance({label:"hardwareSelectorColor"}),t.colorTexture.create(o,{width:r.getCanvas().width,height:r.getCanvas().height,format:"rgba32uint",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC});const n=t.colorTexture.createView("hardwareSelectColorTexture");t.selectionRenderEncoder.setColorTextureView(0,n),t.depthTexture=Oh.newInstance({label:"hardwareSelectorDepth"}),t.depthTexture.create(o,{width:r.getCanvas().width,height:r.getCanvas().height,format:"depth32float",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC});const i=t.depthTexture.createView("hardwareSelectDepthTexture");t.selectionRenderEncoder.setDepthTextureView(i)}t.selectionRenderEncoder.attachTextureViews(),n.setRenderEncoder(t.selectionRenderEncoder),e.setCurrentOperation("cameraPass"),n.traverse(e),e.setCurrentOperation("opaquePass"),n.traverse(e)},e.createRenderEncoder=()=>{t.selectionRenderEncoder=qg.newInstance({label:"HardwareSelectionPass"}),t.selectionRenderEncoder.setPipelineHash("sel"),t.selectionRenderEncoder.setReplaceShaderCodeFunction(e=>{const t=e.getShaderDescription("fragment");t.addOutput("vec4","outColor");let r=t.getCode();r=Np.substitute(r,"//VTK::RenderEncoder::Impl",["output.outColor = vec4(mapperUBO.PropID, compositeID, 0u, 0u);"]).result,t.setCode(r)}),t.selectionRenderEncoder.getDescription().colorAttachments[0].clearValue=[0,0,0,0],t.selectionRenderEncoder.setPipelineSettings({primitive:{cullMode:"none"},depthStencil:{depthWriteEnabled:!0,depthCompare:"greater",format:"depth32float"},fragment:{targets:[{format:"rgba32uint",blend:void 0}]}})}}(e,t)}var Ny={newInstance:zt.newInstance(Oy,"vtkWebGPUHardwareSelectionPass"),extend:Oy};const{SelectionContent:My,SelectionField:Ry}=ag,{FieldAssociations:Fy}=Gs,{vtkErrorMacro:By}=zt;function Ly(e){return`${e.propID} ${e.compositeID}`}function ky(e,t,r,n){const o=4*((r.height-t-1)*r.colorBufferWidth+e)+n;return r.colorValues[o]}function Uy(e,t,r,n){const o=r<0?0:r;if(0===o){if(n[0]=t[0],n[1]=t[1],t[0]<0||t[0]>=e.width||t[1]<0||t[1]>=e.height)return null;const r=ky(t[0],t[1],e,0);if(r<=0)return null;const o={};o.propID=r;let i=ky(t[0],t[1],e,1);if((i<0||i>16777215)&&(i=0),o.compositeID=i,e.captureZValues){const r=(e.height-t[1]-1)*e.zbufferBufferWidth+t[0];o.zValue=e.depthValues[r],o.zValue=e.webGPURenderer.convertToOpenGLDepth(o.zValue),o.displayPosition=t}return o}const i=[t[0],t[1]],a=[0,0];let s=Uy(e,t,0,n);if(s)return s;for(let t=1;tt?i[1]-t:0;r<=i[1]+t;++r){if(a[1]=r,i[0]>=t&&(a[0]=i[0]-t,s=Uy(e,a,0,n),s))return s;if(a[0]=i[0]+t,s=Uy(e,a,0,n),s)return s}for(let r=i[0]>=t?i[0]-(t-1):0;r<=i[0]+(t-1);++r){if(a[0]=r,i[1]>=t&&(a[1]=i[1]-t,s=Uy(e,a,0,n),s))return s;if(a[1]=i[1]+t,s=Uy(e,a,0,n),s)return s}}return n[0]=t[0],n[1]=t[1],null}const Vy={};function Gy(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Vy,r),ng.extend(e,t,r),t._selectionPass=Ny.newInstance(),zt.setGet(e,t,["_WebGPURenderWindow"]),zt.moveToProtected(e,t,["WebGPURenderWindow"]),function(e,t){t.classHierarchy.push("vtkWebGPUHardwareSelector"),e.endSelection=()=>{t.WebGPURenderer.setSelector(null)},e.getSourceDataAsync=async e=>{if(!e||!t._WebGPURenderWindow)return By("Renderer and view must be set before calling Select."),!1;t._WebGPURenderWindow.getRenderable().preRender(),t._WebGPURenderWindow.getInitialized()||(t._WebGPURenderWindow.initialize(),await new Promise(e=>{t._WebGPURenderWindow.onInitialized(e)}));const r=t._WebGPURenderWindow.getViewNodeFor(e);if(!r)return!1;const n=r.getSuppressClear();r.setSuppressClear(!0),t._selectionPass.traverse(t._WebGPURenderWindow,r),r.setSuppressClear(n);const o=t._WebGPURenderWindow.getDevice(),i=t._selectionPass.getColorTexture(),a=t._selectionPass.getDepthTexture(),s={area:[0,0,i.getWidth()-1,i.getHeight()-1],captureZValues:t.captureZValues,fieldAssociation:t.fieldAssociation,renderer:e,webGPURenderer:r,webGPURenderWindow:t._WebGPURenderWindow,width:i.getWidth(),height:i.getHeight()};s.colorBufferWidth=16*Math.floor((s.width+15)/16),s.colorBufferSizeInBytes=s.colorBufferWidth*s.height*4*4;const l=lf.newInstance({label:"hardwareSelectColorBuffer"});l.setDevice(o),l.create(s.colorBufferSizeInBytes,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST);const u=t._WebGPURenderWindow.getCommandEncoder();let c;u.copyTextureToBuffer({texture:i.getHandle()},{buffer:l.getHandle(),bytesPerRow:16*s.colorBufferWidth,rowsPerImage:s.height},{width:s.width,height:s.height,depthOrArrayLayers:1}),t.captureZValues&&(s.zbufferBufferWidth=64*Math.floor((s.width+63)/64),c=lf.newInstance({label:"hardwareSelectDepthBuffer"}),c.setDevice(o),s.zbufferSizeInBytes=s.height*s.zbufferBufferWidth*4,c.create(s.zbufferSizeInBytes,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST),u.copyTextureToBuffer({texture:a.getHandle(),aspect:"depth-only"},{buffer:c.getHandle(),bytesPerRow:4*s.zbufferBufferWidth,rowsPerImage:s.height},{width:s.width,height:s.height,depthOrArrayLayers:1})),o.submitCommandEncoder(u);const d=l.mapAsync(GPUMapMode.READ);if(t.captureZValues){const e=c.mapAsync(GPUMapMode.READ);await Promise.all([d,e]),s.depthValues=new Float32Array(c.getMappedRange().slice()),c.unmap()}else await d;return s.colorValues=new Uint32Array(l.getMappedRange().slice()),l.unmap(),s.generateSelection=(e,t,r,n)=>function(e,t,r,n,o){const i=Math.floor(t),a=Math.floor(r),s=Math.floor(n),l=Math.floor(o),u=new Map,c=[0,0];for(let t=a;t<=l;t++)for(let r=i;r<=s;r++){const n=Uy(e,[r,t],0,c);if(n){const t=Ly(n);if(u.has(t)){const r=u.get(t);r.pixelCount++,e.captureZValues&&n.zValue{const a=ag.newInstance();switch(a.setContentType(My.INDICES),e){case Fy.FIELD_ASSOCIATION_CELLS:a.setFieldType(Ry.CELL);break;case Fy.FIELD_ASSOCIATION_POINTS:a.setFieldType(Ry.POINT);break;default:By("Unknown field association")}a.getProperties().propID=t.info.propID;const s=r.webGPURenderer.getPropFromID(t.info.propID);a.getProperties().prop=s.getRenderable(),a.getProperties().compositeID=t.info.compositeID,a.getProperties().pixelCount=t.pixelCount,r.captureZValues&&(a.getProperties().displayPosition=[t.info.displayPosition[0],t.info.displayPosition[1],t.info.zValue],a.getProperties().worldPosition=r.webGPURenderWindow.displayToWorld(t.info.displayPosition[0],t.info.displayPosition[1],t.info.zValue,r.renderer)),a.setSelectionList(t.attributeIDs),n[o]=a,o++}),n}(e.fieldAssociation,u,e)}(s,e,t,r,n),s}}(e,t)}var zy={newInstance:zt.newInstance(Gy,"vtkWebGPUHardwareSelector"),extend:Gy};const{vtkErrorMacro:jy}=zt,Wy={position:"absolute",top:0,left:0,width:"100%",height:"100%"};const Hy={initialized:!1,context:null,adapter:null,device:null,canvas:null,cursorVisibility:!0,cursor:"pointer",containerSize:null,renderPasses:[],notifyStartCaptureImage:!1,imageFormat:"image/png",useOffScreen:!1,useBackgroundImage:!1,nextPropID:1,xrSupported:!1,presentationFormat:null};const Ky=zt.newInstance(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Hy,r),t.canvas=document.createElement("canvas"),t.canvas.style.width="100%",t.bgImage=new Image,t.bgImage.style.position="absolute",t.bgImage.style.left="0",t.bgImage.style.top="0",t.bgImage.style.width="100%",t.bgImage.style.height="100%",t.bgImage.style.zIndex="-1",Ng.extend(e,t,r),t.myFactory=_p.newInstance(),t.renderPasses[0]=_y.newInstance(),t.selector||(t.selector=zy.newInstance(),t.selector.setWebGPURenderWindow(e)),zt.event(e,t,"imageReady"),zt.event(e,t,"initialized"),zt.get(e,t,["commandEncoder","device","presentationFormat","useBackgroundImage","xrSupported"]),zt.setGet(e,t,["initialized","context","canvas","device","renderPasses","notifyStartCaptureImage","cursor","useOffScreen"]),zt.setGetArray(e,t,["size"],2),zt.event(e,t,"windowResizeEvent"),function(e,t){t.classHierarchy.push("vtkWebGPURenderWindow"),e.getViewNodeFactory=()=>t.myFactory;const r=[0,0];e.onModified(function(){t.renderable&&(t.size[0]===r[0]&&t.size[1]===r[1]||(r[0]=t.size[0],r[1]=t.size[1],t.canvas.setAttribute("width",t.size[0]),t.canvas.setAttribute("height",t.size[1]),e.recreateSwapChain())),t.viewStream&&t.viewStream.setSize(t.size[0],t.size[1]),t.canvas.style.display=t.useOffScreen?"none":"block",t.el&&(t.el.style.cursor=t.cursorVisibility?t.cursor:"none"),t.containerSize=null}),e.recreateSwapChain=()=>{t.context&&(t.context.unconfigure(),t.presentationFormat=navigator.gpu.getPreferredCanvasFormat(t.adapter),t.context.configure({device:t.device.getHandle(),format:t.presentationFormat,alphaMode:"premultiplied",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_DST,width:t.size[0],height:t.size[1]}),t._configured=!0)},e.getCurrentTexture=()=>t.context.getCurrentTexture(),e.buildPass=r=>{if(r){if(!t.renderable)return;e.prepareNodes(),e.addMissingNodes(t.renderable.getRenderersByReference()),e.removeUnusedNodes(),e.initialize()}else t.initialized&&(t._configured||e.recreateSwapChain(),t.commandEncoder=t.device.createCommandEncoder())},e.initialize=()=>{if(!t.initializing){if(t.initializing=!0,!navigator.gpu)return void jy("WebGPU is not enabled.");e.create3DContextAsync().then(()=>{t.initialized=!0,t.deleted||e.invokeInitialized()})}},e.setContainer=r=>{t.el&&t.el!==r&&(t.canvas.parentNode!==t.el&&jy("Error: canvas parent node does not match container"),t.el.removeChild(t.canvas),t.el.contains(t.bgImage)&&t.el.removeChild(t.bgImage)),t.el!==r&&(t.el=r,t.el&&(t.el.appendChild(t.canvas),t.useBackgroundImage&&t.el.appendChild(t.bgImage)),e.modified())},e.getContainer=()=>t.el,e.getContainerSize=()=>{if(!t.containerSize&&t.el){const{width:e,height:r}=t.el.getBoundingClientRect();t.containerSize=[e,r]}return t.containerSize||t.size},e.getFramebufferSize=()=>t.size,e.create3DContextAsync=async()=>{t.adapter=await navigator.gpu.requestAdapter({powerPreference:"high-performance"}),t.deleted||(t.device=Py.newInstance(),t.device.initialize(await t.adapter.requestDevice()),t.deleted?t.device=null:t.context=t.canvas.getContext("webgpu"))},e.releaseGraphicsResources=()=>{const r=Wm.newInstance();r.setCurrentOperation("Release"),r.traverse(e,null),t.adapter=null,t.device=null,t.context=null,t.initialized=!1,t.initializing=!1},e.setBackgroundImage=e=>{t.bgImage.src=e.src},e.setUseBackgroundImage=e=>{t.useBackgroundImage=e,t.useBackgroundImage&&!t.el.contains(t.bgImage)?t.el.appendChild(t.bgImage):!t.useBackgroundImage&&t.el.contains(t.bgImage)&&t.el.removeChild(t.bgImage)},e.captureNextImage=function(){let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"image/png",{resetCamera:n=!1,size:o=null,scale:i=1}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(t.deleted)return null;t.imageFormat=r;const a=t.notifyStartCaptureImage;return t.notifyStartCaptureImage=!0,t._screenshot={size:o||1!==i?o||t.size.map(e=>e*i):null},new Promise((r,o)=>{const i=e.onImageReady(o=>{if(null===t._screenshot.size)t.notifyStartCaptureImage=a,i.unsubscribe(),t._screenshot.placeHolder&&(t.size=t._screenshot.originalSize,e.modified(),t._screenshot.cameras&&t._screenshot.cameras.forEach(e=>{let{restoreParamsFn:t,arg:r}=e;return t(r)}),e.traverseAllPasses(),t.el.removeChild(t._screenshot.placeHolder),t._screenshot.placeHolder.remove(),t._screenshot=null),r(o);else{const r=document.createElement("img");if(r.style=Wy,r.src=o,t._screenshot.placeHolder=t.el.appendChild(r),t.canvas.style.display="none",t._screenshot.originalSize=t.size,t.size=t._screenshot.size,t._screenshot.size=null,e.modified(),n){const e=!0!==n;t._screenshot.cameras=t.renderable.getRenderers().map(t=>{const r=t.getActiveCamera(),o=r.get("focalPoint","position","parallelScale");return{resetCameraArgs:e?{renderer:t}:void 0,resetCameraFn:e?n:t.resetCamera,restoreParamsFn:r.set,arg:JSON.parse(JSON.stringify(o))}}),t._screenshot.cameras.forEach(e=>{let{resetCameraFn:t,resetCameraArgs:r}=e;return t(r)})}e.traverseAllPasses()}})})},e.traverseAllPasses=()=>{if(!t.deleted)if(t.initialized){if(t.renderPasses)for(let r=0;r{!async function(){let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:t.imageFormat;const n=document.createElement("canvas"),o=n.getContext("2d");n.width=t.canvas.width,n.height=t.canvas.height;const i=await e.getPixelsAsync(),a=new ImageData(i.colorValues,i.width,i.height);o.putImageData(a,0,0);const s=t.canvas.getBoundingClientRect();t.renderable.getRenderers().forEach(e=>{e.getViewProps().forEach(e=>{if(e.getContainer){const t=e.getContainer().getElementsByTagName("canvas");for(let e=0;e{t.unsubscribe(),e.traverseAllPasses()})}},e.setViewStream=r=>t.viewStream!==r&&(t.subscription&&(t.subscription.unsubscribe(),t.subscription=null),t.viewStream=r,t.viewStream&&(t.renderable.getRenderers()[0].getBackgroundByReference()[3]=0,e.setUseBackgroundImage(!0),t.subscription=t.viewStream.onImageReady(t=>e.setBackgroundImage(t.image)),t.viewStream.setSize(t.size[0],t.size[1]),t.viewStream.invalidateCache(),t.viewStream.render(),e.modified()),!0),e.getUniquePropID=()=>t.nextPropID++,e.getPropFromID=e=>{for(let r=0;r{const e=t.device,r=t.renderPasses[0].getOpaquePass().getColorTexture(),n={width:r.getWidth(),height:r.getHeight()};n.colorBufferWidth=32*Math.floor((n.width+31)/32),n.colorBufferSizeInBytes=n.colorBufferWidth*n.height*8;const o=lf.newInstance();o.setDevice(e),o.create(n.colorBufferSizeInBytes,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST);const i=t.device.createCommandEncoder();i.copyTextureToBuffer({texture:r.getHandle()},{buffer:o.getHandle(),bytesPerRow:8*n.colorBufferWidth,rowsPerImage:n.height},{width:n.width,height:n.height,depthOrArrayLayers:1}),e.submitCommandEncoder(i);const a=o.mapAsync(GPUMapMode.READ);await a,n.colorValues=new Uint16Array(o.getMappedRange().slice()),o.unmap();const s=new Uint8ClampedArray(n.height*n.width*4);for(let e=0;e{const t=zy.newInstance();return t.setWebGPURenderWindow(e),t};const n=e.setSize;e.setSize=(t,r)=>{const o=n(t,r);return o&&e.invokeWindowResizeEvent({width:t,height:r}),o},e.delete=zt.chain(e.delete,e.setViewStream)}(e,t)},"vtkWebGPURenderWindow");Zh("WebGPU",Ky),vp("vtkRenderWindow",Ky);const Xy=km(),$y={margin:"0",padding:"0",position:"absolute",top:"0",left:"0",width:"100%",height:"100%",overflow:"hidden"},qy={position:"absolute",left:"25px",top:"25px",backgroundColor:"white",borderRadius:"5px",listStyle:"none",padding:"5px 10px",margin:"0",display:"block",border:"solid 1px black",maxWidth:"calc(100% - 70px)",maxHeight:"calc(100% - 60px)",overflow:"auto"};function Yy(e,t){Object.keys(t).forEach(r=>{e.style[r]=t[r]})}const Jy={background:[.32,.34,.43],containerStyle:null,controlPanelStyle:null,listenWindowResize:!0,resizeCallback:null,controllerVisibility:!0};function Qy(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Jy,r),zt.obj(e,t),zt.get(e,t,["renderWindow","renderer","apiSpecificRenderWindow","interactor","rootContainer","container","controlContainer"]),function(e,t){t.classHierarchy.push("vtkFullScreenRenderWindow");const r=document.querySelector("body");function n(t){"c"===String.fromCharCode(t.charCode)&&e.toggleControllerVisibility()}t.rootContainer||(t.rootContainer=r),t.container||(t.container=document.createElement("div"),Yy(t.container,t.containerStyle||$y),t.rootContainer.appendChild(t.container)),t.rootContainer===r&&(document.documentElement.style.height="100%",r.style.height="100%",r.style.padding="0",r.style.margin="0"),t.renderWindow=nm.newInstance(),t.renderer=Jh.newInstance(),t.renderWindow.addRenderer(t.renderer),t.apiSpecificRenderWindow=t.renderWindow.newAPISpecificView(Xy.viewAPI??t.defaultViewAPI),t.apiSpecificRenderWindow.setContainer(t.container),t.renderWindow.addView(t.apiSpecificRenderWindow),t.interactor=xm.newInstance(),t.interactor.setInteractorStyle(Fm.newInstance()),t.interactor.setView(t.apiSpecificRenderWindow),t.interactor.initialize(),t.interactor.bindEvents(t.container),e.setBackground=t.renderer.setBackground,e.removeController=()=>{const e=t.controlContainer;e&&e.parentNode.removeChild(e)},e.setControllerVisibility=e=>{t.controllerVisibility=e,t.controlContainer&&(t.controlContainer.style.display=e?"block":"none")},e.toggleControllerVisibility=()=>{e.setControllerVisibility(!t.controllerVisibility)},e.addController=r=>{t.controlContainer=document.createElement("div"),Yy(t.controlContainer,t.controlPanelStyle||qy),t.rootContainer.appendChild(t.controlContainer),t.controlContainer.innerHTML=r,e.setControllerVisibility(t.controllerVisibility),t.rootContainer.addEventListener("keypress",n)},e.setBackground(...t.background),e.addRepresentation=e=>{e.getActors().forEach(e=>{t.renderer.addActor(e)})},e.removeRepresentation=e=>{e.getActors().forEach(e=>t.renderer.removeActor(e))},e.delete=zt.chain(e.setContainer,t.apiSpecificRenderWindow.delete,()=>{t.rootContainer?.removeEventListener("keypress",n),window.removeEventListener("resize",e.resize)},e.delete),e.resize=()=>{const e=t.container.getBoundingClientRect(),r=window.devicePixelRatio||1;t.apiSpecificRenderWindow.setSize(Math.floor(e.width*r),Math.floor(e.height*r)),t.resizeCallback&&t.resizeCallback(e),t.renderWindow.render()},e.setResizeCallback=r=>{t.resizeCallback=r,e.resize()},t.listenWindowResize&&window.addEventListener("resize",e.resize),e.resize()}(e,t)}var Zy={newInstance:zt.newInstance(Qy),extend:Qy};const ev=e=>e,tv=1e-6;class rv{constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.matrix=h(new Float64Array(16)),this.tmp=new Float64Array(3),this.angleConv=e?l:ev}rotateFromDirections(e,t){const r=new Float64Array(3),n=new Float64Array(3),o=new Float64Array(16);mr(r,e[0],e[1],e[2]),mr(n,t[0],t[1],t[2]),br(r,r),br(n,n);const i=xr(r,n);return i>=1||(_r(this.tmp,r,n),pr(this.tmp)1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1;if($o(io,this.matrix))return this;const n=-1===r?e.length:t+3*r;for(let r=t;r2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,sv,r),zt.obj(e,t),zt.setGet(e,t,["xLength","yLength","zLength","generate3DTextureCoordinates","generateFaces","generateLines"]),zt.setGetArray(e,t,["center","rotations"],3),zt.setGetArray(e,t,["matrix"],16),t._polys=Xl.newInstance({values:Uint16Array.from(av)}),t._lineCells=Xl.newInstance({values:Uint16Array.from(iv)}),zt.moveToProtected(e,t,["polys","lineCells"]),zt.algo(e,t,0,1),function(e,t){t.classHierarchy.push("vtkCubeSource"),e.requestData=(e,r)=>{const n=r[0]?.initialize()||mc.newInstance();r[0]=n;const o=zt.newTypedArray(t.pointType,72);n.getPoints().setData(o,3);const i=zt.newTypedArray(t.pointType,72),a=_s.newInstance({name:"Normals",values:i,numberOfComponents:3});n.getPointData().setNormals(a);let s=2;!0===t.generate3DTextureCoordinates&&(s=3);const l=zt.newTypedArray(t.pointType,24*s),u=_s.newInstance({name:"TextureCoordinates",values:l,numberOfComponents:s});n.getPointData().setTCoords(u);const c=[0,0,0],d=[0,0,0],p=[0,0];let f=0;c[0]=-t.xLength/2,d[0]=-1,d[1]=0,d[2]=0;for(let e=0;e<2;e++){c[1]=-t.yLength/2;for(let r=0;r<2;r++){p[1]=c[1]+.5,c[2]=-t.zLength/2;for(let n=0;n<2;n++)p[0]=(c[2]+.5)*(1-2*e),o[3*f]=c[0],o[3*f+1]=c[1],o[3*f+2]=c[2],i[3*f]=d[0],i[3*f+1]=d[1],i[3*f+2]=d[2],2===s?(l[f*s]=p[0],l[f*s+1]=p[1]):(l[f*s]=2*e-1,l[f*s+1]=2*r-1,l[f*s+2]=2*n-1),f++,c[2]+=t.zLength;c[1]+=t.yLength}c[0]+=t.xLength,d[0]+=2}c[1]=-t.yLength/2,d[1]=-1,d[0]=0,d[2]=0;for(let e=0;e<2;e++){c[0]=-t.xLength/2;for(let r=0;r<2;r++){p[0]=(c[0]+.5)*(2*e-1),c[2]=-t.zLength/2;for(let n=0;n<2;n++)p[1]=-1*(c[2]+.5),o[3*f]=c[0],o[3*f+1]=c[1],o[3*f+2]=c[2],i[3*f]=d[0],i[3*f+1]=d[1],i[3*f+2]=d[2],2===s?(l[f*s]=p[0],l[f*s+1]=p[1]):(l[f*s]=2*r-1,l[f*s+1]=2*e-1,l[f*s+2]=2*n-1),f++,c[2]+=t.zLength;c[0]+=t.xLength}c[1]+=t.yLength,d[1]+=2}c[2]=-t.zLength/2,d[2]=-1,d[0]=0,d[1]=0;for(let e=0;e<2;e++){c[1]=-t.yLength/2;for(let r=0;r<2;r++){p[1]=c[1]+.5,c[0]=-t.xLength/2;for(let n=0;n<2;n++)p[0]=(c[0]+.5)*(2*e-1),o[3*f]=c[0],o[3*f+1]=c[1],o[3*f+2]=c[2],i[3*f]=d[0],i[3*f+1]=d[1],i[3*f+2]=d[2],2===s?(l[f*s]=p[0],l[f*s+1]=p[1]):(l[f*s]=2*n-1,l[f*s+1]=2*r-1,l[f*s+2]=2*e-1),f++,c[0]+=t.xLength;c[1]+=t.yLength}c[2]+=t.zLength,d[2]+=2}if(t.rotations&&nv().rotateX(t.rotations[0]).rotateY(t.rotations[1]).rotateZ(t.rotations[2]).apply(o).apply(i),t.center&&ov().translate(...t.center).apply(o),t.matrix){ov().setMatrix(t.matrix).apply(o);const e=[t.matrix[0],t.matrix[1],t.matrix[2],0,t.matrix[4],t.matrix[5],t.matrix[6],0,t.matrix[8],t.matrix[9],t.matrix[10],0,0,0,0,1];ov().setMatrix(e).apply(i)}t.generateFaces?n.getPolys().deepCopy(t._polys):n.getPolys().initialize(),t.generateLines?(n.getLines().deepCopy(t._lineCells),n.getPointData().setNormals(null)):n.getLines().initialize(),n.modified()},e.setBounds=function(){let t=[];if(Array.isArray(arguments.length<=0?void 0:arguments[0]))t=arguments.length<=0?void 0:arguments[0];else for(let e=0;e1&&void 0!==arguments[1]?arguments[1]:[0,0,0,0];const[r,n,o,i]=t,a=e.getContext("2d").getImageData(r,n,o||e.width,i||e.height),s=qs.newInstance({type:"vtkImageData"});s.setOrigin(0,0,0),s.setSpacing(1,1,1),s.setExtent(0,(o||e.width)-1,0,(i||e.height)-1,0,0);const l=_s.newInstance({numberOfComponents:4,values:new Uint8Array(a.data.buffer)});return l.setName("scalars"),s.getPointData().setScalars(l),s}var dv={canvasToImageData:cv,imageToImageData:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{flipX:!1,flipY:!1,rotate:0};const r=document.createElement("canvas");r.width=e.width,r.height=e.height;const n=r.getContext("2d"),{flipX:o,flipY:i,rotate:a}=t;return n.translate(r.width/2,r.height/2),n.scale(o?-1:1,i?-1:1),n.rotate(a*Math.PI/180),n.drawImage(e,-e.width/2,-e.height/2),cv(r)}};const pv={default:{defaultStyle:{fontStyle:"bold",fontFamily:"Arial",fontColor:"black",fontSizeScale:e=>e/2,faceColor:"white",edgeThickness:.1,edgeColor:"black",resolution:400},xMinusFaceProperty:{text:"X-",faceColor:"yellow"},xPlusFaceProperty:{text:"X+",faceColor:"yellow"},yMinusFaceProperty:{text:"Y-",faceColor:"red"},yPlusFaceProperty:{text:"Y+",faceColor:"red"},zMinusFaceProperty:{text:"Z-",faceColor:"#008000"},zPlusFaceProperty:{text:"Z+",faceColor:"#008000"}},lps:{xMinusFaceProperty:{text:"R",faceRotation:-90},xPlusFaceProperty:{text:"L",faceRotation:90},yMinusFaceProperty:{text:"A",faceRotation:0},yPlusFaceProperty:{text:"P",faceRotation:180},zMinusFaceProperty:{text:"I",faceRotation:180},zPlusFaceProperty:{text:"S",faceRotation:0}}};function fv(e,t){t.set(e)}var hv={applyDefinitions:fv,applyPreset:function(e,t){return fv(pv[e],t)},registerStylePreset:function(e,t){pv[e]=t}};const mv={xPlus:0,xMinus:1,yPlus:2,yMinus:3,zPlus:4,zMinus:5},gv={defaultStyle:{text:"",faceColor:"white",faceRotation:0,fontFamily:"Arial",fontColor:"black",fontStyle:"normal",fontSizeScale:e=>e/1.8,edgeThickness:.1,edgeColor:"black",resolution:200}};function yv(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,gv,r),ss.extend(e,t,r),zt.get(e,t,["defaultStyle","xPlusFaceProperty","xMinusFaceProperty","yPlusFaceProperty","yMinusFaceProperty","zPlusFaceProperty","zMinusFaceProperty"]),function(e,t){t.classHierarchy.push("vtkAnnotatedCubeActor"),t.xPlusFaceProperty={...t.xPlusFaceProperty},t.xMinusFaceProperty={...t.xMinusFaceProperty},t.yPlusFaceProperty={...t.yPlusFaceProperty},t.yMinusFaceProperty={...t.yMinusFaceProperty},t.zPlusFaceProperty={...t.zPlusFaceProperty},t.zMinusFaceProperty={...t.zMinusFaceProperty};let r=null;const n=document.createElement("canvas"),o=Gl.newInstance(),i=vc.newInstance();function a(r){let o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;o&&Object.assign(t[`${r}FaceProperty`],o);const a={...t.defaultStyle,...t[`${r}FaceProperty`]};n.width=a.resolution,n.height=a.resolution;const s=n.getContext("2d");s.fillStyle=a.faceColor,s.fillRect(0,0,n.width,n.height),a.edgeThickness>0&&(s.strokeStyle=a.edgeColor,s.lineWidth=a.edgeThickness*n.width,s.strokeRect(0,0,n.width,n.height)),s.save(),s.translate(0,n.height),s.scale(1,-1),s.translate(n.width/2,n.height/2),s.rotate(-Math.PI*(a.faceRotation/180));const l=a.fontSizeScale(a.resolution);s.fillStyle=a.fontColor,s.textAlign="center",s.textBaseline="middle",s.font=`${a.fontStyle} ${l}px "${a.fontFamily}"`,s.fillText(a.text,0,0),s.restore();const u=dv.canvasToImageData(n);i.setInputData(u,mv[r]),e.modified()}function s(){r=uv.newInstance({generate3DTextureCoordinates:!0}),o.setInputConnection(r.getOutputPort()),a("xPlus"),a("xMinus"),a("yPlus"),a("yMinus"),a("zPlus"),a("zMinus")}i.setInterpolate(!0),e.setDefaultStyle=e=>{t.defaultStyle={...t.defaultStyle,...e},s()},e.setXPlusFaceProperty=e=>a("xPlus",e),e.setXMinusFaceProperty=e=>a("xMinus",e),e.setYPlusFaceProperty=e=>a("yPlus",e),e.setYMinusFaceProperty=e=>a("yMinus",e),e.setZPlusFaceProperty=e=>a("zPlus",e),e.setZMinusFaceProperty=e=>a("zMinus",e),s(),o.setInputConnection(r.getOutputPort()),e.setMapper(o),e.addTexture(i)}(e,t)}var vv={newInstance:zt.newInstance(yv,"vtkAnnotatedCubeActor"),extend:yv,Presets:hv},bv={Corners:{TOP_LEFT:"TOP_LEFT",TOP_RIGHT:"TOP_RIGHT",BOTTOM_LEFT:"BOTTOM_LEFT",BOTTOM_RIGHT:"BOTTOM_RIGHT"}};const{vtkErrorMacro:xv}=zt,{Corners:_v}=bv,Sv={viewportCorner:bv.Corners.BOTTOM_LEFT,viewportSize:.2,minPixelSize:50,maxPixelSize:200,parentRenderer:null,interactiveRenderer:!1};function Cv(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Sv,r),zt.obj(e,t),zt.get(e,t,["enabled","viewportCorner","viewportSize","interactiveRenderer"]),zt.setGet(e,t,["_interactor","minPixelSize","maxPixelSize","parentRenderer"]),zt.get(e,t,["actor"]),zt.moveToProtected(e,t,["interactor"]),function(e,t){t.classHierarchy.push("vtkOrientationMarkerWidget");const r={...e},n=[],o=Jh.newInstance(),i=new ResizeObserver(t=>{e.updateViewport()});let a=null,s=null,l=null,u=null,c=null;function d(){t._interactor.isAnimating()||e.updateMarkerOrientation()}t._onParentRendererChanged=()=>e.updateViewport(),e.computeViewport=()=>{const e=t.parentRenderer||t._interactor.getCurrentRenderer(),[r,n,o,i]=e.getViewport(),a=t._interactor.getView(),s=a.getSize(),[l,u]=a.getViewportSize(e),c=Math.min(l,u);let d=t.viewportSize*c;d=Math.max(Math.min(t.minPixelSize,c),Math.min(t.maxPixelSize,d));const p=d/s[0],f=d/s[1];switch(t.viewportCorner){case _v.TOP_LEFT:return[r,i-f,r+p,i];case _v.TOP_RIGHT:return[o-p,i-f,o,i];case _v.BOTTOM_LEFT:return[r,n,r+p,n+f];case _v.BOTTOM_RIGHT:return[o-p,n,o,n+f];default:return xv("Invalid widget corner"),null}},e.updateViewport=()=>{t.enabled&&(o.setViewport(...e.computeViewport()),t._interactor.render())},e.updateMarkerOrientation=()=>{const e=(t.parentRenderer||t._interactor.getCurrentRenderer()).getActiveCamera();if(!e)return;const r=e.getReferenceByName("position"),i=e.getReferenceByName("focalPoint"),a=e.getReferenceByName("viewUp");if(n[0]!==r[0]||n[1]!==r[1]||n[2]!==r[2]||n[3]!==i[0]||n[4]!==i[1]||n[5]!==i[2]||n[6]!==a[0]||n[7]!==a[1]||n[8]!==a[2]){n[0]=r[0],n[1]=r[1],n[2]=r[2],n[3]=i[0],n[4]=i[1],n[5]=i[2],n[6]=a[0],n[7]=a[1],n[8]=a[2];const e=o.getActiveCamera();e.setPosition(r[0],r[1],r[2]),e.setFocalPoint(i[0],i[1],i[2]),e.setViewUp(a[0],a[1],a[2]),o.resetCamera()}},e.setEnabled=r=>{if(r){if(t.enabled)return;if(!t.actor)return void xv("Must set actor before enabling orientation marker.");if(!t._interactor)return void xv("Must set interactor before enabling orientation marker.");const r=t.parentRenderer||t._interactor.getCurrentRenderer(),n=r.getRenderWindow();n.addRenderer(o),n.getNumberOfLayers()<2&&n.setNumberOfLayers(2),o.setLayer(n.getNumberOfLayers()-1),o.setInteractive(t.interactiveRenderer),o.addViewProp(t.actor),t.actor.setVisibility(!0),a=r.onEvent(e=>{"ActiveCameraEvent"===e.type&&(s&&s.unsubscribe(),s=e.camera.onModified(d))}),s=r.getActiveCamera().onModified(d),l=t._interactor.onAnimation(e.updateMarkerOrientation),u=t._interactor.onEndAnimation(e.updateMarkerOrientation),i.observe(t._interactor.getView().getCanvas()),e.updateViewport(),e.updateMarkerOrientation(),t.enabled=!0}else{if(!t.enabled)return;t.enabled=!1,i.disconnect(),a.unsubscribe(),a=null,s.unsubscribe(),s=null,l.unsubscribe(),l=null,u.unsubscribe(),u=null,t.actor.setVisibility(!1),o.removeViewProp(t.actor);const e=t._interactor?.findPokedRenderer()?.getRenderWindow();e&&e.removeRenderer(o)}e.modified()},e.setViewportCorner=r=>{r!==t.viewportCorner&&(t.viewportCorner=r,e.updateViewport())},e.setViewportSize=r=>{const n=Math.min(1,Math.max(0,r));n!==t.viewportSize&&(t.viewportSize=n,e.updateViewport())},e.setActor=r=>{const n=t.enabled;e.setEnabled(!1),t.actor=r,e.setEnabled(n)},e.getRenderer=()=>o,e.delete=()=>{r.delete(),c&&(c.unsubscribe(),c=null),a&&(a.unsubscribe(),a=null),s&&(s.unsubscribe(),s=null),l&&(l.unsubscribe(),l=null),u&&(u.unsubscribe(),u=null),i.disconnect()},c=e.onModified(e.updateViewport)}(e,t)}var Tv={newInstance:zt.newInstance(Cv,"vtkOrientationMarkerWidget"),extend:Cv,...bv};function wv(e){return new TextDecoder("latin1").decode(e)}var Av={arrayBufferToString:wv,extractBinary:function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;const n=wv(e),o=t.exec(n);if(!o)return{text:n};const i=o.index+o[0].length,a=n.substring(0,i);let s=null;const l=r?r.exec(n):null;return s=l?{text:a+n.substr(l.index),binaryBuffer:e.slice(i,l.index)}:{text:a,binaryBuffer:e.slice(i)},s}};const Ev={};function Dv(e){return!!Ev[e]}function Pv(e,t){Ev[e]=t}var Iv=function(){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Ev[arguments.length>0&&void 0!==arguments[0]?arguments[0]:"http"](e)};function Ov(){const e=new ArrayBuffer(4),t=new Uint8Array(e),r=new Uint32Array(e);return t[0]=161,t[1]=178,t[2]=195,t[3]=212,3569595041===r[0]?"LittleEndian":2712847316===r[0]?"BigEndian":null}var Nv=Ov(),Mv=function(e,t){if(t<2)return;const r=new Int8Array(e),n=r.length,o=[];for(let e=0;e(Rv("LiteHttpDataAccessHelper does not support compression. Need to register HttpDataAccessHelper instead."),Promise.reject(new Error("LiteHttpDataAccessHelper does not support compression. Need to register HttpDataAccessHelper instead.")));let Lv=0;function kv(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const n=new XMLHttpRequest;return n.open(e,t,!0),r.headers&&Object.entries(r.headers).forEach(e=>{let[t,r]=e;return n.setRequestHeader(t,r)}),r.progressCallback&&n.addEventListener("progress",r.progressCallback),n}const Uv={fetchArray:function(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return n&&n.compression?Bv():r.ref&&!r.ref.pending?new Promise((o,i)=>{const a=kv("GET",[t,r.ref.basepath,r.ref.id].join("/"),n);a.onreadystatechange=t=>{1===a.readyState&&(r.ref.pending=!0,1===++Lv&&e?.invokeBusy&&e.invokeBusy(!0)),4===a.readyState&&(r.ref.pending=!1,200===a.status||0===a.status?(r.buffer=a.response,"JSON"===r.ref.encode?r.values=JSON.parse(r.buffer):(Nv!==r.ref.encode&&Nv&&(Fv(`Swap bytes of ${r.name}`),Mv(r.buffer,ls[r.dataType])),r.values=zt.newTypedArray(r.dataType,r.buffer)),r.values.length!==r.size&&Rv(`Error in FetchArray: ${r.name}, does not have the proper array size. Got ${r.values.length}, instead of ${r.size}`),delete r.ref,0===--Lv&&e?.invokeBusy&&e.invokeBusy(!1),e?.modified&&e.modified(),o(r)):i({xhr:a,e:t}))},a.responseType="string"!==r.dataType?"arraybuffer":"text",a.send()}):Promise.resolve(r)},fetchJSON:function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return r&&r.compression?Bv():new Promise((n,o)=>{const i=kv("GET",t,r);i.onreadystatechange=t=>{1===i.readyState&&1===++Lv&&e?.invokeBusy&&e.invokeBusy(!0),4===i.readyState&&(0===--Lv&&e?.invokeBusy&&e.invokeBusy(!1),200===i.status||0===i.status?n(JSON.parse(i.responseText)):o({xhr:i,e:t}))},i.responseType="text",i.send()})},fetchText:function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return r&&r.compression?Bv():new Promise((n,o)=>{const i=kv("GET",t,r);i.onreadystatechange=t=>{1===i.readyState&&1===++Lv&&e?.invokeBusy&&e.invokeBusy(!0),4===i.readyState&&(0===--Lv&&e?.invokeBusy&&e.invokeBusy(!1),200===i.status||0===i.status?n(i.responseText):o({xhr:i,e:t}))},i.responseType="text",i.send()})},fetchBinary:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((r,n)=>{const o=kv("GET",e,t);o.onreadystatechange=e=>{4===o.readyState&&(200===o.status||0===o.status?r(o.response):n({xhr:o,e}))},o.responseType="arraybuffer",o.send()})},fetchImage:function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return new Promise((e,n)=>{const o=new Image;r.crossOrigin&&(o.crossOrigin=r.crossOrigin),o.onload=()=>e(o),o.onerror=n,o.src=t})}};Dv("http")||Pv("http",e=>Uv);const{vtkErrorMacro:Vv}=zt;function Gv(e,t){for(let r=0;re).slice(-3).map(Number);for(Gv(u,o);-1!==e[t+s].indexOf("vertex");){const n=e[t+s].split(/[ \t]+/).filter(e=>e).slice(-3).map(Number);Gv(n,r),a++,s++}n.push(a);for(let e=0;e2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,jv,r),zt.obj(e,t),zt.get(e,t,["url","baseURL"]),zt.setGet(e,t,["dataAccessHelper","removeDuplicateVertices"]),zt.algo(e,t,0,1),function(e,t){function r(e){const r=t.output[0],n=r.getPoints().getData(),o=r.getPolys().getData();if(!n||!o)return void console.warn("No valid polydata.");const i=new Map,a=new Map;let s=0,l=!1;for(let t=0;t+t*10**-e);t[a]=s[0],t[a+1]=s[1],t[a+2]=s[2]}const s=new Int32Array(o.length);for(let e=0;e1&&void 0!==arguments[1]?arguments[1]:{binary:!0};t.url=r;const o=r.split("/");return o.pop(),t.baseURL=o.join("/"),e.loadData(n)},e.loadData=function(){let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const n=function(r){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const o=void 0!==n.compression?n.compression:t.compression,i=void 0!==n.progressCallback?n.progressCallback:t.progressCallback;return n.binary?t.dataAccessHelper.fetchBinary(r,{compression:o,progressCallback:i}):t.dataAccessHelper.fetchText(e,r,{compression:o,progressCallback:i})}(t.url,r);return n.then(e.parse),n},e.parse=t=>{"string"==typeof t?e.parseAsText(t):e.parseAsArrayBuffer(t)},e.parseAsArrayBuffer=n=>{if(!n)return;if(n===t.parseData)return;e.modified(),t.parseData=n;let o=!1;if(o=84+50*new DataView(n,0,84).getUint32(80,!0)===n.byteLength,!o)return void e.parseAsText(Av.arrayBufferToString(n));const i=n.slice(0,80),a=function(e){const t=e.split(" ").filter(e=>e.indexOf("=")>-1),r={};for(let e=0;e=0&&r(t.removeDuplicateVertices)},e.parseAsText=n=>{if(!n)return;if(n===t.parseData)return;e.modified(),t.parseData=n;const o=n.split("\n");let i=1;const a=[],s=[],l=[];for(;-1!==i;)i=zv(o,i,a,s,l);const u=mc.newInstance();u.getPoints().setData(Float32Array.from(a),3),u.getPolys().setData(Uint32Array.from(s)),u.getCellData().setNormals(_s.newInstance({name:"Normals",values:Float32Array.from(l),numberOfComponents:3})),t.output[0]=u,t.removeDuplicateVertices>=0&&r(t.removeDuplicateVertices)},e.requestData=(r,n)=>{e.parse(t.parseData)}}(e,t),t.compression||(t.compression=null),t.progressCallback||(t.progressCallback=null)}var Hv={extend:Wv,newInstance:zt.newInstance(Wv,"vtkSTLReader")};const Kv="ascii",Xv={diffuse_red:"red",diffuse_green:"green",diffuse_blue:"blue"},$v={patternHeader:/ply([\s\S]*)end_header\r?\n/,patternBody:/end_header\s([\s\S]*)$/};function qv(e){let t="",r=0;const n=$v.patternHeader.exec(e);null!==n&&(t=n[1],r=n[0].length);const o={comments:[],elements:[],headerLength:r},i=t.split("\n");let a,s,l;for(let e=0;e"vertex"===e.name),i=t.find(e=>"face"===e.name);let a=0,s=0;o&&(a=o.count),i&&(s=i.count);let l=new Float32Array(3*a),u=new Uint8Array(3*a),c=new Float32Array(2*a),d=new Float32Array(3*a);const p=e.colors.length>0,f=e.uvs.length>0,h=e.normals.length>0,m=e.faceVertexUvs.length>0,g=new Map;let y=a;for(let t=0;t0){let t=0,o=0;if(n){const n=[],i=[],f=[],m=[];for(let a=0;ar||Math.abs(b[1]-v[1])>r){const s=`${v[0]},${v[1]}`;let c=-1;if(g.has(s)){const e=g.get(s);for(let t=0,n=e.length;t0){const e=a+n.length/3,t=new Float32Array(3*e),r=new Float32Array(2*e),o=p?new Uint8Array(3*e):null,s=h?new Float32Array(3*e):null;t.set(l),r.set(c),p&&o&&o.set(u),h&&s&&s.set(d),t.set(n,3*a),r.set(m,2*a),p&&o&&o.set(i,3*a),h&&s&&s.set(f,3*a),l=t,c=r,p&&(u=o),h&&(d=s)}}else for(let r=0;r0)v.getPolys().setData(Uint32Array.from(e.indices));else{const e=new Uint32Array(2*a);for(let t=0;t0&&(e.indices.push(t.length),t.forEach((t,r)=>{e.indices.push(t)})),e.faceVertexUvs.push(n)}}function eb(e,t,r,n){let o;switch(r){case"int8":case"char":o=[e.getInt8(t),1];break;case"uint8":case"uchar":o=[e.getUint8(t),1];break;case"int16":case"short":o=[e.getInt16(t,n),2];break;case"uint16":case"ushort":o=[e.getUint16(t,n),2];break;case"int32":case"int":o=[e.getInt32(t,n),4];break;case"uint32":case"uint":o=[e.getUint32(t,n),4];break;case"float32":case"float":o=[e.getFloat32(t,n),4];break;case"float64":case"double":o=[e.getFloat64(t,n),8];break;default:console.log("Unsupported type")}return o}function tb(e,t,r,n){const o={};let i,a=0;for(let s=0;s2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,rb,r),zt.obj(e,t),zt.get(e,t,["url","baseURL","duplicatePointsForFaceTexture","faceTextureTolerance"]),zt.setGet(e,t,["dataAccessHelper"]),zt.algo(e,t,0,1),function(e,t){t.classHierarchy.push("vtkPLYReader"),t.dataAccessHelper||(t.dataAccessHelper=Iv("http")),e.setUrl=function(r){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{binary:!0};t.url=r;const o=r.split("/");return o.pop(),t.baseURL=o.join("/"),t.compression=n.compression,e.loadData({progressCallback:n.progressCallback,binary:!!n.binary})},e.loadData=function(){let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const n=function(r){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{compression:o,progressCallback:i}=t;return n.binary?t.dataAccessHelper.fetchBinary(r,{compression:o,progressCallback:i}):t.dataAccessHelper.fetchText(e,r,{compression:o,progressCallback:i})}(t.url,r);return n.then(e.parse),n},e.parse=t=>{"string"==typeof t?e.parseAsText(t):e.parseAsArrayBuffer(t)},e.parseAsArrayBuffer=r=>{if(!r)return;if(r===t.parseData)return;e.modified();let n=r;r instanceof ArrayBuffer&&(n=Av.arrayBufferToString(r));const o=qv(n);if(o.format===Kv)return void e.parseAsText(n);t.parseData=r;const i={indices:[],vertices:[],normals:[],uvs:[],faceVertexUvs:[],colors:[]},a="binary_little_endian"===o.format,s=r instanceof ArrayBuffer?r:r.buffer,l=new DataView(s,o.headerLength);let u,c=0;for(let e=0;e{if(!r)return;if(r===t.parseData)return;e.modified(),t.parseData=r;let n=r;r instanceof ArrayBuffer&&(n=Av.arrayBufferToString(r));const o=qv(n);if(o.format!==Kv)return void e.parseAsArrayBuffer(r);const i={indices:[],vertices:[],normals:[],uvs:[],faceVertexUvs:[],colors:[]},a=$v.patternBody.exec(n);let s="";null!==a&&(s=a[1]);const l=s.split("\n");let u=0,c=0;for(let e=0;e=o.elements[u].count&&(u++,c=0);const e=Qv(o.elements[u].properties,t);Zv(i,o.elements[u].name,e),c++}}const d=Yv(i,o.elements,t.faceTextureTolerance,t.duplicatePointsForFaceTexture);t.output[0]=d},e.requestData=(r,n)=>{e.parse(t.parseData)}}(e,t),t.compression||(t.compression=null),t.progressCallback||(t.progressCallback=null)}var ob={extend:nb,newInstance:zt.newInstance(nb,"vtkPLYReader")};const ib={};function ab(e,t,r,n,o){for(let i=0;iNumber(e));let r=t[0]-1;r=r<0?r+1+ib.v.length/3:r;let n=t[1]?t[1]-1:r;n=n<0?n+1+ib.vt.length/2:n;let o=t[2]?t[2]-1:r;return o=o<0?o+1+ib.vn.length/3:o,[r,n,o]}function lb(e){if("#"===e[0])return;const t=e.split(/[ \t]+/);if(t[0]===ib.splitOn)t.shift(),ib.pieces.push(t.join(" ").trim()),ib.f.push([]),ib.size++;else if("v"===t[0])ib.v.push(Number(t[1])),ib.v.push(Number(t[2])),ib.v.push(Number(t[3]));else if("vt"===t[0])ib.vt.push(Number(t[1])),ib.vt.push(Number(t[2]));else if("vn"===t[0])ib.vn.push(Number(t[1])),ib.vn.push(Number(t[2])),ib.vn.push(Number(t[3]));else if("f"===t[0]){0===ib.size&&ib.size++;const e=ib.f[ib.size-1];t.shift();const r=t.filter(e=>e.length>0&&"\r"!==e),n=r.length;e.push(n);for(let t=0;t2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,cb,r),zt.obj(e,t),zt.get(e,t,["url","baseURL"]),zt.setGet(e,t,["dataAccessHelper","splitMode","trackDuplicates"]),zt.algo(e,t,0,1),zt.event(e,t,"busy"),function(e,t){t.classHierarchy.push("vtkOBJReader"),t.dataAccessHelper||(t.dataAccessHelper=Iv("http")),e.setUrl=function(r){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(-1!==r.indexOf(".obj")||n.fullpath){t.url=r;const e=r.split("/");e.pop(),t.baseURL=e.join("/")}else t.baseURL=r,t.url=`${r}/index.obj`;return e.loadData(n)},e.loadData=function(){let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(r){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return t.dataAccessHelper.fetchText(e,r,n)}(t.url,r).then(t=>!e.isDeleted()&&e.parseAsText(t))},e.parseAsText=r=>{return!r||(r!==t.parseData&&e.modified(),t.parseData=r,t.numberOfOutputs=0,n=t.splitMode,ib.splitOn=n,ib.pieces=[],ib.v=[],ib.vt=[],ib.vn=[],ib.f=[[]],ib.size=0,r.split("\n").forEach(lb),function(e){const t=!!ib.vt.length,r=!!ib.vn.length;if(e.splitMode){e.numberOfOutputs=ib.size;for(let n=0;n1?a+r:t;for(let o=1;o{e.parseAsText(t.parseData)},e.isBusy=()=>!!t.requestCount,e.getNumberOfOutputPorts=()=>t.numberOfOutputs}(e,t)}var pb={newInstance:zt.newInstance(db,"vtkOBJReader"),extend:db,...ub},fb=r(570),hb=Uint8Array,mb=Uint16Array,gb=Uint32Array,yb=new hb([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),vb=new hb([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),bb=new hb([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),xb=function(e,t){for(var r=new mb(31),n=0;n<31;++n)r[n]=t+=1<>>1|(21845&Eb)<<1;Db=(61680&(Db=(52428&Db)>>>2|(13107&Db)<<2))>>>4|(3855&Db)<<4,Ab[Eb]=((65280&Db)>>>8|(255&Db)<<8)>>>1}var Pb=function(e,t,r){for(var n=e.length,o=0,i=new mb(t);o>>l]=u}else for(a=new mb(n),o=0;o>>15-e[o]);return a},Ib=new hb(288);for(Eb=0;Eb<144;++Eb)Ib[Eb]=8;for(Eb=144;Eb<256;++Eb)Ib[Eb]=9;for(Eb=256;Eb<280;++Eb)Ib[Eb]=7;for(Eb=280;Eb<288;++Eb)Ib[Eb]=8;var Ob=new hb(32);for(Eb=0;Eb<32;++Eb)Ob[Eb]=5;var Nb=Pb(Ib,9,1),Mb=Pb(Ob,5,1),Rb=function(e){for(var t=e[0],r=1;rt&&(t=e[r]);return t},Fb=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(7&t)&r},Bb=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},Lb=function(e){return(e+7)/8|0},kb=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Ub=function(e,t,r){var n=new Error(t||kb[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,Ub),!r)throw n;return n},Vb=function(e,t,r){var n=e.length;if(!n||r&&r.f&&!r.l)return t||new hb(0);var o=!t||r,i=!r||r.i;r||(r={}),t||(t=new hb(3*n));var a=function(e){var r=t.length;if(e>r){var n=new hb(Math.max(2*r,e));n.set(t),t=n}},s=r.f||0,l=r.p||0,u=r.b||0,c=r.l,d=r.d,p=r.m,f=r.n,h=8*n;do{if(!c){s=Fb(e,l,1);var m=Fb(e,l+1,3);if(l+=3,!m){var g=e[(E=Lb(l)+4)-4]|e[E-3]<<8,y=E+g;if(y>n){i&&Ub(0);break}o&&a(u+g),t.set(e.subarray(E,y),u),r.b=u+=g,r.p=l=8*y,r.f=s;continue}if(1==m)c=Nb,d=Mb,p=9,f=5;else if(2==m){var v=Fb(e,l,31)+257,b=Fb(e,l+10,15)+4,x=v+Fb(e,l+5,31)+1;l+=14;for(var _=new hb(x),S=new hb(19),C=0;C>>4)<16)_[C++]=E;else{var P=0,I=0;for(16==E?(I=3+Fb(e,l,3),l+=2,P=_[C-1]):17==E?(I=3+Fb(e,l,7),l+=3):18==E&&(I=11+Fb(e,l,127),l+=7);I--;)_[C++]=P}}var O=_.subarray(0,v),N=_.subarray(v);p=Rb(O),f=Rb(N),c=Pb(O,p,1),d=Pb(N,f,1)}else Ub(1);if(l>h){i&&Ub(0);break}}o&&a(u+131072);for(var M=(1<>>4;if((l+=15&P)>h){i&&Ub(0);break}if(P||Ub(2),B<256)t[u++]=B;else{if(256==B){F=l,c=null;break}var L=B-254;if(B>264){var k=yb[C=B-257];L=Fb(e,l,(1<>>4;if(U||Ub(3),l+=15&U,N=wb[V],V>3&&(k=vb[V],N+=Bb(e,l)&(1<h){i&&Ub(0);break}o&&a(u+131072);for(var G=u+L;ue.length)&&(r=e.length);var n=new(2==e.BYTES_PER_ELEMENT?mb:4==e.BYTES_PER_ELEMENT?gb:hb)(r-t);return n.set(e.subarray(t,r)),n}(t,0,u)},Gb=new hb(0);function zb(e,t){return Vb(e.subarray(function(e){31==e[0]&&139==e[1]&&8==e[2]||Ub(6,"invalid gzip data");var t=e[3],r=10;4&t&&(r+=e[10]|2+(e[11]<<8));for(var n=(t>>3&1)+(t>>4&1);n>0;n-=!e[r++]);return r+(2&t)}(e),-8),t||new hb((n=(r=e).length,(r[n-4]|r[n-3]<<8|r[n-2]<<16|r[n-1]<<24)>>>0)));var r,n}function jb(e,t){return Vb(((8!=(15&(r=e)[0])||r[0]>>>4>7||(r[0]<<8|r[1])%31)&&Ub(6,"invalid zlib data"),32&r[1]&&Ub(6,"invalid zlib data: preset dictionaries not supported"),e.subarray(2,-4)),t);var r}var Wb="undefined"!=typeof TextDecoder&&new TextDecoder;try{Wb.decode(Gb,{stream:!0})}catch(e){}"function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout&&setTimeout;const Hb=[];Hb["-".charCodeAt(0)]=62,Hb["_".charCodeAt(0)]=63;const Kb="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(let e=0;e<64;e++)Hb[Kb.charCodeAt(e)]=e;function Xb(e){return void 0!==Hb[e.charCodeAt(0)]}function $b(e,t,r,n){const{start:o,count:i}=t,a=i%4,s=Math.floor(i/4);let l=o,u=null,c=r;for(let t=0;t>16&255,n[c++]=u>>8&255,n[c++]=255&u}switch(a){case 3:for(;!Xb(e[l]);)l++;for(u=Hb[e.charCodeAt(l++)]<<10;!Xb(e[l]);)l++;for(u|=Hb[e.charCodeAt(l++)]<<4;!Xb(e[l]);)l++;u|=Hb[e.charCodeAt(l++)]>>2,n[c++]=u>>8&255,n[c++]=255&u;break;case 2:for(;!Xb(e[l]);)l++;for(u=Hb[e.charCodeAt(l++)]<<2;!Xb(e[l]);)l++;u|=Hb[e.charCodeAt(l++)]>>4,n[c++]=255&u;break;case 1:throw new Error("BASE64: remain 1 should not happen")}return c}var qb=function(e){const t=function(e){const t=e.length,r=[];let n=null;for(let o=0;o2&&void 0!==arguments[2]?arguments[2]:{};if(Object.assign(t,Yb,r),!t.empty&&!t.values&&!t.size)throw new TypeError("Cannot create vtkStringArray object without: size > 0, values");t.values?Array.isArray(t.values)&&(t.values=[...t.values]):t.values=[],t.values&&(t.size=t.values.length),zt.obj(e,t),zt.set(e,t,["name"]),function(e,t){t.classHierarchy.push("vtkStringArray"),e.getComponent=function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return t.values[e*t.numberOfComponents+r]},e.setComponent=(r,n,o)=>{o!==t.values[r*t.numberOfComponents+n]&&(t.values[r*t.numberOfComponents+n]=o,e.modified())},e.getData=()=>t.values,e.getTuple=function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];const n=t.numberOfComponents||1;r.length&&(r.length=n);const o=e*n;for(let e=0;e0&&void 0!==arguments[0]?arguments[0]:1)*t.numberOfComponents},e.getNumberOfComponents=()=>t.numberOfComponents,e.getNumberOfValues=()=>t.values.length,e.getNumberOfTuples=()=>t.values.length/t.numberOfComponents,e.getDataType=()=>t.dataType,e.newClone=()=>Qb({name:t.name,numberOfComponents:t.numberOfComponents,empty:!0}),e.getName=()=>(t.name||e.setName(`vtkStringArray${e.getMTime()}`),t.name),e.setData=(r,n)=>{t.values=r,t.size=r.length,n&&(t.numberOfComponents=n),t.size%t.numberOfComponents!==0&&(t.numberOfComponents=1),e.modified()}}(e,t)}const Qb=zt.newInstance(Jb,"vtkStringArray");var Zb={newInstance:Qb,extend:Jb};function ex(e,t){return function(e,t){return[...e.getElementsByTagName(t)]}(e,t)[0]}const tx={Int8:Int8Array,UInt8:Uint8Array,Int16:Int16Array,UInt16:Uint16Array,Int32:Int32Array,UInt32:Uint32Array,Int64:Int32Array,UInt64:Uint32Array,Float32:Float32Array,Float64:Float64Array},rx={Int8:1,UInt8:1,Int16:2,UInt16:2,Int32:4,UInt32:4,Int64:8,UInt64:8,Float32:4,Float64:8};function nx(e){const t=e.length-1;return e.filter((e,r)=>r>4>7||(e[0]<<8|e[1])%31?function(e,t){return Vb(e,t)}(e,t):jb(e,t)}(e);t.uint8.set(r,t.offset),t.offset+=r.length}function ax(e,t){const r=function(e,t){if("UInt64"===t){const t=8;let r=new Uint32Array(e.buffer,0,6);const n=r[0],o=[t,n,r[2],r[4]];r=new Uint32Array(e.buffer,24,2*n);for(let e=0;e0&&(a=0===i?n*o:(n-1)*o+i);const s=new ArrayBuffer(a),l={offset:0,uint8:new Uint8Array(s)};let u=function(e){const[t]=e;return(e.length-1)*t}(r);for(;u{e.trim().length&&(c[r++]=Number(e))})}else if("binary"===l){const e=new Uint8Array(qb(t.firstChild.nodeValue.trim()));if("vtkZLibDataCompressor"===r){const t=ax(e,o);c=new tx[a](t.buffer),/^U?Int64$/.test(a)&&(c=nx(c))}else c=new tx[a](e.buffer,rx[o]),-1!==a.indexOf("Int64")&&(c=nx(c))}else if("appended"===l){const e=Number(t.getAttribute("offset"));c=ox(new Uint8Array(i,e),a,o)}else console.error("Format not supported",l);return{name:s,values:c,numberOfComponents:u}}function lx(e){return(new TextDecoder).decode(e).split("\0").slice(0,-1)}function ux(e,t){t.classHierarchy.push("vtkXMLReader"),t.dataAccessHelper||(t.dataAccessHelper=Iv("http")),e.setUrl=function(r){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t.url=r;const o=r.split("/");return o.pop(),t.baseURL=o.join("/"),e.loadData(n)},e.loadData=function(){let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return t.dataAccessHelper.fetchBinary(e,r)}(t.url,r).then(e.parseAsArrayBuffer)},e.parseAsArrayBuffer=r=>{if(!r)return!1;if(r===t.rawDataBuffer)return!0;e.modified();const{text:n,binaryBuffer:o}=(i=r,Av.extractBinary(i,/^\s*\s*_/m,/\n\s*<\/AppendedData>/m));var i,a;t.rawDataBuffer=r,t.binaryBuffer=o;const s=(a=n,(0,fb.create)(a)).root(),l=s.node,u=l.getAttribute("type"),c=l.getAttribute("compressor"),d=l.getAttribute("byte_order"),p=l.getAttribute("header_type")||"UInt32";if(c&&"vtkZLibDataCompressor"!==c)return console.error("Invalid compressor",c),!1;if(d&&"LittleEndian"!==d)return console.error("Only LittleEndian encoding is supported"),!1;if(u!==t.dataType)return console.error("Invalid data type",u,"expecting",t.dataType),!1;if(ex(l,"AppendedData")){const e=ex(l,"AppendedData"),r=e.getAttribute("encoding"),n=s.filter(e=>{const{node:t}=e;return t.nodeType===Node.ELEMENT_NODE&&"appended"===t.getAttribute("format")&&t.hasAttribute("offset")},!1,!0).map(e=>({node:e.node,offset:Number(e.node.getAttribute("offset"))}));n.sort((e,t)=>e.offset-t.offset);let o=t.binaryBuffer;"base64"===r&&(o=e.textContent.trim().substr(1));const i=[];for(let e=0;ee+t.length,0),u=new ArrayBuffer(a),d=new Uint8Array(u);for(let e=0,t=0;e_s.newInstance(sx(Number(e.getAttribute("NumberOfTuples")),e,t,0,n,o))),a=[...e.getElementsByTagName("Array")].filter(e=>"String"===e.getAttribute("type")).map(e=>{const r=Zb.newInstance(function(e,t,r,n,o){const i=e.getAttribute("Name"),a=e.getAttribute("format"),s=Number(e.getAttribute("NumberOfComponents")||"1"),l=Number(e.getAttribute("NumberOfTuples")||"1")*s,u=[];if("ascii"===a){const t=e.firstChild.nodeValue.trim().split(/\s+/);let r=0;const n=[];for(;u.length{e.parseAsArrayBuffer(t.rawDataBuffer)}}const cx={};var dx={extend:function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,cx,r),zt.obj(e,t),zt.get(e,t,["url","baseURL"]),zt.setGet(e,t,["dataAccessHelper"]),zt.algo(e,t,0,1),ux(e,t)},processDataArray:sx,processFieldData:function(e,t,r,n,o,i,a){if(t){const o={};["Scalars","Vectors","Normals","Tensors","TCoords"].forEach(e=>{const n=t.getAttribute(e);n&&(o[n]=r[`set${e}`])});const s=t.getElementsByTagName("DataArray"),l=s.length;for(let t=0;t{const t=e-f;d[p++]=t;for(let e=0;e0){const l=r.getElementsByTagName(t)[0].getElementsByTagName("DataArray")[0],{values:u,numberOfComponents:c}=dx.processDataArray(s,l,n,o,i,a);e[`get${t}`]().setData(u,c)}return s}function fx(e,t,r,n,o,i,a){const s=Number(r.getAttribute(`NumberOf${t}`));if(s>0){const l=dx.processCells(s,r.getElementsByTagName(t)[0],n,o,i,a);e[`get${t}`]().setData(l)}return s}const hx={dataType:"PolyData"};function mx(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,hx,r),dx.extend(e,t,r),function(e,t){t.classHierarchy.push("vtkXMLPolyDataReader"),e.parseXML=(e,r,n,o,i)=>{const a=e.getElementsByTagName(t.dataType)[0].getElementsByTagName("Piece"),s=a.length;for(let e=0;e{u+=fx(r,e,s,n,o,i,t.binaryBuffer)}),dx.processFieldData(l,s.getElementsByTagName("PointData")[0],r.getPointData(),n,o,i,t.binaryBuffer),dx.processFieldData(u,s.getElementsByTagName("CellData")[0],r.getCellData(),n,o,i,t.binaryBuffer),t.output[e]=r}}}(e,t)}var gx={newInstance:zt.newInstance(mx,"vtkXMLPolyDataReader"),extend:mx};function yx(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,function(e){return{computeCellNormals:!1,computePointNormals:!0,...e}}(r)),zt.obj(e,t),zt.algo(e,t,1,1),zt.setGet(e,t,["computeCellNormals","computePointNormals"]),function(e,t){t.classHierarchy.push("vtkPolyDataNormals"),e.vtkPolyDataNormalsExecute=(e,r,n)=>{if(!n)return null;const o=new Float32Array(n.length),i=new Float32Array(3*e);let a=0,s=0;const l=r.length,u=[0,0,0],c=[0,0,0];for(let e=0;e{if(!e.getNumberOfInputPorts())return;const o=r[0];if(!o)return;const i=n[0]?.initialize()||mc.newInstance();i.setPoints(o.getPoints()),i.setVerts(o.getVerts()),i.setLines(o.getLines()),i.setPolys(o.getPolys()),i.setStrips(o.getStrips()),i.getPointData().passData(o.getPointData()),i.getCellData().passData(o.getCellData()),i.getFieldData().passData(o.getFieldData());const[a,s]=e.vtkPolyDataNormalsExecute(o.getNumberOfPolys(),o.getPolys().getData(),o.getPoints().getData());if(t.computePointNormals){const e=_s.newInstance({numberOfComponents:3,name:"Normals",values:s});i.getPointData().setNormals(e)}if(t.computeCellNormals){const e=_s.newInstance({numberOfComponents:3,name:"Normals",values:a});i.getCellData().setNormals(e)}n[0]=i}}(e,t)}var vx={newInstance:zt.newInstance(yx,"vtkPolyDataNormals"),extend:yx};const{vtkErrorMacro:bx}=zt;let xx=null;function _x(e,t){const r=function(e,t){const r=3*t.num_faces(),n=4*r,o=xx._malloc(n);e.GetTrianglesUInt32Array(t,n,o);const i=new Uint32Array(xx.HEAPF32.buffer,o,r).slice();return xx._free(o),i}(e,t),n=r.length-2,o=Xl.newInstance();o.allocate(4*r.length/3);for(let e=0;e{const n=Float32Array,o=e.GetAttributeId(t,xx[a[r]]);if(-1===o)return;const s=e.GetAttribute(t,o),l=function(e,t,r,n,o){const i=o.num_components(),a=t.num_points()*i,s=a*n.BYTES_PER_ELEMENT,l=function(e){switch(e){case Float32Array:return xx.DT_FLOAT32;case Int8Array:return xx.DT_INT8;case Int16Array:return xx.DT_INT16;case Int32Array:return xx.DT_INT32;case Uint8Array:return xx.DT_UINT8;case Uint16Array:return xx.DT_UINT16;case Uint32Array:return xx.DT_UINT32;default:return xx.DT_FLOAT32}}(n),u=xx._malloc(s);e.GetAttributeDataArrayForAllPoints(t,o,l,s,u);const c=new n(xx.HEAPF32.buffer,u,a).slice();return xx._free(u),{name:r,array:c,itemSize:i}}(e,t,r,n,s),u=i.getPointData();switch(r){case"points":i.getPoints().setData(l.array,l.itemSize);break;case"normals":u.setNormals(_s.newInstance({numberOfComponents:l.itemSize,values:l.array,name:"Normals"}));break;case"scalars":u.setScalars(_s.newInstance({numberOfComponents:l.itemSize,values:l.array,name:"Scalars"}));break;case"tcoords":u.setTCoords(_s.newInstance({numberOfComponents:l.itemSize,values:l.array,name:"TCoords"}))}}),!i.getPointData().getNormals()){const e=vx.newInstance();return e.setInputData(i),e.setComputePointNormals(!0),e.getOutputData()}return i}const Sx={};function Cx(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Sx,r),zt.obj(e,t),zt.get(e,t,["url","baseURL"]),zt.setGet(e,t,["dataAccessHelper"]),zt.algo(e,t,0,1),function(e,t){t.classHierarchy.push("vtkDracoReader"),t.dataAccessHelper||(t.dataAccessHelper=Iv("http")),e.setUrl=function(r){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{binary:!0};t.url=r;const o=r.split("/");return o.pop(),t.baseURL=o.join("/"),t.compression=n.compression,e.loadData({progressCallback:n.progressCallback,binary:!!n.binary})},e.loadData=function(){let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const n=function(r){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{compression:o,progressCallback:i}=t;return n.binary?t.dataAccessHelper.fetchBinary(r,{compression:o,progressCallback:i}):t.dataAccessHelper.fetchText(e,r,{compression:o,progressCallback:i})}(t.url,r);return n.then(e.parse),n},e.parse=t=>{e.parseAsArrayBuffer(t)},e.parseAsArrayBuffer=r=>{if(!r)return;if(r===t.parseData)return;e.modified(),t.parseData=r;const n=new Int8Array(r),o=new xx.Decoder,i=new xx.DecoderBuffer;let a;if(i.Init(n,n.length),o.GetEncodedGeometryType(i)!==xx.TRIANGULAR_MESH)return void bx("Wrong geometry type, expected mesh, got point cloud.");{a=new xx.Mesh;const e=o.DecodeBufferToMesh(i,a);if(!e.ok())return void bx(`Could not decode Draco file: ${e.error_msg()}`)}const s=_x(o,a);xx.destroy(a),xx.destroy(i),xx.destroy(o),t.output[0]=s},e.requestData=()=>{e.parse(t.parseData)}}(e,t),t.compression||(t.compression=null),t.progressCallback||(t.progressCallback=null)}var Tx={extend:Cx,newInstance:zt.newInstance(Cx,"vtkDracoReader"),setDracoDecoder:async function(e){xx=await e({})},setWasmBinary:function(e,t){const r={};return new Promise((n,o)=>{r.wasmBinaryFile=t;const i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=()=>{200===i.status?(r.wasmBinary=i.response,Promise.resolve(window.DracoDecoderModule(r)).then(e=>{xx=e,n(!0)},o)):o(Error(`WASM binary could not be loaded: ${i.statusText}`))},i.send(null)})},getDracoDecoder:function(){return xx}};const{vtkWarningMacro:wx}=zt;let Ax;const Ex={preMultiplyFlag:!1,matrix:[...io]};function Dx(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,Ex,r),zt.obj(e,t),zt.setGet(e,t,["preMultiplyFlag"]),zt.setGetArray(e,t,["matrix"],16),function(e,t){t.classHierarchy.push("vtkAbstractTransform","vtkHomogeneousTransform","vtkTransform"),e.transformPoint=(e,r)=>(Sr(r,e,t.matrix),r),e.transformPoints=(e,r)=>{const n=new Float64Array(3),o=new Float64Array(3);for(let i=0;i{e.setPreMultiplyFlag(!0)},e.postMultiply=()=>{e.setPreMultiplyFlag(!1)},e.transformMatrix=(e,r)=>(t.preMultiplyFlag?b(r,t.matrix,e):b(r,e,t.matrix),r),e.transformMatrices=(e,r)=>{const n=new Float64Array(16),o=new Float64Array(16),i=t.preMultiplyFlag?()=>b(o,t.matrix,n):()=>b(o,n,t.matrix);for(let t=0;tAx({matrix:Oi.invertMatrix(Array.from(t.matrix),[],4),preMultiplyFlag:t.preMultiplyFlag}),e.translate=(r,n,o)=>{if(0===r&&0===n&&0===o)return;const i=u();A(i,[r,n,o]),t.preMultiplyFlag?b(t.matrix,t.matrix,i):b(t.matrix,i,t.matrix),e.modified()},e.rotateWXYZ=(r,n,o,i)=>{if(0===n&&0===o&&0===i)return void wx("No rotation applied, axis is zero vector.");if(0===r)return;const a=Oi.radiansFromDegrees(r),s=Mi();Ri(s,[n,o,i],a);const l=new Float64Array(16);U(l,s),t.preMultiplyFlag?b(t.matrix,t.matrix,l):b(t.matrix,l,t.matrix),e.modified()},e.rotateX=t=>{e.rotateWXYZ(t,1,0,0)},e.rotateY=t=>{e.rotateWXYZ(t,0,1,0)},e.rotateZ=t=>{e.rotateWXYZ(t,0,0,1)},e.scale=(r,n,o)=>{if(1===r&&1===n&&1===o)return;const i=u();E(i,[r,n,o]),t.preMultiplyFlag?b(t.matrix,t.matrix,i):b(t.matrix,i,t.matrix),e.modified()},e.transformNormal=function(r){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];const o=se(ae(),t.matrix),i=ae();he(i,o);const a=ae();return fe(a,i),e.transformVector(r,n,a),Oi.normalize(n),n},e.transformNormals=(r,n)=>{const o=r.getData(),i=n.getData(),a=[0,0,0],s=se(ae(),t.matrix),l=ae();he(l,s);const u=ae();fe(u,l);for(let t=0;t1&&void 0!==arguments[1]?arguments[1]:[];return function(e,t,r){var n=t[0],o=t[1],i=t[2];e[0]=n*r[0]+o*r[3]+i*r[6],e[1]=n*r[1]+o*r[4]+i*r[7],e[2]=n*r[2]+o*r[5]+i*r[8]}(r,e,(arguments.length>2&&void 0!==arguments[2]?arguments[2]:null)||se(ae(),t.matrix)),r},e.transformVectors=(t,r)=>{const n=t.getData(),o=r.getData(),i=[0,0,0];for(let t=0;t6&&void 0!==arguments[6]?arguments[6]:null,l=arguments.length>7&&void 0!==arguments[7]?arguments[7]:null;const u=t.getNumberOfPoints(),c=s?.length??0,d=new Float64Array(3),p=new Float64Array(3),f=new Float64Array(3),h=new Float64Array(3);let m=!1,g=!1,y=!1;const v=[];for(let b=0;bl[e].modified())}}(e,t)}Ax=zt.newInstance(Dx,"vtkTransform");var Px={newInstance:Ax,extend:Dx};const Ix="glTF",Ox={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Nx={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},Mx={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},Rx=9987,Fx=10497,Bx={magFilter:9728,minFilter:Rx,wrapS:Fx,wrapT:Fx},Lx={NORMAL:"normal",POSITION:"position",TEXCOORD_0:"texcoord0",TEXCOORD_1:"texcoord1",WEIGHTS_0:"weight",JOINTS_0:"joint",COLOR_0:"color",TANGENT:"tangent"},kx="OPAQUE",{vtkWarningMacro:Ux,vtkErrorMacro:Vx}=zt;function Gx(e){return{magFilter:10240,minFilter:10241,wrapS:10242,wrapT:10243}[e]}function zx(e,t){if("string"!=typeof e||""===e)return"";try{if(e.startsWith("data:"))return e;if(e.startsWith("blob:"))return e;const r=new URL(t);return r.pathname.includes(".")||r.pathname.endsWith("/")||(r.pathname+="/"),e.startsWith("http:")||e.startsWith("https:")||e.startsWith("//")||e.startsWith("/"),new URL(e,r).href}catch(e){return Vx("Error resolving URL:",e),""}}async function jx(e){if(e.bufferView){const t=new Blob([e.bufferView.data],{type:e.mimeType});return await createImageBitmap(t,{colorSpaceConversion:"none",imageOrientation:"flipY"})}return e.uri?(Ux("Falling back to image uri",e.uri),new Promise((t,r)=>{const n=new Image;n.crossOrigin="Anonymous",n.onload=()=>{t(n)},n.onerror=r,n.src=e.uri})):null}function Wx(e,t,r){const n=vc.newInstance();if(t)if("wrapS"in t&&"wrapT"in t||"minFilter"in t&&"magFilter"in t){33071===t.wrapS||33071===t.wrapT?(n.setRepeat(!1),n.setEdgeClamp(!0)):t.wrapS===Fx||t.wrapT===Fx?(n.setRepeat(!0),n.setEdgeClamp(!1)):Ux("Mirrored texture wrapping is not supported!");const e=[9729,9985,9986,Rx];(e.includes(t.minFilter)||e.includes(t.magFilter))&&n.setInterpolate(!0)}else n.setMipLevel(8),n.setInterpolate(!0),n.setEdgeClamp(!0);return n.setImageBitmap(e),n}const{vtkDebugMacro:Hx,vtkWarningMacro:Kx}=zt;class Xx{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{json:r,baseUri:n=""}=e;this.glTF=e,this.options=t,this.baseUri=n,this.json=r,this.extensions=r.extensions||{},this.extensionsUsed=r.extensionsUsed||[]}async parse(){const e=this.json.buffers||[];this.buffers=new Array(e.length).fill(null);const t=this.json.images||[];return this.images=new Array(t.length).fill({}),await this.loadBuffers(),await this.loadImages(),this.resolveTree(),this.glTF.json}resolveTree(){this.json.scenes=this.json.scenes?.map((e,t)=>this.resolveScene(e,t)),this.json.cameras=this.json.cameras?.map((e,t)=>this.resolveCamera(e,t)),this.json.bufferViews=this.json.bufferViews?.map((e,t)=>this.resolveBufferView(e,t)),this.json.images=this.json.images?.map((e,t)=>this.resolveImage(e,t)),this.json.samplers=this.json.samplers?.map((e,t)=>this.resolveSampler(e,t)),this.json.textures=this.json.textures?.map((e,t)=>this.resolveTexture(e,t)),this.json.accessors=this.json.accessors?.map((e,t)=>this.resolveAccessor(e,t)),this.json.materials=this.json.materials?.map((e,t)=>this.resolveMaterial(e,t)),this.json.meshes=this.json.meshes?.map((e,t)=>this.resolveMesh(e,t)),this.json.nodes=this.json.nodes?.map((e,t)=>this.resolveNode(e,t)),this.json.skins=this.json.skins?.map((e,t)=>this.resolveSkin(e,t)),this.json.animations=this.json.animations?.map((e,t)=>this.resolveAnimation(e,t))}get(e,t){if("object"==typeof t)return t;const r=this.json[e]&&this.json[e][t];return r||Kx(`glTF file error: Could not find ${e}[${t}]`),r}resolveScene(e,t){return e.id=e.id||`scene-${t}`,e.nodes=(e.nodes||[]).map(e=>this.get("nodes",e)),e}resolveNode(e,t){return e.id=e.id||`node-${t}`,e.children&&(e.children=e.children.map(e=>this.get("nodes",e))),void 0!==e.mesh?e.mesh=this.get("meshes",e.mesh):void 0!==e.meshes&&e.meshes.length&&(e.mesh=e.meshes.reduce((e,t)=>{const r=this.get("meshes",t);return e.id=r.id,e.primitives=e.primitives.concat(r.primitives),e},{primitives:[]})),void 0!==e.camera&&(e.camera=this.get("cameras",e.camera)),void 0!==e.skin&&(e.skin=this.get("skins",e.skin)),e.extensions?.KHR_lights_punctual&&(e.extensions.KHR_lights_punctual.light=this.extensions?.KHR_lights_punctual.lights[e.extensions.KHR_lights_punctual.light]),e}resolveSkin(e,t){return e.id=e.id||`skin-${t}`,e.inverseBindMatrices=this.get("accessors",e.inverseBindMatrices),e}resolveMesh(e,t){return e.id=e.id||`mesh-${t}`,e.primitives&&(e.primitives=e.primitives.map((e,t)=>{const r=e.attributes;e.name=`primitive-${t}`,e.attributes={};for(const t in r){const n=Lx[t];e.attributes[n]=this.get("accessors",r[t])}if(void 0!==e.indices&&(e.indices=this.get("accessors",e.indices)),void 0!==e.material&&(e.material=this.get("materials",e.material)),void 0===e.mode&&(e.mode=4),e.extensions?.KHR_draco_mesh_compression){Hx("Using Draco mesh compression");const t=this.get("bufferViews",e.extensions.KHR_draco_mesh_compression.bufferView);e.extensions.KHR_draco_mesh_compression.bufferView=t.data}return e})),e}resolveMaterial(e,t){if(e.id=e.id||`material-${t}`,void 0===e.alphaMode&&(e.alphaMode=kx),void 0===e.doubleSided&&(e.doubleSided=!1),void 0===e.alphaCutoff&&(e.alphaCutoff=.5),e.normalTexture&&(e.normalTexture={...e.normalTexture},e.normalTexture.texture=this.get("textures",e.normalTexture.index)),e.occlusionTexture&&(e.occlusionTexture={...e.occlusionTexture},e.occlusionTexture.texture=this.get("textures",e.occlusionTexture.index)),e.emissiveTexture&&(e.emissiveTexture={...e.emissiveTexture},e.emissiveTexture.texture=this.get("textures",e.emissiveTexture.index)),e.emissiveFactor?e.emissiveFactor=e.emissiveFactor[0]:e.emissiveFactor=e.emissiveTexture?1:0,e.pbrMetallicRoughness){e.pbrMetallicRoughness={...e.pbrMetallicRoughness};const t=e.pbrMetallicRoughness;t.baseColorTexture&&(t.baseColorTexture={...t.baseColorTexture},t.baseColorTexture.texture=this.get("textures",t.baseColorTexture.index)),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture={...t.metallicRoughnessTexture},t.metallicRoughnessTexture.texture=this.get("textures",t.metallicRoughnessTexture.index))}else e.pbrMetallicRoughness={baseColorFactor:[1,1,1,1],metallicFactor:1,roughnessFactor:1};return e}getValueFromInterleavedBuffer(e,t,r,n,o){const i=new Uint8Array(o*n);for(let a=0;a{const r=e.extensions[t];switch(t){case"KHR_texture_basisu":case"EXT_texture_webp":case"EXT_texture_avif":e.source=this.get("images",r.source);break;default:Kx(`Unhandled extension: ${t}`)}}),e}resolveSampler(e,t){e.id=e.id||`sampler-${t}`,Object.hasOwn(e,"wrapS")||(e.wrapS=Fx),Object.hasOwn(e,"wrapT")||(e.wrapT=Fx),Object.hasOwn(e,"minFilter")||(e.minFilter=Rx),Object.hasOwn(e,"magFilter")||(e.magFilter=9728),e.parameters={};for(const t in e){const r=Gx(t);void 0!==r&&(e.parameters[r]=e[t])}return e}resolveImage(e,t){return e.id=e.id||`image-${t}`,void 0!==e.bufferView&&(e.bufferView=this.get("bufferViews",e.bufferView)),e}resolveBufferView(e,t){e.id=e.id||`bufferView-${t}`;const r=e.buffer;e.buffer=this.buffers[r];const n=this.buffers[r].arrayBuffer;let o=this.buffers[r].byteOffset||0;return"byteOffset"in e&&(o+=e.byteOffset),e.data=new Uint8Array(n,o,e.byteLength),e}resolveCamera(e,t){return e.id=e.id||`camera-${t}`,e}resolveAnimation(e,t){return e.id=e.id||`animation-${t}`,e.samplers.map(e=>(e.input=this.get("accessors",e.input).value,e.output=this.get("accessors",e.output).value,e)),e}loadBuffers(){const e=this.json.buffers.map((e,t)=>this.loadBuffer(e,t).then(()=>{delete e.uri}));return Promise.all(e)}async loadBuffer(e,t){let r=e;if(e.uri){Hx("Loading uri",e.uri);const t=zx(e.uri,this.options.baseUri),n=await fetch(t);r=await n.arrayBuffer()}else this.glTF.glbBuffers&&(r=this.glTF.glbBuffers[t]);this.buffers[t]={arrayBuffer:r,byteOffset:0,byteLength:r.byteLength}}loadImages(){const e=this.json.images||[],t=[];return new Promise((r,n)=>{for(let r=0;r{Hx("Texture loaded ",e[r])})));Promise.all(t).then(()=>r(this.images))})}async loadImage(e,t){let r,n;if(e.uri){Hx("Loading texture",e.uri);const t=zx(e.uri,this.options.baseUri),n=await fetch(t);r=await n.arrayBuffer(),e.uri=t,e.bufferView={data:r}}else if(e.bufferView){const t=this.get("bufferViews",e.bufferView);n=this.get("buffers",t.buffer),this.glTF.glbBuffers&&(n=this.glTF.glbBuffers[t.buffer],r=n.slice(t.byteOffset,t.byteOffset+t.byteLength)),e.bufferView={data:r}}}}const{vtkWarningMacro:$x}=zt,{vtkWarningMacro:qx,vtkDebugMacro:Yx}=zt;async function Jx(e,t,r){let n=1,o=1;const i=t.emissiveFactor,a=r.getProperty(),s=t.pbrMetallicRoughness;if(null!=s){!s?.metallicFactor||s?.metallicFactor<=0||s?.metallicFactor>=1?Yx("Invalid material.pbrMetallicRoughness.metallicFactor value. Using default value instead."):n=s.metallicFactor,!s?.roughnessFactor||s?.roughnessFactor<=0||s?.roughnessFactor>=1?Yx("Invalid material.pbrMetallicRoughness.roughnessFactor value. Using default value instead."):o=s.roughnessFactor;const e=s.baseColorFactor;if(null!=e&&(a.setDiffuseColor(e[0],e[1],e[2]),a.setOpacity(e[3])),a.setMetallic(n),a.setRoughness(o),a.setEmission(i),s.baseColorTexture){s.baseColorTexture.extensions;const e=s.baseColorTexture.texture;null!=e.extensions&&Object.keys(e.extensions).forEach(e=>{qx(`Unhandled extension: ${e}`)});const t=e.sampler,r=Wx(await jx(e.source),t);a.setDiffuseTexture(r)}if(s.metallicRoughnessTexture){s.metallicRoughnessTexture.extensions;const e=s.metallicRoughnessTexture.texture,t=e.sampler,r=Wx(await jx(e.source),t);a.setRMTexture(r)}if(t.occlusionTexture){t.occlusionTexture.extensions;const e=t.occlusionTexture.texture,r=e.sampler,n=Wx(await jx(e.source),r);a.setAmbientOcclusionTexture(n)}if(t.emissiveTexture){t.emissiveTexture.extensions;const e=t.emissiveTexture.texture,n=e.sampler,o=Wx(await jx(e.source),n);a.setEmissionTexture(o),null!=t.emissiveTexture.texCoord&&r.getMapper().getInputData().getPointData().setActiveTCoords(`TEXCOORD_${t.emissiveTexture.texCoord}`)}if(t.normalTexture){t.normalTexture.extensions;const e=t.normalTexture.texture,r=e.sampler,n=Wx(await jx(e.source),r);a.setNormalTexture(n),null!=t.normalTexture.scale&&a.setNormalStrength(t.normalTexture.scale)}}null!=t.extensions&&Object.keys(t.extensions).forEach(e=>{const r=t.extensions[e];switch(e){case"KHR_materials_unlit":!function(e,t){t.setLighting(!0)}(0,a);break;case"KHR_materials_ior":!function(e,t){t.setBaseIOR(e.ior)}(r,a);break;case"KHR_materials_specular":!function(e,t){t.setSpecular(e.specularFactor),t.setSpecularColor(e.specularColorFactor)}(r,a);break;default:qx(`Unhandled extension: ${e}`)}}),t.alphaMode!==kx&&r.setForceTranslucent(!0),a.setBackfaceCulling(!t.doubleSided)}async function Qx(e,t,r){const n=ss.newInstance(),o=Gl.newInstance();o.setColorModeToDirectScalars(),o.setInterpolateScalarsBeforeMapping(!0),n.setMapper(o),n.setUserMatrix(r);const i=await async function(e){if(!e||!e.attributes)return qx("Primitive has no position data, skipping"),null;if(e.extensions?.KHR_draco_mesh_compression)return function(e){const t=Tx.newInstance();return t.parse(e.bufferView),t.getOutputData()}(e.extensions.KHR_draco_mesh_compression);const t=mc.newInstance(),r=Xl.newInstance(),n=t.getPointData();if(Object.entries(e.attributes).forEach(async r=>{let[o,i]=r;switch(o){case Lx.POSITION:{const r=e.attributes.position.value;t.getPoints().setData(r,e.attributes.position.component);break}case Lx.NORMAL:{const t=e.attributes.normal.value;n.setNormals(_s.newInstance({name:"Normals",values:t,numberOfComponents:e.attributes.normal.components}));break}case Lx.COLOR_0:{const t=e.attributes.color.value;n.setScalars(_s.newInstance({name:"Scalars",values:t,numberOfComponents:e.attributes.color.components}));break}case Lx.TEXCOORD_0:{const t=e.attributes.texcoord0.value,r=_s.newInstance({name:"TEXCOORD_0",values:t,numberOfComponents:e.attributes.texcoord0.components});n.addArray(r),n.setActiveTCoords(r.getName());break}case Lx.TEXCOORD_1:{const t=e.attributes.texcoord1.value,r=_s.newInstance({name:"TEXCOORD_1",values:t,numberOfComponents:e.attributes.texcoord1.components});n.addArray(r);break}case Lx.TANGENT:{const t=e.attributes.tangent.value,r=_s.newInstance({name:"Tangents",values:t,numberOfComponents:e.attributes.tangent.components});n.addArray(r);break}default:qx(`Unhandled attribute: ${o}`)}}),null!=e.indices){const t=e.indices.value,n=t.length-2;switch(e.mode){case 3:case 5:case 2:qx("GL_LINE_LOOP not implemented");break;default:r.allocate(4*t.length/3);for(let e=0;e{const o=t[n];switch(n){case"KHR_materials_variants":r.variantMappings.set(e,o.mappings);break;case"KHR_draco_mesh_compression":break;default:qx(`Unhandled extension: ${n}`)}})}(`${t.name}`,t.extensions,e),n}function Zx(e){return Yx("Creating animation:",e),{name:e.name,channels:e.channels,samplers:e.samplers,getChannelByTargetNode(e){return this.channels.filter(t=>t.target.node===e)}}}async function e_(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:u();e.transform=function(e){const t=e.translation??dr(),r=e.rotation??Mi(),n=e.scale??fr(1,1,1);return null!=e.matrix?c(e.matrix):L(u(),r,t,n)}(e);const o=b(u(),n,e.transform);if(null!=e.mesh){const n=await async function(e){const t=ss.newInstance(),r=Gl.newInstance();r.setColorModeToDirectScalars(),r.setInterpolateScalarsBeforeMapping(!0),t.setMapper(r),t.setUserMatrix(e);const n=mc.newInstance();return r.setInputData(n),t}(o);r&&n.setParentProp(r),t.actors.set(`${e.id}`,n),await Promise.all(e.mesh.primitives.map(async(r,i)=>{const a=await Qx(t,r,o);a.setParentProp(n),t.actors.set(`${e.id}_${r.name}`,a)}))}e.extensions?.KHR_lights_punctual&&function(e,t,r){const{light:n}=e,{color:o,intensity:i,range:a,spot:s,type:l}=n,u=Vh.newInstance({color:o||[1,1,1],intensity:i||1});switch(u.setTransformMatrix(t),a>0&&u.setAttenuationValues(1,0,1/(a*a*.01)),l){case"directional":u.setPositional(!1);break;case"point":u.setPositional(!0),u.setConeAngle(90);break;case"spot":u.setPositional(!0),u.setConeAngle(yo(s.outerConeAngle));break;default:$x(`Unsupported light type: ${l}`)}r.lights.set(n.name,u)}(e.extensions.KHR_lights_punctual,e.transform,t),e.children&&Array.isArray(e.children)&&e.children.length>0&&await Promise.all(e.children.map(async r=>{const n=t.actors.get(e.id);await e_(r,t,n,o)}))}function t_(e,t){const r=new Uint32Array(t,e,2);return{start:e+8,length:r[0],type:r[1]}}function r_(e,t){const r=new Uint8Array(t,20,e.length),n=new TextDecoder("utf-8").decode(r);return JSON.parse(n)}function n_(e,t){return t.slice(e.start,e.start+e.length)}const{vtkDebugMacro:o_,vtkWarningMacro:i_}=zt;function a_(e,t){const r=e.target.path,n=e.target.node;return{...e,animate:function(o){!function(e){let t,o,i;switch(r){case"translation":n.setPosition(e[0],e[1],e[2]);break;case"rotation":i=function(e,t){var r=t[0],n=t[1],o=t[2],i=t[3],a=r*r+n*n+o*o+i*i;return a>0&&(a=1/Math.sqrt(a)),e[0]=r*a,e[1]=n*a,e[2]=o*a,e[3]=i*a,e}(Mi(),e),t=new Float64Array(3),o=Fi(t,i),n.rotateWXYZ(vo(o),t[0],t[1],t[2]);break;case"scale":n.setScale(e[0],e[1],e[2]);break;default:i_(`Unsupported animation path: ${r}`)}}(t[e.sampler].evaluate(o,r))}}}function s_(e,t){const r=new Map,n=new Map;return{addAnimation:function(t){const n=function(e,t){return e.samplers=e.samplers.map(e=>function(e){let t=0;return{...e,evaluate:function(r,n){const[o,i,a,s]=function(r){let n=t;for(;n{const r=c-u;return(2*c-3*u+1)*e+(c-2*u+l)*p[t]+(-2*c+3*u)*f[t]+r*h[t]}):(2*c-3*u+1)*d+(c-2*u+l)*p+(-2*c+3*u)*f+(c-u)*h}(0,o,i,a,s,r);break;default:i_(`Unknown interpolation method: ${e.interpolation}`)}return l}}}(e)),e.channels=e.channels.map(r=>(r.target.node=t.get(`node-${r.target.node}`),a_(r,e.samplers))),{...e,update:function(t){e.channels.forEach(e=>e.animate(t))}}}(t,e);r.set(t.id,n),o_(`Animation "${t.id}" added to mixer`)},play:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;r.has(e)?(n.set(e,{animation:r.get(e),weight:t,time:0}),o_(`Playing animation "${e}" with weight ${t}`)):i_(`Animation "${e}" not found in mixer`)},stop:function(e){n.delete(e)?i_(`Stopped animation "${e}"`):i_(`Animation "${e}" was not playing`)},stopAll:function(){n.clear(),i_("Stopped all animations")},update:function(e){const t=Array.from(n.values()).reduce((e,t)=>{let{weight:r}=t;return e+r},0);n.forEach((r,o)=>{let{animation:i,weight:a,time:s}=r;const l=t>0?a/t:0,u=s+e;n.set(o,{animation:i,weight:a,time:u}),o_(`Updating animation "${o}" at time ${u.toFixed(3)} with normalized weight ${l.toFixed(3)}`),i.update(u,l)})}}}const{vtkDebugMacro:l_,vtkErrorMacro:u_}=zt;function c_(e,t){t.classHierarchy.push("vtkGLTFImporter"),t.dataAccessHelper||(t.dataAccessHelper=Iv("http")),e.setUrl=function(r){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{binary:!0};t.url=r;const o=r.split("/");return o.pop(),t.baseURL=o.join("/"),t.compression=n.compression,t.sceneId=n.sceneId?n.sceneId:0,e.loadData({progressCallback:n.progressCallback,binary:!!n.binary})},e.loadData=function(){let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const n=function(r){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{compression:o,progressCallback:i}=t;return n.binary?t.dataAccessHelper.fetchBinary(r,{compression:o,progressCallback:i}):t.dataAccessHelper.fetchText(e,r,{compression:o,progressCallback:i})}(t.url,r);return n.then(e.parse),n},e.parse=t=>{"string"==typeof t?e.parseAsText(t):e.parseAsBinary(t)},e.parseAsBinary=async r=>{if(!r)return;if(r===t.parseData)return;e.modified();const n={},o={baseUri:t.baseURL};if(Av.arrayBufferToString(new Uint8Array(r,0,4))===Ix){const{json:e,buffers:t}=function(e){if(e.byteLength<12)throw new Error("Invalid GLB: File too small");const t=new DataView(e,0,12),r=new Uint8Array(e,0,4),n=Av.arrayBufferToString(r),o=t.getUint32(4,!0),i=t.getUint32(8,!0);if(n!==Ix)throw new Error("Unsupported glTF-Binary header.");if(o<2)throw new Error("Unsupported legacy binary file detected.");if(i>e.byteLength)throw new Error("Invalid GLB: Declared length exceeds file size");const a=function(e){const t=Math.floor((e.byteLength-12)/8),r=new Array(t);let n=12,o=0;for(;n=2.0 are supported."):(t.glTFTree=await async function(e,t){const r=new Xx(e,t);return await r.parse()}(n,o),t.actors=new Map,t.cameras=new Map,t.lights=new Map,t.animations=[],t.variants=[],t.variantMappings=new Map,await async function(e){e.animations=e.glTFTree.animations?.map(Zx),Object.keys(e.glTFTree?.extensions||[]).forEach(t=>{const r=e.glTFTree.extensions[t];switch(t){case"KHR_materials_variants":!function(e,t){t.variants=e.variants.map(e=>e.name)}(r,e);break;case"KHR_draco_mesh_compression":break;default:qx(`Unhandled extension: ${t}`)}});const t=e.sceneId??e.glTFTree.scene;e.glTFTree.scenes?.length&&e.glTFTree.scenes[t]?.nodes?await Promise.all(e.glTFTree.scenes[t].nodes.map(async t=>{t?await e_(t,e):qx("Node not found in glTF.nodes")})):qx("No valid scenes found in the glTF data")}(t),t.scenes=t.glTFTree.scenes,e.invokeReady())},e.parseAsText=r=>{r&&r!==t.parseData&&(e.modified(),t.parseData=r)},e.requestData=(r,n)=>{e.parse(t.parseData)},e.setDracoDecoder=async e=>{await Tx.setDracoDecoder(e)},e.importActors=()=>{t.actors.forEach(e=>t.renderer.addActor(e))},e.importCameras=()=>{t.glTFTree.cameras?.forEach(e=>{const r=function(e){const t=Lh.newInstance();if("perspective"===e.type){const{yfov:r,znear:n,zfar:o}=e.perspective;t.setClippingRange(n,o),t.setParallelProjection(!1),t.setViewAngle(vo(r))}else{if("orthographic"!==e.type)throw new Error("Unsupported camera type");{const{ymag:r,znear:n,zfar:o}=e.orthographic;t.setClippingRange(n,o),t.setParallelProjection(!0),t.setParallelScale(r)}}return t}(e);t.cameras.set(e.id,r)}),t.scenes.forEach(e=>{e.nodes.forEach(e=>{const r=t.cameras.get(e.camera?.id);r&&function(e,t){if(!e||!t)return;const r=[0,0,0],n=[0,1,0],o=[0,0,-1],i=Px.newInstance();i.setMatrix(t),i.transformPoint(r,r),i.transformPoints(n,n),i.transformPoints(o,o),o[0]+=r[0],o[1]+=r[1],o[2]+=r[2],e.setPosition(r),e.setFocalPoint(o),e.setViewUp(n)}(r,e.transform)})})},e.importAnimations=()=>{t.glTFTree.animations?.length>0&&(t.animationMixer=s_(t.actors,t.glTFTree.accessors),t.glTFTree.animations.forEach(e=>{t.animationMixer.addAnimation(e)})),t.animations=t.glTFTree.animations||[]},e.importLights=()=>{t.lights?.forEach(e=>{l_("Adding light",e),t.renderer.addLight(e)})},e.setCamera=e=>{const r=t.cameras.get(e);r?(l_("Setting camera",r),t.renderer.setActiveCamera(r)):u_(`Camera ${e} not found`)},e.switchToVariant=async e=>{const r=Array.from(t.actors).map(async r=>{let[n,o]=r;l_("Switching to variant",e,"for node",n);const i=t.variantMappings.get(n);if(i){const r=i.find(t=>t.variants.includes(e));if(r){const e=t.glTFTree.materials[r.material];await Jx(0,e,o)}}});await Promise.all(r)}}const d_={};function p_(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,d_,r),zt.obj(e,t),zt.get(e,t,["url","baseURL","actors","scenes","cameras","animations","animationMixer","variants","variantMappings"]),zt.set(e,t,["renderer","dracoDecoder"]),zt.event(e,t,"ready"),c_(e,t),t.compression||(t.compression=null),t.progressCallback||(t.progressCallback=null)}var f_={extend:p_,newInstance:zt.newInstance(p_,"vtkGLTFImporter")};const{vtkErrorMacro:h_}=jt;function m_(e,t){t.classHierarchy.push("vtkCutter");const r={...e};e.getMTime=()=>{let e=r.getMTime();return t.cutFunction?(e=Math.max(e,t.cutFunction.getMTime()),e):e},e.requestData=(e,r)=>{const n=e[0];if(!n)return void h_("Invalid or missing input");if(!t.cutFunction)return void h_("Missing cut function");const o=r[0]?.initialize()||mc.newInstance();(function(e,r){const n=e.getPoints(),o=n.getData(),i=e.getPointData(),a=n.getNumberOfPoints(),s=[],l=[],u=[],c={},d=i.getNumberOfArrays();for(let e=0;e0;let n=!0;for(let t=1;t0!==e){n=!1;break}if(n)continue;const a=[];for(let e=0;e0;if(y[n]>0===s)continue;let l=e,u=n,c=y[u]-y[l];c<=0&&(l=n,u=e,c*=-1);let p=0;0!==c&&(p=(t.cutValue-y[l])/c);const f=r.cell[l],h=r.cell[u];m[0]=o[3*f],m[1]=o[3*f+1],m[2]=o[3*f+2],g[0]=o[3*h],g[1]=o[3*h+1],g[2]=o[3*h+2];const v=[m[0]+p*(g[0]-m[0]),m[1]+p*(g[1]-m[1]),m[2]+p*(g[2]-m[2])],b={};for(let e=0;e{c[e].push(...t.intersectedArrays[e])}),a[e].newPointID=s.length/3-1,h.push(a[e]))}const p=a.length;2===p?l.push(p,a[0].newPointID,a[1].newPointID):p>2&&(u.push(p),a.forEach(e=>{u.push(e.newPointID)}))}r.getPoints().setData(it(n.getDataType(),s),3);const v=r.getPointData();for(let e=0;e2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,g_,r),mt(e,t),At(e,t,1,1),_t(e,t,["cutFunction","cutValue"]),m_(e,t)}var v_={newInstance:Pt(y_,"vtkCutter"),extend:y_};const b_={numberOfIterations:20,passBand:.1,featureAngle:45,edgeAngle:15,featureEdgeSmoothing:0,boundarySmoothing:1,nonManifoldSmoothing:0,generateErrorScalars:0,generateErrorVectors:0,normalizeCoordinates:0};function x_(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,b_,r),zt.obj(e,t),zt.algo(e,t,1,1),zt.setGet(e,t,["numberOfIterations","passBand","featureAngle","edgeAngle","featureEdgeSmoothing","boundarySmoothing","nonManifoldSmoothing","generateErrorScalars","generateErrorVectors","normalizeCoordinates"]),function(e,t){t.classHierarchy.push("vtkWindowedSincPolyDataFilter"),e.vtkWindowedSincPolyDataFilterExecute=(e,r,n)=>{if(!e||t.numberOfIterations<=0)return e;const o=e.getData(),i=r.getVerts().getData(),a=r.getLines().getData(),s=r.getPolys().getData(),l=r.getStrips().getData(),u=Math.cos(Oi.radiansFromDegrees(t.featureAngle)),c=Math.cos(Oi.radiansFromDegrees(t.edgeAngle)),d=e.getNumberOfPoints(),p=new Array(d);for(let e=0;e3;for(let e=0;e0||m>0){const n=mc.newInstance();n.setPoints(r.getPoints()),n.setPolys(r.getPolys());const o=n;let i=[],a=0;const s=[],l=[];o.buildLinks();const c=o.getPolys().getData();let d=0;for(let r=0;r=2){if(!t.nonManifoldSmoothing){let e=0;for(;e=m&&(g=2)}}else{if(!(1===m&&(a=i[0])>d))continue;if(t.featureEdgeSmoothing){ec.computeNormal(e.getPoint(n[0]),e.getPoint(n[1]),e.getPoint(n[2]),s);const{cellPointIds:t}=o.getCellPoints(a);ec.computeNormal(e.getPoint(t[0]),e.getPoint(t[1]),e.getPoint(t[2]),l),Oi.dot(s,l)<=u&&(g=2)}}g&&0===p[c].type?(p[c].edges=[h],p[c].type=g):(g&&3===p[c].type||g&&2===p[c].type||!g&&0===p[c].type)&&(p[c].edges.push(h),p[c].type&&3===g&&(p[c].type=3)),g&&0===p[h].type?(p[h].edges=[c],p[h].type=g):(g&&3===p[h].type||g&&2===p[h].type||!g&&0===p[h].type)&&(p[h].edges.push(c),p[h].type&&3===g&&(p[h].type=3))}}}for(let r=0;r=0&&Oi.normalize(a)>=0&&Oi.dot(i,a)1&&(A[t.numberOfIterations-2]=2*(t.numberOfIterations-1)*w[t.numberOfIterations-1]);for(let e=t.numberOfIterations-3;e>=0;--e)A[e]=A[e+2]+2*(e+1)*w[e+1];D=0,P=0,D+=w[0],P+=A[0];for(let e=1;e<=t.numberOfIterations;++e)1===e?(D+=w[e]*(1-.5*S),P+=A[e]*(1-.5*S)):(D+=w[e]*Math.cos(e*Math.acos(1-.5*S)),P+=A[e]*Math.cos(e*Math.acos(1-.5*S)));t.numberOfIterations>1?Math.abs(D-1)>=.001?O-=(D-1)/P:I=!0:(I=!0,O=0)}Math.abs(D-1)>=.001&&console.log("An optimal offset for the smoothing filter could not be found. Unpredictable smoothing/shrinkage may result.");const N=[0,0,0],M=[0,0,0],R=[0,0,0],F=[0,0,0],B=[0,0,0],L=[0,0,0];for(let e=0;e0){b[g].getPoint(e,N),R[0]=0,R[1]=0,R[2]=0;for(let t=0;t0){b[g].getPoint(e,k),b[y].getPoint(e,U),R[0]=0,R[1]=0,R[2]=0;for(let t=0;t{if(!e.getNumberOfInputPorts())return;const n=t[0];if(!n)return;const o=r[0]?.initialize()||mc.newInstance(),i=e.vtkWindowedSincPolyDataFilterExecute(n.getPoints(),n,o);o.setPointData(n.getPointData()),o.setCellData(n.getCellData()),o.setFieldData(n.getFieldData()),o.setPoints(i),o.setVerts(n.getVerts()),o.setLines(n.getLines()),o.setPolys(n.getPolys()),o.setStrips(n.getStrips()),r[0]=o}}(e,t)}var __={newInstance:zt.newInstance(x_,"vtkWindowedSincPolyDataFilter"),extend:x_};const{vtkErrorMacro:S_}=zt,C_=[0,2,4,1,2,4,0,3,4,1,3,4,0,2,5,1,2,5,0,3,5,1,3,5],T_=[2,0,1,2,2,3,2,4,5,2,6,7,2,0,2,2,1,3,2,4,6,2,5,7,2,0,4,2,1,5,2,2,6,2,3,7],w_={};function A_(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,w_,r),zt.obj(e,t),zt.algo(e,t,1,1),function(e,t){t.classHierarchy.push("vtkOutlineFilter"),e.requestData=(e,t)=>{const r=e[0];if(!r)return void S_("Invalid or missing input");const n=r.getBounds(),o=t[0]?.initialize()||mc.newInstance();o.getPoints().setData(Float32Array.from(C_.map(e=>n[e])),3),o.getLines().setData(Uint16Array.from(T_)),t[0]=o}}(e,t)}var E_={newInstance:zt.newInstance(A_,"vtkOutlineFilter"),extend:A_,BOUNDS_MAP:C_,LINE_ARRAY:T_};const D_={height:1,radius:.5,resolution:6,center:[0,0,0],direction:[1,0,0],capping:!0,pointType:"Float64Array"};function P_(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,D_,r),zt.obj(e,t),zt.setGet(e,t,["height","radius","resolution","capping"]),zt.setGetArray(e,t,["center","direction"],3),zt.algo(e,t,0,1),function(e,t){t.classHierarchy.push("vtkConeSource"),e.requestData=(e,r)=>{const n=2*Math.PI/t.resolution,o=-t.height/2,i=t.resolution+1,a=4*t.resolution+1+t.resolution;let s=0;const l=zt.newTypedArray(t.pointType,3*i);let u=0;const c=new Uint32Array(a);l[0]=t.height/2,l[1]=0,l[2]=0,t.capping&&(c[u++]=t.resolution);for(let e=0;et.resolution?1:e+2;ov().translate(...t.center).rotateFromDirections([1,0,0],t.direction).apply(l);const d=r[0]?.initialize()||mc.newInstance();d.getPoints().setData(l,3),d.getPolys().setData(c,1),r[0]=d}}(e,t)}var I_={newInstance:zt.newInstance(P_,"vtkConeSource"),extend:P_};const O_={radius:.5,latLongTessellation:!1,thetaResolution:8,startTheta:0,endTheta:360,phiResolution:8,startPhi:0,endPhi:180,center:[0,0,0],pointType:"Float64Array"};function N_(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,O_,r),zt.obj(e,t),zt.setGet(e,t,["radius","latLongTessellation","thetaResolution","startTheta","endTheta","phiResolution","startPhi","endPhi"]),zt.setGetArray(e,t,["center"],3),zt.algo(e,t,0,1),function(e,t){t.classHierarchy.push("vtkSphereSource"),e.requestData=(e,r)=>{let n=r[0];const o=n?n.getPoints().getDataType():t.pointType;n=n?.initialize()||mc.newInstance();let i=0,{thetaResolution:a}=t,s=t.startThetat.startTheta?t.endTheta:t.startTheta;l*=Math.PI/180;let u=t.startPhit.startPhi?t.endPhi:t.startPhi;c*=Math.PI/180,Math.abs(s-l)<2*Math.PI&&++a;const d=(l-s)/t.thetaResolution,p=t.startPhi<=0?1:0,f=t.phiResolution+(t.endPhi>=180?-1:0),h=t.phiResolution*a+2,m=2*t.phiResolution*t.thetaResolution;let g=0,y=zt.newTypedArray(o,3*h),v=new Float32Array(3*h),b=0,x=new Uint32Array(5*m);t.startPhi<=0&&(y[3*g+0]=t.center[0],y[3*g+1]=t.center[1],y[3*g+2]=t.center[2]+t.radius,v[3*g+0]=0,v[3*g+1]=0,v[3*g+2]=1,g++,i++),t.endPhi>=180&&(y[3*g+0]=t.center[0],y[3*g+1]=t.center[1],y[3*g+2]=t.center[2]-t.radius,v[3*g+0]=0,v[3*g+1]=0,v[3*g+2]=-1,g++,i++);const _=t.phiResolution-i,S=(c-u)/(t.phiResolution-1);for(let e=0;e=180){const e=_-1+i;for(let t=0;t.001?Math.acos(r/i):0,s=a>.001?Math.atan2(o,n):0;t[0]=i,t[1]=a,t[2]=s}function z_(e,t){if(e[0]>=t-.1)return e[2];const r=e[1]*Math.sqrt(t*t-e[0]*e[0])/(e[0]*Math.sin(e[1]));return e[2]>-.3*Math.PI?e[2]+r:e[2]-r}function j_(e,t,r,n){const o=[],i=[];mi(t,o),mi(r,i);const a=[],s=[];G_(o,a),G_(i,s);let l=e;if(a[1]>.05&&s[1]>.05&&function(e,t){let r=e-t;for(r<0&&(r=-r);r>=2*Math.PI;)r-=2*Math.PI;return r>Math.PI&&(r=2*Math.PI-r),r}(a[2],s[2])>.33*Math.PI){let t=Math.max(a[0],s[0]);t=Math.max(88,t),e<.5?(s[0]=t,s[1]=0,s[2]=0,l*=2):(a[0]=t,a[1]=0,a[2]=0,l=2*l-1)}a[1]<.05&&s[1]>.05?a[2]=z_(s,a[0]):s[1]<.05&&a[1]>.05&&(s[2]=z_(a,s[0]));const u=[];u[0]=(1-l)*a[0]+l*s[0],u[1]=(1-l)*a[1]+l*s[1],u[2]=(1-l)*a[2]+l*s[2];const c=[];!function(e,t){const r=e[0],n=e[1],o=e[2];t[0]=r*Math.cos(n),t[1]=r*Math.sin(n)*Math.cos(o),t[2]=r*Math.sin(n)*Math.sin(o)}(u,c),gi(c,n)}const W_={clamping:!0,colorSpace:F_.RGB,hSVWrap:!0,scale:B_.LINEAR,nanColor:null,belowRangeColor:null,aboveRangeColor:null,useAboveRangeColor:!1,useBelowRangeColor:!1,allowDuplicateScalars:!1,table:null,tableSize:0,buildTime:null,nodes:null,discretize:!1,numberOfValues:256};function H_(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};Object.assign(t,W_,r),ul.extend(e,t,r),t.table=[],t.nodes=[],t.nanColor=[.5,0,0,1],t.belowRangeColor=[0,0,0,1],t.aboveRangeColor=[1,1,1,1],t.buildTime={},zt.obj(t.buildTime),zt.get(e,t,["buildTime","mappingRange"]),zt.setGet(e,t,["useAboveRangeColor","useBelowRangeColor","discretize","numberOfValues",{type:"enum",name:"colorSpace",enum:F_},{type:"enum",name:"scale",enum:B_}]),zt.setArray(e,t,["nanColor","belowRangeColor","aboveRangeColor"],4),zt.getArray(e,t,["nanColor","belowRangeColor","aboveRangeColor"]),function(e,t){t.classHierarchy.push("vtkColorTransferFunction"),e.getSize=()=>t.nodes.length,e.addRGBPoint=(t,r,n,o)=>e.addRGBPointLong(t,r,n,o,.5,0),e.addRGBPointLong=function(r,n,o,i){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:.5,s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0;if(a<0||a>1)return U_("Midpoint outside range [0.0, 1.0]"),-1;if(s<0||s>1)return U_("Sharpness outside range [0.0, 1.0]"),-1;t.allowDuplicateScalars||e.removePoint(r);const l={x:r,r:n,g:o,b:i,midpoint:a,sharpness:s};t.nodes.push(l),e.sortAndUpdateRange();let u=0;for(;ue.addHSVPointLong(t,r,n,o,.5,0),e.addHSVPointLong=function(t,r,n,o){let i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:.5,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0;const s=[];return ci([r,n,o],s),e.addRGBPoint(t,s[0],s[1],s[2],i,a)},e.setNodes=r=>{if(t.nodes!==r){const n=JSON.stringify(t.nodes);t.nodes=r;const o=JSON.stringify(t.nodes);if(e.sortAndUpdateRange()||n!==o)return e.modified(),!0}return!1},e.sortAndUpdateRange=()=>{const r=JSON.stringify(t.nodes);t.nodes.sort((e,t)=>e.x-t.x);const n=JSON.stringify(t.nodes),o=e.updateRange();return o||r===n?o:(e.modified(),!0)},e.updateRange=()=>{const r=[2];r[0]=t.mappingRange[0],r[1]=t.mappingRange[1];const n=t.nodes.length;return n?(t.mappingRange[0]=t.nodes[0].x,t.mappingRange[1]=t.nodes[n-1].x):(t.mappingRange[0]=0,t.mappingRange[1]=0),(r[0]!==t.mappingRange[0]||r[1]!==t.mappingRange[1])&&(e.modified(),!0)},e.removePoint=r=>{let n=0;for(;n=t.nodes.length)return-1;let i=!1;return t.nodes.splice(n,1),0!==n&&n!==t.nodes.length||(i=e.updateRange()),i||e.modified(),o},e.movePoint=(r,n)=>{if(r!==n){e.removePoint(n);for(let o=0;o{t.nodes=[],e.sortAndUpdateRange()},e.addRGBSegment=(r,n,o,i,a,s,l,u)=>{e.sortAndUpdateRange();for(let e=0;e=r&&t.nodes[e].x<=a?t.nodes.splice(e,1):e++;e.addRGBPointLong(r,n,o,i,.5,0),e.addRGBPointLong(a,s,l,u,.5,0),e.modified()},e.addHSVSegment=(t,r,n,o,i,a,s,l)=>{const u=[a,s,l],c=[],d=[];ci([r,n,o],c),ci(u,d),e.addRGBSegment(t,c[0],c[1],c[2],i,d[0],d[1],d[2])},e.mapValue=t=>{const r=[];return e.getColor(t,r),[Math.floor(255*r[0]+.5),Math.floor(255*r[1]+.5),Math.floor(255*r[2]+.5),255]},e.getColor=(r,n)=>{if(t.indexedLookup){const t=e.getSize(),o=e.getAnnotatedValueIndexInternal(r);if(o<0||0===t){const t=e.getNanColorByReference();n[0]=t[0],n[1]=t[1],n[2]=t[2]}else{const r=[];e.getNodeValue(o%t,r),n[0]=r[1],n[1]=r[2],n[2]=r[3]}return}e.getTable(r,r,1,n)},e.getRedValue=t=>{const r=[];return e.getColor(t,r),r[0]},e.getGreenValue=t=>{const r=[];return e.getColor(t,r),r[1]},e.getBlueValue=t=>{const r=[];return e.getColor(t,r),r[2]},e.logScaleEnabled=()=>t.scale===B_.LOG10,e.usingLogScale=()=>e.logScaleEnabled()&&t.mappingRange[0]>0,e.getTable=(r,n,o,i)=>{const a=e.usingLogScale(),s=a?Math.log10(Number(r)):Number(r),l=a?Math.log10(Number(n)):Number(n);if(Ai(s)||Ai(l)){for(let e=0;e1?s+r/(o-1)*(l-s):.5*(s+l),t.discretize){const e=S;if(h>=e[0]&&h<=e[1]){const r=t.numberOfValues,n=e[1]-e[0];if(r<=1)h=e[0]+n/2;else{const t=(h-e[0])/n,o=xo(r*t);h=e[0]+o/(r-1)*n}}}for(;ut.nodes[u].x;)u++,u.99999&&(b=.99999));if(h>S[1])i[n]=0,i[n+1]=0,i[n+2]=0,t.clamping&&(e.getUseAboveRangeColor()?(i[n]=t.aboveRangeColor[0],i[n+1]=t.aboveRangeColor[1],i[n+2]=t.aboveRangeColor[2]):(i[n]=d,i[n+1]=p,i[n+2]=f));else if(h0&&(i[n]=t.nodes[0].r,i[n+1]=t.nodes[0].g,i[n+2]=t.nodes[0].b));else if(0===u&&(Math.abs(h-s)<1e-6||t.discretize))c>0?(i[n]=t.nodes[0].r,i[n+1]=t.nodes[0].g,i[n+2]=t.nodes[0].b):(i[n]=0,i[n+1]=0,i[n+2]=0);else{let e=0;if(e=(h-m)/(g-m),e=e.99){if(e<.5){i[n]=y[0],i[n+1]=y[1],i[n+2]=y[2];continue}i[n]=v[0],i[n+1]=v[1],i[n+2]=v[2];continue}if(x<.01){if(t.colorSpace===F_.RGB)i[n]=(1-e)*y[0]+e*v[0],i[n+1]=(1-e)*y[1]+e*v[1],i[n+2]=(1-e)*y[2]+e*v[2];else if(t.colorSpace===F_.HSV){const r=[],o=[];ui(y,r),ui(v,o),t.hSVWrap&&(r[0]-o[0]>.5||o[0]-r[0]>.5)&&(r[0]>o[0]?r[0]-=1:o[0]-=1);const a=[];a[0]=(1-e)*r[0]+e*o[0],a[0]<0&&(a[0]+=1),a[1]=(1-e)*r[1]+e*o[1],a[2]=(1-e)*r[2]+e*o[2],ci(a,_),i[n]=_[0],i[n+1]=_[1],i[n+2]=_[2]}else if(t.colorSpace===F_.LAB){const t=[],r=[];mi(y,t),mi(v,r);const o=[];o[0]=(1-e)*t[0]+e*r[0],o[1]=(1-e)*t[1]+e*r[1],o[2]=(1-e)*t[2]+e*r[2],gi(o,_),i[n]=_[0],i[n+1]=_[1],i[n+2]=_[2]}else t.colorSpace===F_.DIVERGING?(j_(e,y,v,_),i[n]=_[0],i[n+1]=_[1],i[n+2]=_[2]):U_("ColorSpace set to invalid value.",t.colorSpace);continue}e<.5?e=.5*(2*e)**(1+10*x):e>.5&&(e=1-.5*(2*(1-e))**(1+10*x));const r=e*e,o=r*e,a=2*o-3*r+1,s=-2*o+3*r,l=o-2*r+e,u=o-r;let c,d;if(t.colorSpace===F_.RGB)for(let e=0;e<3;e++)c=v[e]-y[e],d=(1-x)*c,i[n+e]=a*y[e]+s*v[e]+l*d+u*d;else if(t.colorSpace===F_.HSV){const e=[],r=[];ui(y,e),ui(v,r),t.hSVWrap&&(e[0]-r[0]>.5||r[0]-e[0]>.5)&&(e[0]>r[0]?e[0]-=1:r[0]-=1);const o=[];for(let t=0;t<3;t++)c=r[t]-e[t],d=(1-x)*c,o[t]=a*e[t]+s*r[t]+l*d+u*d,0===t&&o[t]<0&&(o[t]+=1);ci(o,_),i[n]=_[0],i[n+1]=_[1],i[n+2]=_[2]}else if(t.colorSpace===F_.LAB){const e=[],t=[];mi(y,e),mi(v,t);const r=[];for(let n=0;n<3;n++)c=t[n]-e[n],d=(1-x)*c,r[n]=a*e[n]+s*t[n]+l*d+u*d;gi(r,_),i[n]=_[0],i[n+1]=_[1],i[n+2]=_[2]}else t.colorSpace===F_.DIVERGING?(j_(e,y,v,_),i[n]=_[0],i[n+1]=_[1],i[n+2]=_[2]):U_("ColorSpace set to invalid value.");for(let e=0;e<3;e++)i[n+e]=i[n+e]<0?0:i[n+e],i[n+e]=i[n+e]>1?1:i[n+e]}}},e.getUint8Table=function(r,n,o){let i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(e.getMTime()<=t.buildTime&&t.tableSize===o&&t.tableWithAlpha!==i)return t.table;if(0===t.nodes.length)return U_("Attempting to lookup a value with no points in the function"),t.table;const a=i?4:3;t.tableSize===o&&t.tableWithAlpha===i||(t.table=new Uint8Array(o*a),t.tableSize=o,t.tableWithAlpha=i);const s=[];e.getTable(r,n,o,s);for(let e=0;e{e.removeAllPoints();const n=r.getNumberOfComponents();for(let e=0;e{let a=0;e.removeAllPoints(),o>1&&(a=(n-r)/(o-1));for(let e=0;ee<0||e>=t.nodes.length?(U_("Index out of range!"),-1):(r[0]=t.nodes[e].x,r[1]=t.nodes[e].r,r[2]=t.nodes[e].g,r[3]=t.nodes[e].b,r[4]=t.nodes[e].midpoint,r[5]=t.nodes[e].sharpness,1),e.setNodeValue=(r,n)=>{if(r<0||r>=t.nodes.length)return U_("Index out of range!"),-1;const o=t.nodes[r].x;return t.nodes[r].x=n[0],t.nodes[r].r=n[1],t.nodes[r].g=n[2],t.nodes[r].b=n[3],t.nodes[r].midpoint=n[4],t.nodes[r].sharpness=n[5],o!==n[0]?e.sortAndUpdateRange():e.modified(),1},e.getNumberOfAvailableColors=()=>{if(t.indexedLookup&&e.getSize())return e.getSize();if(t.tableSize)return t.tableSize;const r=t.nodes?.length??0;return Math.max(4094,r)},e.getIndexedColor=(t,r)=>{const n=e.getSize();if(n>0&&t>=0){const o=[];e.getNodeValue(t%n,o);for(let e=0;e<3;++e)r[e]=o[e+1];return void(r[3]=1)}const o=e.getNanColorByReference();r[0]=o[0],r[1]=o[1],r[2]=o[2],r[3]=1},e.fillFromDataPointer=(t,r)=>{if(!(t<=0)&&r){e.removeAllPoints();for(let n=0;n{const o=[r,n],i=[r,n],a=e.getRange(),s=e.logScaleEnabled();if(a[1]===o[1]&&a[0]===o[0])return;if(o[1]===o[0])return void U_("attempt to set zero width color range");s&&(o[0]<=0?console.warn("attempt to set log scale color range with non-positive minimum"):(i[0]=Math.log10(o[0]),i[1]=Math.log10(o[1])));const l=(i[1]-i[0])/(a[1]-a[0]),u=i[0]-a[0]*l;for(let e=0;e{const n=e.getRange(),o=[];n[0]r[1]?(e.getColor(r[1],o),e.addRGBPoint(r[1],o[0],o[1],o[2])):(e.getColor(n[1],o),e.addRGBPoint(r[1],o[0],o[1],o[2])),e.sortAndUpdateRange();for(let e=0;e=r[0]&&t.nodes[e].x<=r[1]?t.nodes.splice(e,1):++e;return 1},e.estimateMinNumberOfSamples=(t,r)=>{const n=e.findMinimumXDistance();return Math.ceil((r-t)/n)},e.findMinimumXDistance=()=>{if(t.nodes.length<2)return-1;let e=Number.MAX_VALUE;for(let r=0;r{0!==e.getSize()?t.indexedLookup?e.mapDataIndexed(r,n,o,i):e.mapData(r,n,o,i):k_("Transfer Function Has No Points!")},e.mapData=(t,r,n,o)=>{if(0===e.getSize())return void V_("Transfer Function Has No Points!");const i=Math.floor(255*e.getAlpha()+.5),a=t.getNumberOfTuples(),s=t.getNumberOfComponents(),l=r.getData(),u=t.getData(),c=[];if(n===L_.RGBA)for(let t=0;t{const n=JSON.stringify(t.colorSpace);r.ColorSpace&&(t.colorSpace=F_[r.ColorSpace.toUpperCase()],void 0===t.colorSpace&&(U_(`ColorSpace ${r.ColorSpace} not supported, using RGB instead`),t.colorSpace=F_.RGB));let o=n!==JSON.stringify(t.colorSpace);const i=o||JSON.stringify(t.nanColor);if(r.NanColor)for(t.nanColor=[].concat(r.NanColor);t.nanColor.length<4;)t.nanColor.push(1);o=o||i!==JSON.stringify(t.nanColor);const a=o||JSON.stringify(t.nodes);if(r.RGBPoints){const e=r.RGBPoints.length;t.nodes=[];const n=.5,o=0;for(let i=0;ie.RGBPoints).filter(e=>"CIELAB"!==e.ColorSpace).forEach(e=>{X_[e.Name]=e});const $_=Object.keys(X_);$_.sort();var q_={addPreset:function(e){e.RGBPoints&&"CIELAB"!==e.ColorSpace&&(X_[e.Name]||($_.push(e.Name),$_.sort()),X_[e.Name]=e)},removePresetByName:function(e){const t=$_.indexOf(e);t>-1&&$_.splice(t,1),delete X_[e]},getPresetByName:function(e){return X_[e]},rgbPresetNames:$_};e=r.hmd(e),console.log("[VTK Bundle] GLTFImporter included in bundle");var Y_={Rendering:{Core:{vtkActor:ss,vtkMapper:Gl,vtkTexture:vc,vtkProperty:os,vtkAnnotatedCubeActor:vv,vtkCamera:Lh,vtkRenderWindow:nm,vtkRenderWindowInteractor:xm,vtkRenderer:Jh,vtkColorTransferFunction:K_},Misc:{vtkFullScreenRenderWindow:Zy},OpenGL:{vtkRenderWindow:Hg}},Interaction:{Style:{vtkInteractorStyleTrackballCamera:Fm},Widgets:{vtkOrientationMarkerWidget:Tv}},IO:{Geometry:{vtkSTLReader:Hv,vtkPLYReader:ob,vtkGLTFImporter:f_},Misc:{vtkOBJReader:pb},XML:{vtkXMLPolyDataReader:gx}},Filters:{Core:{vtkPolyDataNormals:vx,vtkCutter:v_},General:{vtkWindowedSincPolyDataFilter:__,vtkOutlineFilter:E_},Sources:{vtkConeSource:I_,vtkSphereSource:M_,vtkCubeSource:uv}},Common:{Core:{vtkDataArray:_s},DataModel:{vtkPlane:ea}},_gltfAvailable:!0};K_.vtkColorMaps=q_,e.exports&&(e.exports=Y_),"undefined"!=typeof window&&(window.vtk=Y_),void 0!==r.g&&(r.g.vtk=Y_);const J_=Y_},41(e,t,r){"use strict";var n=r(655),o=r(68),i=r(675),a=r(795);e.exports=function(e,t,r){if(!e||"object"!=typeof e&&"function"!=typeof e)throw new i("`obj` must be an object or a function`");if("string"!=typeof t&&"symbol"!=typeof t)throw new i("`property` must be a string or a symbol`");if(arguments.length>3&&"boolean"!=typeof arguments[3]&&null!==arguments[3])throw new i("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&"boolean"!=typeof arguments[4]&&null!==arguments[4])throw new i("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&"boolean"!=typeof arguments[5]&&null!==arguments[5])throw new i("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&"boolean"!=typeof arguments[6])throw new i("`loose`, if provided, must be a boolean");var s=arguments.length>3?arguments[3]:null,l=arguments.length>4?arguments[4]:null,u=arguments.length>5?arguments[5]:null,c=arguments.length>6&&arguments[6],d=!!a&&a(e,t);if(n)n(e,t,{configurable:null===u&&d?d.configurable:!u,enumerable:null===s&&d?d.enumerable:!s,value:r,writable:null===l&&d?d.writable:!l});else{if(!c&&(s||l||u))throw new o("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");e[t]=r}}},452(e,t,r){"use strict";var n=r(189),o="function"==typeof Symbol&&"symbol"==typeof Symbol("foo"),i=Object.prototype.toString,a=Array.prototype.concat,s=r(41),l=r(592)(),u=function(e,t,r,n){if(t in e)if(!0===n){if(e[t]===r)return}else if("function"!=typeof(o=n)||"[object Function]"!==i.call(o)||!n())return;var o;l?s(e,t,r,!0):s(e,t,r)},c=function(e,t){var r=arguments.length>2?arguments[2]:{},i=n(t);o&&(i=a.call(i,Object.getOwnPropertySymbols(t)));for(var s=0;s0&&!o.call(e,0))for(var m=0;m0)for(var g=0;g=0&&"[object Function]"===t.call(e.callee)),n}},391(e,t,r){var n=r(180),o=r(181),i=r(31),a=r(67),s=r(833),l=r(717),u=r(801);u.alea=n,u.xor128=o,u.xorwow=i,u.xorshift7=a,u.xor4096=s,u.tychei=l,e.exports=u},180(e,t,r){var n;!function(e,o){function i(e){var t,r=this,n=(t=4022871197,function(e){e=String(e);for(var r=0;r>>0,t=(n*=t)>>>0,t+=4294967296*(n-=t)}return 2.3283064365386963e-10*(t>>>0)});r.next=function(){var e=2091639*r.s0+2.3283064365386963e-10*r.c;return r.s0=r.s1,r.s1=r.s2,r.s2=e-(r.c=0|e)},r.c=1,r.s0=n(" "),r.s1=n(" "),r.s2=n(" "),r.s0-=n(e),r.s0<0&&(r.s0+=1),r.s1-=n(e),r.s1<0&&(r.s1+=1),r.s2-=n(e),r.s2<0&&(r.s2+=1),n=null}function a(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function s(e,t){var r=new i(e),n=t&&t.state,o=r.next;return o.int32=function(){return 4294967296*r.next()|0},o.double=function(){return o()+11102230246251565e-32*(2097152*o()|0)},o.quick=o,n&&("object"==typeof n&&a(n,r),o.state=function(){return a(r,{})}),o}o&&o.exports?o.exports=s:r.amdD&&r.amdO?void 0===(n=function(){return s}.call(t,r,t,o))||(o.exports=n):this.alea=s}(0,e=r.nmd(e),r.amdD)},717(e,t,r){var n;!function(e,o){function i(e){var t=this,r="";t.next=function(){var e=t.b,r=t.c,n=t.d,o=t.a;return e=e<<25^e>>>7^r,r=r-n|0,n=n<<24^n>>>8^o,o=o-e|0,t.b=e=e<<20^e>>>12^r,t.c=r=r-n|0,t.d=n<<16^r>>>16^o,t.a=o-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):r+=e;for(var n=0;n>>0)/4294967296};return o.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=r.next,o.quick=o,n&&("object"==typeof n&&a(n,r),o.state=function(){return a(r,{})}),o}o&&o.exports?o.exports=s:r.amdD&&r.amdO?void 0===(n=function(){return s}.call(t,r,t,o))||(o.exports=n):this.tychei=s}(0,e=r.nmd(e),r.amdD)},181(e,t,r){var n;!function(e,o){function i(e){var t=this,r="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:r+=e;for(var n=0;n>>0)/4294967296};return o.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=r.next,o.quick=o,n&&("object"==typeof n&&a(n,r),o.state=function(){return a(r,{})}),o}o&&o.exports?o.exports=s:r.amdD&&r.amdO?void 0===(n=function(){return s}.call(t,r,t,o))||(o.exports=n):this.xor128=s}(0,e=r.nmd(e),r.amdD)},833(e,t,r){var n;!function(e,o){function i(e){var t=this;t.next=function(){var e,r,n=t.w,o=t.X,i=t.i;return t.w=n=n+1640531527|0,r=o[i+34&127],e=o[i=i+1&127],r^=r<<13,e^=e<<17,r^=r>>>15,e^=e>>>12,r=o[i]=r^e,t.i=i,r+(n^n>>>16)|0},function(e,t){var r,n,o,i,a,s=[],l=128;for(t===(0|t)?(n=t,t=null):(t+="\0",n=0,l=Math.max(l,t.length)),o=0,i=-32;i>>15,n^=n<<4,n^=n>>>13,i>=0&&(a=a+1640531527|0,o=0==(r=s[127&i]^=n+a)?o+1:0);for(o>=128&&(s[127&(t&&t.length||0)]=-1),o=127,i=512;i>0;--i)n=s[o+34&127],r=s[o=o+1&127],n^=n<<13,r^=r<<17,n^=n>>>15,r^=r>>>12,s[o]=n^r;e.w=a,e.X=s,e.i=o}(t,e)}function a(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function s(e,t){null==e&&(e=+new Date);var r=new i(e),n=t&&t.state,o=function(){return(r.next()>>>0)/4294967296};return o.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=r.next,o.quick=o,n&&(n.X&&a(n,r),o.state=function(){return a(r,{})}),o}o&&o.exports?o.exports=s:r.amdD&&r.amdO?void 0===(n=function(){return s}.call(t,r,t,o))||(o.exports=n):this.xor4096=s}(0,e=r.nmd(e),r.amdD)},67(e,t,r){var n;!function(e,o){function i(e){var t=this;t.next=function(){var e,r,n=t.x,o=t.i;return e=n[o],r=(e^=e>>>7)^e<<24,r^=(e=n[o+1&7])^e>>>10,r^=(e=n[o+3&7])^e>>>3,r^=(e=n[o+4&7])^e<<7,e=n[o+7&7],r^=(e^=e<<13)^e<<9,n[o]=r,t.i=o+1&7,r},function(e,t){var r,n=[];if(t===(0|t))n[0]=t;else for(t=""+t,r=0;r0;--r)e.next()}(t,e)}function a(e,t){return t.x=e.x.slice(),t.i=e.i,t}function s(e,t){null==e&&(e=+new Date);var r=new i(e),n=t&&t.state,o=function(){return(r.next()>>>0)/4294967296};return o.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=r.next,o.quick=o,n&&(n.x&&a(n,r),o.state=function(){return a(r,{})}),o}o&&o.exports?o.exports=s:r.amdD&&r.amdO?void 0===(n=function(){return s}.call(t,r,t,o))||(o.exports=n):this.xorshift7=s}(0,e=r.nmd(e),r.amdD)},31(e,t,r){var n;!function(e,o){function i(e){var t=this,r="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:r+=e;for(var n=0;n>>4),t.next()}function a(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function s(e,t){var r=new i(e),n=t&&t.state,o=function(){return(r.next()>>>0)/4294967296};return o.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=r.next,o.quick=o,n&&("object"==typeof n&&a(n,r),o.state=function(){return a(r,{})}),o}o&&o.exports?o.exports=s:r.amdD&&r.amdO?void 0===(n=function(){return s}.call(t,r,t,o))||(o.exports=n):this.xorwow=s}(0,e=r.nmd(e),r.amdD)},801(e,t,r){var n;!function(o,i,a){var s,l=256,u=a.pow(l,6),c=a.pow(2,52),d=2*c,p=255;function f(e,t,r){var n=[],p=y(g((t=1==t?{entropy:!0}:t||{}).entropy?[e,v(i)]:null==e?function(){try{var e;return s&&(e=s.randomBytes)?e=e(l):(e=new Uint8Array(l),(o.crypto||o.msCrypto).getRandomValues(e)),v(e)}catch(e){var t=o.navigator,r=t&&t.plugins;return[+new Date,o,r,o.screen,v(i)]}}():e,3),n),f=new h(n),b=function(){for(var e=f.g(6),t=u,r=0;e=d;)e/=2,t/=2,r>>>=1;return(e+r)/t};return b.int32=function(){return 0|f.g(4)},b.quick=function(){return f.g(4)/4294967296},b.double=b,y(v(f.S),i),(t.pass||r||function(e,t,r,n){return n&&(n.S&&m(n,f),e.state=function(){return m(f,{})}),r?(a.random=e,t):e})(b,p,"global"in t?t.global:this==a,t.state)}function h(e){var t,r=e.length,n=this,o=0,i=n.i=n.j=0,a=n.S=[];for(r||(e=[r++]);o>>25)+n|0)&n|~r&o)+t[1]-389564586|0)<<12|i>>>20)+r|0)&r|~i&n)+t[2]+606105819|0)<<17|o>>>15)+i|0)&i|~o&r)+t[3]-1044525330|0)<<22|n>>>10)+o|0,n=((n+=((o=((o+=((i=((i+=((r=((r+=(n&o|~n&i)+t[4]-176418897|0)<<7|r>>>25)+n|0)&n|~r&o)+t[5]+1200080426|0)<<12|i>>>20)+r|0)&r|~i&n)+t[6]-1473231341|0)<<17|o>>>15)+i|0)&i|~o&r)+t[7]-45705983|0)<<22|n>>>10)+o|0,n=((n+=((o=((o+=((i=((i+=((r=((r+=(n&o|~n&i)+t[8]+1770035416|0)<<7|r>>>25)+n|0)&n|~r&o)+t[9]-1958414417|0)<<12|i>>>20)+r|0)&r|~i&n)+t[10]-42063|0)<<17|o>>>15)+i|0)&i|~o&r)+t[11]-1990404162|0)<<22|n>>>10)+o|0,n=((n+=((o=((o+=((i=((i+=((r=((r+=(n&o|~n&i)+t[12]+1804603682|0)<<7|r>>>25)+n|0)&n|~r&o)+t[13]-40341101|0)<<12|i>>>20)+r|0)&r|~i&n)+t[14]-1502002290|0)<<17|o>>>15)+i|0)&i|~o&r)+t[15]+1236535329|0)<<22|n>>>10)+o|0,n=((n+=((o=((o+=((i=((i+=((r=((r+=(n&i|o&~i)+t[1]-165796510|0)<<5|r>>>27)+n|0)&o|n&~o)+t[6]-1069501632|0)<<9|i>>>23)+r|0)&n|r&~n)+t[11]+643717713|0)<<14|o>>>18)+i|0)&r|i&~r)+t[0]-373897302|0)<<20|n>>>12)+o|0,n=((n+=((o=((o+=((i=((i+=((r=((r+=(n&i|o&~i)+t[5]-701558691|0)<<5|r>>>27)+n|0)&o|n&~o)+t[10]+38016083|0)<<9|i>>>23)+r|0)&n|r&~n)+t[15]-660478335|0)<<14|o>>>18)+i|0)&r|i&~r)+t[4]-405537848|0)<<20|n>>>12)+o|0,n=((n+=((o=((o+=((i=((i+=((r=((r+=(n&i|o&~i)+t[9]+568446438|0)<<5|r>>>27)+n|0)&o|n&~o)+t[14]-1019803690|0)<<9|i>>>23)+r|0)&n|r&~n)+t[3]-187363961|0)<<14|o>>>18)+i|0)&r|i&~r)+t[8]+1163531501|0)<<20|n>>>12)+o|0,n=((n+=((o=((o+=((i=((i+=((r=((r+=(n&i|o&~i)+t[13]-1444681467|0)<<5|r>>>27)+n|0)&o|n&~o)+t[2]-51403784|0)<<9|i>>>23)+r|0)&n|r&~n)+t[7]+1735328473|0)<<14|o>>>18)+i|0)&r|i&~r)+t[12]-1926607734|0)<<20|n>>>12)+o|0,n=((n+=((o=((o+=((i=((i+=((r=((r+=(n^o^i)+t[5]-378558|0)<<4|r>>>28)+n|0)^n^o)+t[8]-2022574463|0)<<11|i>>>21)+r|0)^r^n)+t[11]+1839030562|0)<<16|o>>>16)+i|0)^i^r)+t[14]-35309556|0)<<23|n>>>9)+o|0,n=((n+=((o=((o+=((i=((i+=((r=((r+=(n^o^i)+t[1]-1530992060|0)<<4|r>>>28)+n|0)^n^o)+t[4]+1272893353|0)<<11|i>>>21)+r|0)^r^n)+t[7]-155497632|0)<<16|o>>>16)+i|0)^i^r)+t[10]-1094730640|0)<<23|n>>>9)+o|0,n=((n+=((o=((o+=((i=((i+=((r=((r+=(n^o^i)+t[13]+681279174|0)<<4|r>>>28)+n|0)^n^o)+t[0]-358537222|0)<<11|i>>>21)+r|0)^r^n)+t[3]-722521979|0)<<16|o>>>16)+i|0)^i^r)+t[6]+76029189|0)<<23|n>>>9)+o|0,n=((n+=((o=((o+=((i=((i+=((r=((r+=(n^o^i)+t[9]-640364487|0)<<4|r>>>28)+n|0)^n^o)+t[12]-421815835|0)<<11|i>>>21)+r|0)^r^n)+t[15]+530742520|0)<<16|o>>>16)+i|0)^i^r)+t[2]-995338651|0)<<23|n>>>9)+o|0,n=((n+=((i=((i+=(n^((r=((r+=(o^(n|~i))+t[0]-198630844|0)<<6|r>>>26)+n|0)|~o))+t[7]+1126891415|0)<<10|i>>>22)+r|0)^((o=((o+=(r^(i|~n))+t[14]-1416354905|0)<<15|o>>>17)+i|0)|~r))+t[5]-57434055|0)<<21|n>>>11)+o|0,n=((n+=((i=((i+=(n^((r=((r+=(o^(n|~i))+t[12]+1700485571|0)<<6|r>>>26)+n|0)|~o))+t[3]-1894986606|0)<<10|i>>>22)+r|0)^((o=((o+=(r^(i|~n))+t[10]-1051523|0)<<15|o>>>17)+i|0)|~r))+t[1]-2054922799|0)<<21|n>>>11)+o|0,n=((n+=((i=((i+=(n^((r=((r+=(o^(n|~i))+t[8]+1873313359|0)<<6|r>>>26)+n|0)|~o))+t[15]-30611744|0)<<10|i>>>22)+r|0)^((o=((o+=(r^(i|~n))+t[6]-1560198380|0)<<15|o>>>17)+i|0)|~r))+t[13]+1309151649|0)<<21|n>>>11)+o|0,n=((n+=((i=((i+=(n^((r=((r+=(o^(n|~i))+t[4]-145523070|0)<<6|r>>>26)+n|0)|~o))+t[11]-1120210379|0)<<10|i>>>22)+r|0)^((o=((o+=(r^(i|~n))+t[2]+718787259|0)<<15|o>>>17)+i|0)|~r))+t[9]-343485551|0)<<21|n>>>11)+o|0,e[0]=r+e[0]|0,e[1]=n+e[1]|0,e[2]=o+e[2]|0,e[3]=i+e[3]|0}function r(e){var t,r=[];for(t=0;t<64;t+=4)r[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return r}function n(e){var t,r=[];for(t=0;t<64;t+=4)r[t>>2]=e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24);return r}function o(e){var n,o,i,a,s,l,u=e.length,c=[1732584193,-271733879,-1732584194,271733878];for(n=64;n<=u;n+=64)t(c,r(e.substring(n-64,n)));for(o=(e=e.substring(n-64)).length,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0;n>2]|=e.charCodeAt(n)<<(n%4<<3);if(i[n>>2]|=128<<(n%4<<3),n>55)for(t(c,i),n=0;n<16;n+=1)i[n]=0;return a=(a=8*u).toString(16).match(/(.*?)(.{0,8})$/),s=parseInt(a[2],16),l=parseInt(a[1],16)||0,i[14]=s,i[15]=l,t(c,i),c}function i(t){var r,n="";for(r=0;r<4;r+=1)n+=e[t>>8*r+4&15]+e[t>>8*r&15];return n}function a(e){var t;for(t=0;tu?new ArrayBuffer(0):(n=u-l,o=new ArrayBuffer(n),i=new Uint8Array(o),a=new Uint8Array(this,l,n),i.set(a),o)}}(),u.prototype.append=function(e){return this.appendBinary(s(e)),this},u.prototype.appendBinary=function(e){this._buff+=e,this._length+=e.length;var n,o=this._buff.length;for(n=64;n<=o;n+=64)t(this._hash,r(this._buff.substring(n-64,n)));return this._buff=this._buff.substring(n-64),this},u.prototype.end=function(e){var t,r,n=this._buff,o=n.length,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t>2]|=n.charCodeAt(t)<<(t%4<<3);return this._finish(i,o),r=a(this._hash),e&&(r=l(r)),this.reset(),r},u.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},u.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},u.prototype.setState=function(e){return this._buff=e.buff,this._length=e.length,this._hash=e.hash,this},u.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},u.prototype._finish=function(e,r){var n,o,i,a=r;if(e[a>>2]|=128<<(a%4<<3),a>55)for(t(this._hash,e),a=0;a<16;a+=1)e[a]=0;n=(n=8*this._length).toString(16).match(/(.*?)(.{0,8})$/),o=parseInt(n[2],16),i=parseInt(n[1],16)||0,e[14]=o,e[15]=i,t(this._hash,e)},u.hash=function(e,t){return u.hashBinary(s(e),t)},u.hashBinary=function(e,t){var r=a(o(e));return t?l(r):r},u.ArrayBuffer=function(){this.reset()},u.ArrayBuffer.prototype.append=function(e){var r,o,i,a,s,l=(o=this._buff.buffer,i=e,a=!0,(s=new Uint8Array(o.byteLength+i.byteLength)).set(new Uint8Array(o)),s.set(new Uint8Array(i),o.byteLength),a?s:s.buffer),u=l.length;for(this._length+=e.byteLength,r=64;r<=u;r+=64)t(this._hash,n(l.subarray(r-64,r)));return this._buff=r-64>2]|=n[t]<<(t%4<<3);return this._finish(i,o),r=a(this._hash),e&&(r=l(r)),this.reset(),r},u.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},u.ArrayBuffer.prototype.getState=function(){var e,t=u.prototype.getState.call(this);return t.buff=(e=t.buff,String.fromCharCode.apply(null,new Uint8Array(e))),t},u.ArrayBuffer.prototype.setState=function(e){return e.buff=function(e,t){var r,n=e.length,o=new ArrayBuffer(n),i=new Uint8Array(o);for(r=0;r>2]|=e[r]<<(r%4<<3);if(i[r>>2]|=128<<(r%4<<3),r>55)for(t(c,i),r=0;r<16;r+=1)i[r]=0;return a=(a=8*u).toString(16).match(/(.*?)(.{0,8})$/),s=parseInt(a[2],16),l=parseInt(a[1],16)||0,i[14]=s,i[15]=l,t(c,i),c}(new Uint8Array(e)));return r?l(o):o},u}()},570(e){e.exports=function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=184)}([function(e,t,r){"use strict";function n(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}Object.defineProperty(t,"__esModule",{value:!0}),n(r(240)),n(r(251)),n(r(175)),n(r(107)),n(r(29)),n(r(73)),n(r(106)),n(r(30)),n(r(252)),n(r(52)),n(r(97)),n(r(253)),n(r(37)),n(r(51)),n(r(173)),n(r(176)),n(r(172)),n(r(108)),n(r(254)),n(r(255)),n(r(256)),n(r(72)),n(r(177)),n(r(105)),n(r(17)),n(r(257)),n(r(12)),n(r(174))},function(e,t,r){"use strict";var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var o=r(212);t.FixedSizeSet=o.FixedSizeSet;var i=r(213);t.ObjectCache=i.ObjectCache;var a=r(214);t.CompareCache=a.CompareCache;var s=r(215);t.Lazy=s.Lazy;var l=r(216);function u(e,t,r){if(m(e))e.forEach(function(e,n){return t.call(r,n,e)});else for(var n in e)e.hasOwnProperty(n)&&t.call(r,n,e[n])}function c(e){var t,r;if(d(e))return e;if(f(e)){var o=[];try{for(var i=n(e),a=i.next();!a.done;a=i.next()){var s=a.value;o.push(c(s))}}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return o}if(p(e)){for(var l in o={},e)if(e.hasOwnProperty(l)){var u=e[l];o[l]=c(u)}return o}return e}function d(e){return!!e&&"[object Function]"===Object.prototype.toString.call(e)}function p(e){var t=typeof e;return!!e&&("function"===t||"object"===t)}function f(e){return Array.isArray(e)}function h(e){return e instanceof Set}function m(e){return e instanceof Map}function g(e){if(p(e)){var t=Object.getPrototypeOf(e),r=t.constructor;return t&&r&&"function"==typeof r&&r instanceof r&&Function.prototype.toString.call(r)===Function.prototype.toString.call(Object)}return!1}t.StringWalker=l.StringWalker,t.applyMixin=function(e,t){for(var r=[],n=2;n>6|192;else{if(o>55295&&o<56320){if(++n>=e.length)throw new Error("Incomplete surrogate pair.");var i=e.charCodeAt(n);if(i<56320||i>57343)throw new Error("Invalid surrogate character.");o=65536+((1023&o)<<10)+(1023&i),t[r++]=o>>18|240,t[r++]=o>>12&63|128}else t[r++]=o>>12|224;t[r++]=o>>6&63|128}t[r++]=63&o|128}}return t.subarray(0,r)},t.utf8Decode=function(e){for(var t="",r=0;r127)if(n>191&&n<224){if(r>=e.length)throw new Error("Incomplete 2-byte sequence.");n=(31&n)<<6|63&e[r++]}else if(n>223&&n<240){if(r+1>=e.length)throw new Error("Incomplete 3-byte sequence.");n=(15&n)<<12|(63&e[r++])<<6|63&e[r++]}else{if(!(n>239&&n<248))throw new Error("Unknown multi-byte start.");if(r+2>=e.length)throw new Error("Incomplete 4-byte sequence.");n=(7&n)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++]}if(n<=65535)t+=String.fromCharCode(n);else{if(!(n<=1114111))throw new Error("Code point exceeds UTF-16 limit.");n-=65536,t+=String.fromCharCode(n>>10|55296),t+=String.fromCharCode(1023&n|56320)}}return t}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e[e.Before=0]="Before",e[e.Equal=1]="Equal",e[e.After=2]="After"}(t.BoundaryPosition||(t.BoundaryPosition={})),function(e){e[e.None=0]="None",e[e.Capturing=1]="Capturing",e[e.AtTarget=2]="AtTarget",e[e.Bubbling=3]="Bubbling"}(t.EventPhase||(t.EventPhase={})),function(e){e[e.Element=1]="Element",e[e.Attribute=2]="Attribute",e[e.Text=3]="Text",e[e.CData=4]="CData",e[e.EntityReference=5]="EntityReference",e[e.Entity=6]="Entity",e[e.ProcessingInstruction=7]="ProcessingInstruction",e[e.Comment=8]="Comment",e[e.Document=9]="Document",e[e.DocumentType=10]="DocumentType",e[e.DocumentFragment=11]="DocumentFragment",e[e.Notation=12]="Notation"}(t.NodeType||(t.NodeType={})),function(e){e[e.Disconnected=1]="Disconnected",e[e.Preceding=2]="Preceding",e[e.Following=4]="Following",e[e.Contains=8]="Contains",e[e.ContainedBy=16]="ContainedBy",e[e.ImplementationSpecific=32]="ImplementationSpecific"}(t.Position||(t.Position={})),function(e){e[e.Accept=1]="Accept",e[e.Reject=2]="Reject",e[e.Skip=3]="Skip"}(t.FilterResult||(t.FilterResult={})),function(e){e[e.All=4294967295]="All",e[e.Element=1]="Element",e[e.Attribute=2]="Attribute",e[e.Text=4]="Text",e[e.CDataSection=8]="CDataSection",e[e.EntityReference=16]="EntityReference",e[e.Entity=32]="Entity",e[e.ProcessingInstruction=64]="ProcessingInstruction",e[e.Comment=128]="Comment",e[e.Document=256]="Document",e[e.DocumentType=512]="DocumentType",e[e.DocumentFragment=1024]="DocumentFragment",e[e.Notation=2048]="Notation"}(t.WhatToShow||(t.WhatToShow={})),function(e){e[e.StartToStart=0]="StartToStart",e[e.StartToEnd=1]="StartToEnd",e[e.EndToEnd=2]="EndToEnd",e[e.EndToStart=3]="EndToStart"}(t.HowToCompare||(t.HowToCompare={}))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(241);t.Cast=n.Cast;var o=r(150);t.Guard=o.Guard;var i=r(242);t.EmptySet=i.EmptySet},function(e,t,r){var n=r(11),o=r(55).f,i=r(21),a=r(25),s=r(80),l=r(119),u=r(123);e.exports=function(e,t){var r,c,d,p,f,h=e.target,m=e.global,g=e.stat;if(r=m?n:g?n[h]||s(h,{}):(n[h]||{}).prototype)for(c in t){if(p=t[c],d=e.noTargetGet?(f=o(r,c))&&f.value:r[c],!u(m?c:h+(g?".":"#")+c,e.forced)&&void 0!==d){if(typeof p==typeof d)continue;l(p,d)}(e.sham||d&&d.sham)&&i(p,"sham",!0),a(r,c,p,e)}}},function(e,t,r){var n=r(11),o=r(81),i=r(14),a=r(58),s=r(86),l=r(124),u=o("wks"),c=n.Symbol,d=l?c:c&&c.withoutSetter||a;e.exports=function(e){return i(u,e)||(s&&i(c,e)?u[e]=c[e]:u[e]=d("Symbol."+e)),u[e]}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(1),o=r(29),i=function(){function e(){this._features={mutationObservers:!0,customElements:!0,slots:!0,steps:!0},this._window=null,this._compareCache=new n.CompareCache,this._rangeList=new n.FixedSizeSet}return e.prototype.setFeatures=function(e){if(void 0===e&&(e=!0),n.isObject(e))for(var t in e)this._features[t]=e[t]||!1;else for(var t in this._features)this._features[t]=e},Object.defineProperty(e.prototype,"features",{get:function(){return this._features},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"window",{get:function(){return null===this._window&&(this._window=o.create_window()),this._window},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"compareCache",{get:function(){return this._compareCache},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rangeList",{get:function(){return this._rangeList},enumerable:!0,configurable:!0}),Object.defineProperty(e,"instance",{get:function(){return e._instance||(e._instance=new e),e._instance},enumerable:!0,configurable:!0}),e}();t.dom=i.instance},function(e,t,r){"use strict";var n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t};Object.defineProperty(t,"__esModule",{value:!0});var o=n(r(228));t.base64=o;var i=n(r(146));t.byte=i;var a=n(r(147));t.byteSequence=a;var s=n(r(96));t.codePoint=s;var l=n(r(232));t.json=l;var u=n(r(233));t.list=u;var c=n(r(234));t.map=c;var d=n(r(235));t.namespace=d;var p=n(r(236));t.queue=p;var f=n(r(237));t.set=f;var h=n(r(238));t.stack=h;var m=n(r(239));t.string=m},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t,r){"use strict";var n,o=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var i=function(e){function t(t,r){void 0===r&&(r="");var n=e.call(this,r)||this;return n.name=t,n}return o(t,e),t}(Error);t.DOMException=i;var a=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"DOMStringSizeError",t)||this}return o(t,e),t}(i);t.DOMStringSizeError=a;var s=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"WrongDocumentError","The object is in the wrong document. "+t)||this}return o(t,e),t}(i);t.WrongDocumentError=s;var l=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"NoDataAllowedError",t)||this}return o(t,e),t}(i);t.NoDataAllowedError=l;var u=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"NoModificationAllowedError","The object can not be modified. "+t)||this}return o(t,e),t}(i);t.NoModificationAllowedError=u;var c=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"NotSupportedError","The operation is not supported. "+t)||this}return o(t,e),t}(i);t.NotSupportedError=c;var d=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"InUseAttributeError",t)||this}return o(t,e),t}(i);t.InUseAttributeError=d;var p=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"InvalidStateError","The object is in an invalid state. "+t)||this}return o(t,e),t}(i);t.InvalidStateError=p;var f=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"InvalidModificationError","The object can not be modified in this way. "+t)||this}return o(t,e),t}(i);t.InvalidModificationError=f;var h=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"NamespaceError","The operation is not allowed by Namespaces in XML. [XMLNS] "+t)||this}return o(t,e),t}(i);t.NamespaceError=h;var m=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"InvalidAccessError","The object does not support the operation or argument. "+t)||this}return o(t,e),t}(i);t.InvalidAccessError=m;var g=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"ValidationError",t)||this}return o(t,e),t}(i);t.ValidationError=g;var y=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"TypeMismatchError",t)||this}return o(t,e),t}(i);t.TypeMismatchError=y;var v=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"SecurityError","The operation is insecure. "+t)||this}return o(t,e),t}(i);t.SecurityError=v;var b=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"NetworkError","A network error occurred. "+t)||this}return o(t,e),t}(i);t.NetworkError=b;var x=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"AbortError","The operation was aborted. "+t)||this}return o(t,e),t}(i);t.AbortError=x;var _=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"URLMismatchError","The given URL does not match another URL. "+t)||this}return o(t,e),t}(i);t.URLMismatchError=_;var S=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"QuotaExceededError","The quota has been exceeded. "+t)||this}return o(t,e),t}(i);t.QuotaExceededError=S;var C=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"TimeoutError","The operation timed out. "+t)||this}return o(t,e),t}(i);t.TimeoutError=C;var T=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"InvalidNodeTypeError","The supplied node is incorrect or has an incorrect ancestor for this operation. "+t)||this}return o(t,e),t}(i);t.InvalidNodeTypeError=T;var w=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"DataCloneError","The object can not be cloned. "+t)||this}return o(t,e),t}(i);t.DataCloneError=w;var A=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"NotImplementedError","The DOM method is not implemented by this module. "+t)||this}return o(t,e),t}(i);t.NotImplementedError=A;var E=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"HierarchyRequestError","The operation would yield an incorrect node tree. "+t)||this}return o(t,e),t}(i);t.HierarchyRequestError=E;var D=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"NotFoundError","The object can not be found here. "+t)||this}return o(t,e),t}(i);t.NotFoundError=D;var P=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"IndexSizeError","The index is not in the allowed range. "+t)||this}return o(t,e),t}(i);t.IndexSizeError=P;var I=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"SyntaxError","The string did not match the expected pattern. "+t)||this}return o(t,e),t}(i);t.SyntaxError=I;var O=function(e){function t(t){return void 0===t&&(t=""),e.call(this,"InvalidCharacterError","The string contains invalid characters. "+t)||this}return o(t,e),t}(i);t.InvalidCharacterError=O},function(e,t,r){"use strict";var n=r(53),o=["kind","resolve","construct","instanceOf","predicate","represent","defaultStyle","styleAliases"],i=["scalar","sequence","mapping"];e.exports=function(e,t){var r,a;if(t=t||{},Object.keys(t).forEach(function(t){if(-1===o.indexOf(t))throw new n('Unknown option "'+t+'" is met in definition of "'+e+'" YAML type.')}),this.tag=e,this.kind=t.kind||null,this.resolve=t.resolve||function(){return!0},this.construct=t.construct||function(e){return e},this.instanceOf=t.instanceOf||null,this.predicate=t.predicate||null,this.represent=t.represent||null,this.defaultStyle=t.defaultStyle||null,this.styleAliases=(r=t.styleAliases||null,a={},null!==r&&Object.keys(r).forEach(function(e){r[e].forEach(function(t){a[String(t)]=e})}),a),-1===i.indexOf(this.kind))throw new n('Unknown kind "'+this.kind+'" is specified for "'+e+'" YAML type.')}},function(e,t,r){(function(t){var r=function(e){return e&&e.Math==Math&&e};e.exports=r("object"==typeof globalThis&&globalThis)||r("object"==typeof window&&window)||r("object"==typeof self&&self)||r("object"==typeof t&&t)||Function("return this")()}).call(this,r(78))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.idl_defineConst=function(e,t,r){Object.defineProperty(e,t,{writable:!1,enumerable:!0,configurable:!1,value:r})}},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t){var r={}.hasOwnProperty;e.exports=function(e,t){return r.call(e,t)}},function(e,t,r){var n=r(16),o=r(115),i=r(18),a=r(56),s=Object.defineProperty;t.f=n?s:function(e,t,r){if(i(e),t=a(t,!0),i(r),o)try{return s(e,t,r)}catch(e){}if("get"in r||"set"in r)throw TypeError("Accessors not supported");return"value"in r&&(e[t]=r.value),e}},function(e,t,r){var n=r(8);e.exports=!n(function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})},function(e,t,r){"use strict";var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var o=r(3),i=r(2);function a(e,t,r){if(void 0===r&&(r=!1),r&&o.Guard.isElementNode(t)&&o.Guard.isShadowRoot(t.shadowRoot)&&t.shadowRoot._firstChild)return t.shadowRoot._firstChild;if(t._firstChild)return t._firstChild;if(t===e)return null;if(t._nextSibling)return t._nextSibling;for(var n=t._parent;n&&n!==e;){if(n._nextSibling)return n._nextSibling;n=n._parent}return null}function s(){var e;return(e={})[Symbol.iterator]=function(){return{next:function(){return{done:!0,value:null}}}},e}function l(e,t,r,n){void 0===t&&(t=!1),void 0===r&&(r=!1);for(var o=t?e:a(e,e,r);o&&n&&!n(o);)o=a(e,o,r);return o}function u(e,t,r,n,o){void 0===r&&(r=!1),void 0===n&&(n=!1);for(var i=a(e,t,n);i&&o&&!o(i);)i=a(e,i,n);return i}function c(e,t,r,n){var o;return void 0===t&&(t=!1),void 0===r&&(r=!1),t||0!==e._children.size?((o={})[Symbol.iterator]=function(){var o=t?e:a(e,e,r);return{next:function(){for(;o&&n&&!n(o);)o=a(e,o,r);if(null===o)return{done:!0,value:null};var t={done:!1,value:o};return o=a(e,o,r),t}}},o):s()}function d(e,t,r){void 0===t&&(t=!1);for(var n=t?e:e._parent;n&&r&&!r(n);)n=n._parent;return n}function p(e,t,r,n){void 0===r&&(r=!1);for(var o=t._parent;o&&n&&!n(o);)o=o._parent;return o}function f(e){return o.Guard.isDocumentTypeNode(e)?0:o.Guard.isCharacterDataNode(e)?e._data.length:e._children.size}function h(e,t){if(void 0===t&&(t=!1),t){var r=h(e,!1);return o.Guard.isShadowRoot(r)?h(r._host,!0):r}return e._parent?h(e._parent):e}function m(e,t,r,n){void 0===r&&(r=!1),void 0===n&&(n=!1);for(var i=r?e:n&&o.Guard.isShadowRoot(e)?e._host:e._parent;null!==i;){if(i===t)return!0;i=n&&o.Guard.isShadowRoot(i)?i._host:i._parent}return!1}function g(e){for(var t=h(e),r=0,n=l(t);null!==n;){if(r++,n===e)return r;n=u(t,n)}return-1}t.tree_getFirstDescendantNode=l,t.tree_getNextDescendantNode=u,t.tree_getDescendantNodes=c,t.tree_getDescendantElements=function(e,t,r,n){var i;return void 0===t&&(t=!1),void 0===r&&(r=!1),t||0!==e._children.size?((i={})[Symbol.iterator]=function(){var i=c(e,t,r,function(e){return o.Guard.isElementNode(e)})[Symbol.iterator](),a=i.next().value;return{next:function(){for(;a&&n&&!n(a);)a=i.next().value;if(null===a)return{done:!0,value:null};var e={done:!1,value:a};return a=i.next().value,e}}},i):s()},t.tree_getSiblingNodes=function(e,t,r){var n;return void 0===t&&(t=!1),e._parent&&0!==e._parent._children.size?((n={})[Symbol.iterator]=function(){var n=e._parent?e._parent._firstChild:null;return{next:function(){for(;n&&(r&&!r(n)||!t&&n===e);)n=n._nextSibling;if(null===n)return{done:!0,value:null};var o={done:!1,value:n};return n=n._nextSibling,o}}},n):s()},t.tree_getFirstAncestorNode=d,t.tree_getNextAncestorNode=p,t.tree_getAncestorNodes=function(e,t,r){var n;return void 0===t&&(t=!1),t||e._parent?((n={})[Symbol.iterator]=function(){var n=d(e,t,r);return{next:function(){if(null===n)return{done:!0,value:null};var e={done:!1,value:n};return n=p(0,n,t,r),e}}},n):s()},t.tree_getCommonAncestor=function(e,t){if(e===t)return e._parent;for(var r=[],n=[],o=d(e,!0);null!==o;)r.push(o),o=p(0,o,!0);for(var i=d(t,!0);null!==i;)n.push(i),i=p(0,i,!0);for(var a=r.length,s=n.length,l=null,u=Math.min(a,s);u>0;u--){var c=r[--a];if(c!==n[--s])break;l=c}return l},t.tree_getFollowingNode=function(e,t){if(t._firstChild)return t._firstChild;if(t._nextSibling)return t._nextSibling;for(;;){var r=t._parent;if(null===r||r===e)return null;if(r._nextSibling)return r._nextSibling;t=r}},t.tree_getPrecedingNode=function(e,t){return t===e?null:t._previousSibling?(t=t._previousSibling)._lastChild?t._lastChild:t:t._parent},t.tree_isConstrained=function e(t){var r,o,a,s,l,u;switch(t._nodeType){case i.NodeType.Document:var c=!1,d=!1;try{for(var p=n(t._children),f=p.next();!f.done;f=p.next())switch(f.value._nodeType){case i.NodeType.ProcessingInstruction:case i.NodeType.Comment:break;case i.NodeType.DocumentType:if(c||d)return!1;c=!0;break;case i.NodeType.Element:if(d)return!1;d=!0;break;default:return!1}}catch(e){r={error:e}}finally{try{f&&!f.done&&(o=p.return)&&o.call(p)}finally{if(r)throw r.error}}break;case i.NodeType.DocumentFragment:case i.NodeType.Element:try{for(var h=n(t._children),m=h.next();!m.done;m=h.next())switch(m.value._nodeType){case i.NodeType.Element:case i.NodeType.Text:case i.NodeType.ProcessingInstruction:case i.NodeType.CData:case i.NodeType.Comment:break;default:return!1}}catch(e){a={error:e}}finally{try{m&&!m.done&&(s=h.return)&&s.call(h)}finally{if(a)throw a.error}}break;case i.NodeType.DocumentType:case i.NodeType.Text:case i.NodeType.ProcessingInstruction:case i.NodeType.CData:case i.NodeType.Comment:return!t.hasChildNodes()}try{for(var g=n(t._children),y=g.next();!y.done;y=g.next())if(!e(y.value))return!1}catch(e){l={error:e}}finally{try{y&&!y.done&&(u=g.return)&&u.call(g)}finally{if(l)throw l.error}}return!0},t.tree_nodeLength=f,t.tree_isEmpty=function(e){return 0===f(e)},t.tree_rootNode=h,t.tree_isDescendantOf=function(e,t,r,n){void 0===r&&(r=!1),void 0===n&&(n=!1);for(var o=l(e,r,n);null!==o;){if(o===t)return!0;o=u(e,o,r,n)}return!1},t.tree_isAncestorOf=m,t.tree_isHostIncludingAncestorOf=function e(t,r,n){if(void 0===n&&(n=!1),m(t,r,n))return!0;var i=h(t);return!(!o.Guard.isDocumentFragmentNode(i)||null===i._host||!e(i._host,r,n))},t.tree_isSiblingOf=function(e,t,r){return void 0===r&&(r=!1),e!==t?null!==e._parent&&e._parent===t._parent:!!r},t.tree_isPreceding=function(e,t){var r=g(e),n=g(t);return-1!==r&&-1!==n&&h(e)===h(t)&&nr},t.tree_isParentOf=function(e,t){return e._parent===t},t.tree_isChildOf=function(e,t){return t._parent===e},t.tree_previousSibling=function(e){return e._previousSibling},t.tree_nextSibling=function(e){return e._nextSibling},t.tree_firstChild=function(e){return e._firstChild},t.tree_lastChild=function(e){return e._lastChild},t.tree_treePosition=g,t.tree_index=function(e){for(var t=0;null!==e._previousSibling;)t++,e=e._previousSibling;return t},t.tree_retarget=function(e,t){for(;;){if(!e||!o.Guard.isNode(e))return e;var r=h(e);if(!o.Guard.isShadowRoot(r))return e;if(t&&o.Guard.isNode(t)&&m(r,t,!0,!0))return e;e=r.host}}},function(e,t,r){var n=r(13);e.exports=function(e){if(!n(e))throw TypeError(String(e)+" is not an object");return e}},function(e,t,r){"use strict";var n=r(24),o=r(130),i=r(49),a=r(43),s=r(88),l=a.set,u=a.getterFor("Array Iterator");e.exports=s(Array,"Array",function(e,t){l(this,{type:"Array Iterator",target:n(e),index:0,kind:t})},function(){var e=u(this),t=e.target,r=e.kind,n=e.index++;return!t||n>=t.length?(e.target=void 0,{value:void 0,done:!0}):"keys"==r?{value:n,done:!1}:"values"==r?{value:t[n],done:!1}:{value:[n,t[n]],done:!1}},"values"),i.Arguments=i.Array,o("keys"),o("values"),o("entries")},function(e,t,r){var n=r(90),o=r(25),i=r(202);n||o(Object.prototype,"toString",i,{unsafe:!0})},function(e,t,r){var n=r(16),o=r(15),i=r(40);e.exports=n?function(e,t,r){return o.f(e,t,i(1,r))}:function(e,t,r){return e[t]=r,e}},function(e,t,r){"use strict";var n=r(137).charAt,o=r(43),i=r(88),a=o.set,s=o.getterFor("String Iterator");i(String,"String",function(e){a(this,{type:"String Iterator",string:String(e),index:0})},function(){var e,t=s(this),r=t.string,o=t.index;return o>=r.length?{value:void 0,done:!0}:(e=n(r,o),t.index+=e.length,{value:e,done:!1})})},function(e,t,r){var n=r(11),o=r(203),i=r(19),a=r(21),s=r(5),l=s("iterator"),u=s("toStringTag"),c=i.values;for(var d in o){var p=n[d],f=p&&p.prototype;if(f){if(f[l]!==c)try{a(f,l,c)}catch(e){f[l]=c}if(f[u]||a(f,u,d),o[d])for(var h in i)if(f[h]!==i[h])try{a(f,h,i[h])}catch(e){f[h]=i[h]}}}},function(e,t,r){var n=r(41),o=r(35);e.exports=function(e){return n(o(e))}},function(e,t,r){var n=r(11),o=r(21),i=r(14),a=r(80),s=r(117),l=r(43),u=l.get,c=l.enforce,d=String(String).split("String");(e.exports=function(e,t,r,s){var l=!!s&&!!s.unsafe,u=!!s&&!!s.enumerable,p=!!s&&!!s.noTargetGet;"function"==typeof r&&("string"!=typeof t||i(r,"name")||o(r,"name",t),c(r).source=d.join("string"==typeof t?t:"")),e!==n?(l?!p&&e[t]&&(u=!0):delete e[t],u?e[t]=r:o(e,t,r)):u?e[t]=r:a(t,r)})(Function.prototype,"toString",function(){return"function"==typeof this&&u(this).source||s(this)})},function(e,t,r){var n=r(47),o=Math.min;e.exports=function(e){return e>0?o(n(e),9007199254740991):0}},function(e,t,r){var n=r(35);e.exports=function(e){return Object(n(e))}},function(e,t,r){var n=r(16),o=r(8),i=r(14),a=Object.defineProperty,s={},l=function(e){throw e};e.exports=function(e,t){if(i(s,e))return s[e];t||(t={});var r=[][e],u=!!i(t,"ACCESSORS")&&t.ACCESSORS,c=i(t,0)?t[0]:l,d=i(t,1)?t[1]:void 0;return s[e]=!!r&&!o(function(){if(u&&!n)return!0;var e={length:-1};u?a(e,1,{enumerable:!0,get:l}):e[1]=1,r.call(e,c,d)})}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(148),o=r(149),i=r(151),a=r(98),s=r(153),l=r(154),u=r(155),c=r(99),d=r(100),p=r(156),f=r(157),h=r(101),m=r(158),g=r(159),y=r(160),v=r(161),b=r(162),x=r(163),_=r(164),S=r(165),C=r(166),T=r(167),w=r(168),A=r(169),E=r(170);t.create_domImplementation=function(e){return n.DOMImplementationImpl._create(e)},t.create_window=function(){return o.WindowImpl._create()},t.create_xmlDocument=function(){return new i.XMLDocumentImpl},t.create_document=function(){return new a.DocumentImpl},t.create_abortController=function(){return new s.AbortControllerImpl},t.create_abortSignal=function(){return l.AbortSignalImpl._create()},t.create_documentType=function(e,t,r,n){return u.DocumentTypeImpl._create(e,t,r,n)},t.create_element=function(e,t,r,n){return c.ElementImpl._create(e,t,r,n)},t.create_htmlElement=function(e,t,r,n){return c.ElementImpl._create(e,t,r,n)},t.create_htmlUnknownElement=function(e,t,r,n){return c.ElementImpl._create(e,t,r,n)},t.create_documentFragment=function(e){return d.DocumentFragmentImpl._create(e)},t.create_shadowRoot=function(e,t){return p.ShadowRootImpl._create(e,t)},t.create_attr=function(e,t){return f.AttrImpl._create(e,t)},t.create_text=function(e,t){return h.TextImpl._create(e,t)},t.create_cdataSection=function(e,t){return m.CDATASectionImpl._create(e,t)},t.create_comment=function(e,t){return g.CommentImpl._create(e,t)},t.create_processingInstruction=function(e,t,r){return y.ProcessingInstructionImpl._create(e,t,r)},t.create_htmlCollection=function(e,t){return void 0===t&&(t=function(){return!0}),v.HTMLCollectionImpl._create(e,t)},t.create_nodeList=function(e){return b.NodeListImpl._create(e)},t.create_nodeListStatic=function(e,t){return x.NodeListStaticImpl._create(e,t)},t.create_namedNodeMap=function(e){return _.NamedNodeMapImpl._create(e)},t.create_range=function(e,t){return S.RangeImpl._create(e,t)},t.create_nodeIterator=function(e,t,r){return C.NodeIteratorImpl._create(e,t,r)},t.create_treeWalker=function(e,t){return T.TreeWalkerImpl._create(e,t)},t.create_nodeFilter=function(){return w.NodeFilterImpl._create()},t.create_mutationRecord=function(e,t,r,n,o,i,a,s,l){return A.MutationRecordImpl._create(e,t,r,n,o,i,a,s,l)},t.create_domTokenList=function(e,t){return E.DOMTokenListImpl._create(e,t)}},function(e,t,r){"use strict";var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var o=r(6),i=r(17),a=r(3),s=r(72),l=new Map;function u(e,t){if(t!==e._root&&i.tree_isAncestorOf(e._reference,t,!0)){if(e._pointerBeforeReference)for(;;){var r=i.tree_getFollowingNode(e._root,t);if(null!==r&&i.tree_isDescendantOf(e._root,r,!0)&&!i.tree_isDescendantOf(t,r,!0))return void(e._reference=r);if(null===r)return void(e._pointerBeforeReference=!1)}if(null===t._previousSibling)null!==t._parent&&(e._reference=t._parent);else{for(var n=t._previousSibling,o=i.tree_getFirstDescendantNode(t._previousSibling,!0,!1);null!==o;)null!==o&&(n=o),o=i.tree_getNextDescendantNode(t._previousSibling,o,!0,!1);e._reference=n}}}function c(e,t,r,n,o){if(a.Guard.isSlot(e)&&"name"===t&&null===o){if(n===r)return;if(null===n&&""===r)return;if(""===n&&null===r)return;e._name=null===n||""===n?"":n,s.shadowTree_assignSlotablesForATree(i.tree_rootNode(e))}}function d(e,t,r,n,o){if(a.Guard.isSlotable(e)&&"slot"===t&&null===o){if(n===r)return;if(null===n&&""===r)return;if(""===n&&null===r)return;e._name=null===n||""===n?"":n,s.shadowTree_isAssigned(e)&&s.shadowTree_assignSlotables(e._assignedSlot),s.shadowTree_assignASlot(e)}}function p(e,t,r,n){"id"===t&&null===n&&(e._uniqueIdentifier=r||void 0)}t.dom_runRemovingSteps=function(e,t){},t.dom_runCloningSteps=function(e,t,r,n){},t.dom_runAdoptingSteps=function(e,t){},t.dom_runAttributeChangeSteps=function(e,t,r,i,a){var s,l;o.dom.features.slots&&(d.call(e,e,t,r,i,a),c.call(e,e,t,r,i,a)),p.call(e,e,t,i,a);try{for(var u=n(e._attributeChangeSteps),f=u.next();!f.done;f=u.next())f.value.call(e,e,t,r,i,a)}catch(e){s={error:e}}finally{try{f&&!f.done&&(l=u.return)&&l.call(u)}finally{if(s)throw s.error}}},t.dom_runInsertionSteps=function(e){},t.dom_runNodeIteratorPreRemovingSteps=function(e,t){u.call(e,e,t)},t.dom_hasSupportedTokens=function(e){return l.has(e)},t.dom_getSupportedTokens=function(e){return l.get(e)||new Set},t.dom_runEventConstructingSteps=function(e){},t.dom_runChildTextContentChangeSteps=function(e){}},function(e,t,r){"use strict";var n=r(4),o=r(11),i=r(46),a=r(44),s=r(16),l=r(86),u=r(124),c=r(8),d=r(14),p=r(59),f=r(13),h=r(18),m=r(27),g=r(24),y=r(56),v=r(40),b=r(60),x=r(61),_=r(82),S=r(190),C=r(85),T=r(55),w=r(15),A=r(79),E=r(21),D=r(25),P=r(81),I=r(57),O=r(45),N=r(58),M=r(5),R=r(125),F=r(126),B=r(62),L=r(43),k=r(36).forEach,U=I("hidden"),V=M("toPrimitive"),G=L.set,z=L.getterFor("Symbol"),j=Object.prototype,W=o.Symbol,H=i("JSON","stringify"),K=T.f,X=w.f,$=S.f,q=A.f,Y=P("symbols"),J=P("op-symbols"),Q=P("string-to-symbol-registry"),Z=P("symbol-to-string-registry"),ee=P("wks"),te=o.QObject,re=!te||!te.prototype||!te.prototype.findChild,ne=s&&c(function(){return 7!=b(X({},"a",{get:function(){return X(this,"a",{value:7}).a}})).a})?function(e,t,r){var n=K(j,t);n&&delete j[t],X(e,t,r),n&&e!==j&&X(j,t,n)}:X,oe=function(e,t){var r=Y[e]=b(W.prototype);return G(r,{type:"Symbol",tag:e,description:t}),s||(r.description=t),r},ie=u?function(e){return"symbol"==typeof e}:function(e){return Object(e)instanceof W},ae=function(e,t,r){e===j&&ae(J,t,r),h(e);var n=y(t,!0);return h(r),d(Y,n)?(r.enumerable?(d(e,U)&&e[U][n]&&(e[U][n]=!1),r=b(r,{enumerable:v(0,!1)})):(d(e,U)||X(e,U,v(1,{})),e[U][n]=!0),ne(e,n,r)):X(e,n,r)},se=function(e,t){h(e);var r=g(t),n=x(r).concat(de(r));return k(n,function(t){s&&!le.call(r,t)||ae(e,t,r[t])}),e},le=function(e){var t=y(e,!0),r=q.call(this,t);return!(this===j&&d(Y,t)&&!d(J,t))&&(!(r||!d(this,t)||!d(Y,t)||d(this,U)&&this[U][t])||r)},ue=function(e,t){var r=g(e),n=y(t,!0);if(r!==j||!d(Y,n)||d(J,n)){var o=K(r,n);return!o||!d(Y,n)||d(r,U)&&r[U][n]||(o.enumerable=!0),o}},ce=function(e){var t=$(g(e)),r=[];return k(t,function(e){d(Y,e)||d(O,e)||r.push(e)}),r},de=function(e){var t=e===j,r=$(t?J:g(e)),n=[];return k(r,function(e){!d(Y,e)||t&&!d(j,e)||n.push(Y[e])}),n};l||(D((W=function(){if(this instanceof W)throw TypeError("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?String(arguments[0]):void 0,t=N(e),r=function(e){this===j&&r.call(J,e),d(this,U)&&d(this[U],t)&&(this[U][t]=!1),ne(this,t,v(1,e))};return s&&re&&ne(j,t,{configurable:!0,set:r}),oe(t,e)}).prototype,"toString",function(){return z(this).tag}),D(W,"withoutSetter",function(e){return oe(N(e),e)}),A.f=le,w.f=ae,T.f=ue,_.f=S.f=ce,C.f=de,R.f=function(e){return oe(M(e),e)},s&&(X(W.prototype,"description",{configurable:!0,get:function(){return z(this).description}}),a||D(j,"propertyIsEnumerable",le,{unsafe:!0}))),n({global:!0,wrap:!0,forced:!l,sham:!l},{Symbol:W}),k(x(ee),function(e){F(e)}),n({target:"Symbol",stat:!0,forced:!l},{for:function(e){var t=String(e);if(d(Q,t))return Q[t];var r=W(t);return Q[t]=r,Z[r]=t,r},keyFor:function(e){if(!ie(e))throw TypeError(e+" is not a symbol");if(d(Z,e))return Z[e]},useSetter:function(){re=!0},useSimple:function(){re=!1}}),n({target:"Object",stat:!0,forced:!l,sham:!s},{create:function(e,t){return void 0===t?b(e):se(b(e),t)},defineProperty:ae,defineProperties:se,getOwnPropertyDescriptor:ue}),n({target:"Object",stat:!0,forced:!l},{getOwnPropertyNames:ce,getOwnPropertySymbols:de}),n({target:"Object",stat:!0,forced:c(function(){C.f(1)})},{getOwnPropertySymbols:function(e){return C.f(m(e))}}),H&&n({target:"JSON",stat:!0,forced:!l||c(function(){var e=W();return"[null]"!=H([e])||"{}"!=H({a:e})||"{}"!=H(Object(e))})},{stringify:function(e,t,r){for(var n,o=[e],i=1;arguments.length>i;)o.push(arguments[i++]);if(n=t,(f(t)||void 0!==e)&&!ie(e))return p(t)||(t=function(e,t){if("function"==typeof n&&(t=n.call(this,e,t)),!ie(t))return t}),o[1]=t,H.apply(null,o)}}),W.prototype[V]||E(W.prototype,V,W.prototype.valueOf),B(W,"Symbol"),O[U]=!0},function(e,t,r){"use strict";var n=r(4),o=r(16),i=r(11),a=r(14),s=r(13),l=r(15).f,u=r(119),c=i.Symbol;if(o&&"function"==typeof c&&(!("description"in c.prototype)||void 0!==c().description)){var d={},p=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:String(arguments[0]),t=this instanceof p?new c(e):void 0===e?c():c(e);return""===e&&(d[t]=!0),t};u(p,c);var f=p.prototype=c.prototype;f.constructor=p;var h=f.toString,m="Symbol(test)"==String(c("test")),g=/^Symbol\((.*)\)[^)]+$/;l(f,"description",{configurable:!0,get:function(){var e=s(this)?this.valueOf():this,t=h.call(e);if(a(d,e))return"";var r=m?t.slice(7,-1):t.replace(g,"$1");return""===r?void 0:r}}),n({global:!0,forced:!0},{Symbol:p})}},function(e,t,r){r(126)("iterator")},function(e,t,r){"use strict";var n,o=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),i=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var a=r(6),s=r(2),l=r(70),u=r(3),c=r(9),d=r(0),p=r(152),f=r(12),h=function(e){function t(){var t=e.call(this)||this;return t._parent=null,t._firstChild=null,t._lastChild=null,t._previousSibling=null,t._nextSibling=null,t}return o(t,e),Object.defineProperty(t.prototype,"_childNodes",{get:function(){return this.__childNodes||(this.__childNodes=d.create_nodeList(this))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"_nodeDocument",{get:function(){return this._nodeDocumentOverride||a.dom.window._associatedDocument},set:function(e){this._nodeDocumentOverride=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"_registeredObserverList",{get:function(){return this.__registeredObserverList||(this.__registeredObserverList=[])},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nodeType",{get:function(){return this._nodeType},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nodeName",{get:function(){return u.Guard.isElementNode(this)?this._htmlUppercasedQualifiedName:u.Guard.isAttrNode(this)?this._qualifiedName:u.Guard.isExclusiveTextNode(this)?"#text":u.Guard.isCDATASectionNode(this)?"#cdata-section":u.Guard.isProcessingInstructionNode(this)?this._target:u.Guard.isCommentNode(this)?"#comment":u.Guard.isDocumentNode(this)?"#document":u.Guard.isDocumentTypeNode(this)?this._name:u.Guard.isDocumentFragmentNode(this)?"#document-fragment":""},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"baseURI",{get:function(){return p.urlSerializer(this._nodeDocument._URL)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isConnected",{get:function(){return u.Guard.isElementNode(this)&&d.shadowTree_isConnected(this)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ownerDocument",{get:function(){return this._nodeType===s.NodeType.Document?null:this._nodeDocument},enumerable:!0,configurable:!0}),t.prototype.getRootNode=function(e){return d.tree_rootNode(this,!!e&&e.composed)},Object.defineProperty(t.prototype,"parentNode",{get:function(){return this._nodeType===s.NodeType.Attribute?null:this._parent},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"parentElement",{get:function(){return this._parent&&u.Guard.isElementNode(this._parent)?this._parent:null},enumerable:!0,configurable:!0}),t.prototype.hasChildNodes=function(){return null!==this._firstChild},Object.defineProperty(t.prototype,"childNodes",{get:function(){return this._childNodes},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"firstChild",{get:function(){return this._firstChild},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"lastChild",{get:function(){return this._lastChild},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"previousSibling",{get:function(){return this._previousSibling},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nextSibling",{get:function(){return this._nextSibling},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nodeValue",{get:function(){return u.Guard.isAttrNode(this)?this._value:u.Guard.isCharacterDataNode(this)?this._data:null},set:function(e){null===e&&(e=""),u.Guard.isAttrNode(this)?d.attr_setAnExistingAttributeValue(this,e):u.Guard.isCharacterDataNode(this)&&d.characterData_replaceData(this,0,this._data.length,e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"textContent",{get:function(){return u.Guard.isDocumentFragmentNode(this)||u.Guard.isElementNode(this)?d.text_descendantTextContent(this):u.Guard.isAttrNode(this)?this._value:u.Guard.isCharacterDataNode(this)?this._data:null},set:function(e){null===e&&(e=""),u.Guard.isDocumentFragmentNode(this)||u.Guard.isElementNode(this)?d.node_stringReplaceAll(e,this):u.Guard.isAttrNode(this)?d.attr_setAnExistingAttributeValue(this,e):u.Guard.isCharacterDataNode(this)&&d.characterData_replaceData(this,0,d.tree_nodeLength(this),e)},enumerable:!0,configurable:!0}),t.prototype.normalize=function(){for(var e,t,r,n,o=[],s=d.tree_getFirstDescendantNode(this,!1,!1,function(e){return u.Guard.isExclusiveTextNode(e)});null!==s;)o.push(s),s=d.tree_getNextDescendantNode(this,s,!1,!1,function(e){return u.Guard.isExclusiveTextNode(e)});for(var l=0;lC;C++)if((p||C in x)&&(v=_(y=x[C],C,b),e))if(t)w[C]=v;else if(v)switch(e){case 3:return!0;case 5:return y;case 6:return C;case 2:l.call(w,y)}else if(c)return!1;return d?-1:u||c?c:w}};e.exports={forEach:u(0),map:u(1),filter:u(2),some:u(3),every:u(4),find:u(5),findIndex:u(6)}},function(e,t,r){"use strict";var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},o=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a},i=this&&this.__spread||function(){for(var e=[],t=0;t1)throw new s.HierarchyRequestError("A document node can only have one document element node. Document fragment to be inserted has "+v+" element nodes.");if(1===v){try{for(var S=n(t._children),C=S.next();!C.done;C=S.next())if(C.value._nodeType===l.NodeType.Element)throw new s.HierarchyRequestError("The document node already has a document element node.")}catch(e){a={error:e}}finally{try{C&&!C.done&&(u=S.return)&&u.call(S)}finally{if(a)throw a.error}}if(r){if(y===l.NodeType.DocumentType)throw new s.HierarchyRequestError("Cannot insert an element node before a document type node.");for(var T=r._nextSibling;T;){if(T._nodeType===l.NodeType.DocumentType)throw new s.HierarchyRequestError("Cannot insert an element node before a document type node.");T=T._nextSibling}}}}else if(g===l.NodeType.Element){try{for(var w=n(t._children),A=w.next();!A.done;A=w.next())if(A.value._nodeType===l.NodeType.Element)throw new s.HierarchyRequestError("Document already has a document element node. Node is "+e.nodeName+".")}catch(e){c={error:e}}finally{try{A&&!A.done&&(d=w.return)&&d.call(w)}finally{if(c)throw c.error}}if(r){if(y===l.NodeType.DocumentType)throw new s.HierarchyRequestError("Cannot insert an element node before a document type node. Node is "+e.nodeName+".");for(T=r._nextSibling;T;){if(T._nodeType===l.NodeType.DocumentType)throw new s.HierarchyRequestError("Cannot insert an element node before a document type node. Node is "+e.nodeName+".");T=T._nextSibling}}}else if(g===l.NodeType.DocumentType){try{for(var E=n(t._children),D=E.next();!D.done;D=E.next())if(D.value._nodeType===l.NodeType.DocumentType)throw new s.HierarchyRequestError("Document already has a document type node. Node is "+e.nodeName+".")}catch(e){p={error:e}}finally{try{D&&!D.done&&(h=E.return)&&h.call(E)}finally{if(p)throw p.error}}if(r)for(var P=r._previousSibling;P;){if(P._nodeType===l.NodeType.Element)throw new s.HierarchyRequestError("Cannot insert a document type node before an element node. Node is "+e.nodeName+".");P=P._previousSibling}else for(P=t._firstChild;P;){if(P._nodeType===l.NodeType.Element)throw new s.HierarchyRequestError("Cannot insert a document type node before an element node. Node is "+e.nodeName+".");P=P._nextSibling}}}function x(e,t,r){b(e,t,r);var n=r;return n===e&&(n=e._nextSibling),v.document_adopt(e,t._nodeDocument),_(e,t,n),e}function _(e,t,r,o){var s,h;if(null!==r||e._nodeType===l.NodeType.DocumentFragment){var v=e._nodeType===l.NodeType.DocumentFragment?e._children.size:1;if(null!==r&&0!==a.dom.rangeList.size){var b=f.tree_index(r);try{for(var x=n(a.dom.rangeList),_=x.next();!_.done;_=x.next()){var C=_.value;C._start[0]===t&&C._start[1]>b&&(C._start[1]+=v),C._end[0]===t&&C._end[1]>b&&(C._end[1]+=v)}}catch(e){s={error:e}}finally{try{_&&!_.done&&(h=x.return)&&h.call(x)}finally{if(s)throw s.error}}}var T=e._nodeType===l.NodeType.DocumentFragment?new(Array.bind.apply(Array,i([void 0],e._children))):[e];if(e._nodeType===l.NodeType.DocumentFragment)for(;e._firstChild;)S(e._firstChild,e,!0);a.dom.features.mutationObservers&&e._nodeType===l.NodeType.DocumentFragment&&g.observer_queueTreeMutationRecord(e,[],T,null,null);for(var w=r?r._previousSibling:t._lastChild,A=null===r?-1:f.tree_index(r),E=0;E_&&T._start[1]--,T._end[0]===t&&T._end[1]>_&&T._end[1]--}}catch(e){o={error:e}}finally{try{C&&!C.done&&(i=S.return)&&i.call(S)}finally{if(o)throw o.error}}try{for(var w=n(a.dom.rangeList),A=w.next();!A.done;A=w.next())(T=A.value)._start[0]===t&&T._start[1]>_&&(T._start[1]-=1),T._end[0]===t&&T._end[1]>_&&(T._end[1]-=1)}catch(e){s={error:e}}finally{try{A&&!A.done&&(l=w.return)&&l.call(w)}finally{if(s)throw s.error}}}if(a.dom.features.steps)try{for(var E=n(h.nodeIterator_iteratorList()),D=E.next();!D.done;D=E.next()){var P=D.value;P._root._nodeDocument===e._nodeDocument&&y.dom_runNodeIteratorPreRemovingSteps(P,e)}}catch(e){d={error:e}}finally{try{D&&!D.done&&(v=E.return)&&v.call(E)}finally{if(d)throw d.error}}var I=e._previousSibling,O=e._nextSibling;u.Guard.isDocumentNode(t)&&u.Guard.isElementNode(e)&&(t._documentElement=null),e._parent=null,t._children.delete(e);var N=e._previousSibling,M=e._nextSibling;e._previousSibling=null,e._nextSibling=null,N&&(N._nextSibling=M),M&&(M._previousSibling=N),N||(t._firstChild=M),M||(t._lastChild=N),a.dom.features.slots&&u.Guard.isSlotable(e)&&null!==e._assignedSlot&&m.shadowTree_isAssigned(e)&&m.shadowTree_assignSlotables(e._assignedSlot),a.dom.features.slots&&u.Guard.isShadowRoot(f.tree_rootNode(t))&&u.Guard.isSlot(t)&&c.isEmpty(t._assignedNodes)&&m.shadowTree_signalASlotChange(t),a.dom.features.slots&&null!==f.tree_getFirstDescendantNode(e,!0,!1,function(e){return u.Guard.isSlot(e)})&&(m.shadowTree_assignSlotablesForATree(f.tree_rootNode(t)),m.shadowTree_assignSlotablesForATree(e)),a.dom.features.steps&&y.dom_runRemovingSteps(e,t),a.dom.features.customElements&&u.Guard.isCustomElementNode(e)&&p.customElement_enqueueACustomElementCallbackReaction(e,"disconnectedCallback",[]);for(var R=f.tree_getFirstDescendantNode(e,!1,!0);null!==R;)a.dom.features.steps&&y.dom_runRemovingSteps(R,e),a.dom.features.customElements&&u.Guard.isCustomElementNode(R)&&p.customElement_enqueueACustomElementCallbackReaction(R,"disconnectedCallback",[]),R=f.tree_getNextDescendantNode(e,R,!1,!0);if(a.dom.features.mutationObservers)for(var F=f.tree_getFirstAncestorNode(t,!0);null!==F;){try{for(var B=(b=void 0,n(F._registeredObserverList)),L=B.next();!L.done;L=B.next()){var k=L.value;k.options.subtree&&e._registeredObserverList.push({observer:k.observer,options:k.options,source:k})}}catch(e){b={error:e}}finally{try{L&&!L.done&&(x=B.return)&&x.call(B)}finally{if(b)throw b.error}}F=f.tree_getNextAncestorNode(t,F,!0)}a.dom.features.mutationObservers&&(r||g.observer_queueTreeMutationRecord(t,[],[e],I,O)),a.dom.features.steps&&u.Guard.isTextNode(e)&&y.dom_runChildTextContentChangeSteps(t)}t.mutation_ensurePreInsertionValidity=b,t.mutation_preInsert=x,t.mutation_insert=_,t.mutation_append=function(e,t){return x(e,t,null)},t.mutation_replace=function(e,t,r){var o,i,u,c,d,p,h,m;if(r._nodeType!==l.NodeType.Document&&r._nodeType!==l.NodeType.DocumentFragment&&r._nodeType!==l.NodeType.Element)throw new s.HierarchyRequestError("Only document, document fragment and element nodes can contain child nodes. Parent node is "+r.nodeName+".");if(f.tree_isHostIncludingAncestorOf(r,t,!0))throw new s.HierarchyRequestError("The node to be inserted cannot be an ancestor of parent node. Node is "+t.nodeName+", parent node is "+r.nodeName+".");if(e._parent!==r)throw new s.NotFoundError("The reference child node cannot be found under parent node. Child node is "+e.nodeName+", parent node is "+r.nodeName+".");if(t._nodeType!==l.NodeType.DocumentFragment&&t._nodeType!==l.NodeType.DocumentType&&t._nodeType!==l.NodeType.Element&&t._nodeType!==l.NodeType.Text&&t._nodeType!==l.NodeType.ProcessingInstruction&&t._nodeType!==l.NodeType.CData&&t._nodeType!==l.NodeType.Comment)throw new s.HierarchyRequestError("Only document fragment, document type, element, text, processing instruction, cdata section or comment nodes can be inserted. Node is "+t.nodeName+".");if(t._nodeType===l.NodeType.Text&&r._nodeType===l.NodeType.Document)throw new s.HierarchyRequestError("Cannot insert a text node as a child of a document node. Node is "+t.nodeName+".");if(t._nodeType===l.NodeType.DocumentType&&r._nodeType!==l.NodeType.Document)throw new s.HierarchyRequestError("A document type node can only be inserted under a document node. Parent node is "+r.nodeName+".");if(r._nodeType===l.NodeType.Document)if(t._nodeType===l.NodeType.DocumentFragment){var y=0;try{for(var b=n(t._children),x=b.next();!x.done;x=b.next()){var C=x.value;if(C._nodeType===l.NodeType.Element)y++;else if(C._nodeType===l.NodeType.Text)throw new s.HierarchyRequestError("Cannot insert text a node as a child of a document node. Node is "+C.nodeName+".")}}catch(e){o={error:e}}finally{try{x&&!x.done&&(i=b.return)&&i.call(b)}finally{if(o)throw o.error}}if(y>1)throw new s.HierarchyRequestError("A document node can only have one document element node. Document fragment to be inserted has "+y+" element nodes.");if(1===y){try{for(var T=n(r._children),w=T.next();!w.done;w=T.next())if((O=w.value)._nodeType===l.NodeType.Element&&O!==e)throw new s.HierarchyRequestError("The document node already has a document element node.")}catch(e){u={error:e}}finally{try{w&&!w.done&&(c=T.return)&&c.call(T)}finally{if(u)throw u.error}}for(var A=e._nextSibling;A;){if(A._nodeType===l.NodeType.DocumentType)throw new s.HierarchyRequestError("Cannot insert an element node before a document type node.");A=A._nextSibling}}}else if(t._nodeType===l.NodeType.Element){try{for(var E=n(r._children),D=E.next();!D.done;D=E.next())if((O=D.value)._nodeType===l.NodeType.Element&&O!==e)throw new s.HierarchyRequestError("Document already has a document element node. Node is "+t.nodeName+".")}catch(e){d={error:e}}finally{try{D&&!D.done&&(p=E.return)&&p.call(E)}finally{if(d)throw d.error}}for(A=e._nextSibling;A;){if(A._nodeType===l.NodeType.DocumentType)throw new s.HierarchyRequestError("Cannot insert an element node before a document type node. Node is "+t.nodeName+".");A=A._nextSibling}}else if(t._nodeType===l.NodeType.DocumentType){try{for(var P=n(r._children),I=P.next();!I.done;I=P.next()){var O;if((O=I.value)._nodeType===l.NodeType.DocumentType&&O!==e)throw new s.HierarchyRequestError("Document already has a document type node. Node is "+t.nodeName+".")}}catch(e){h={error:e}}finally{try{I&&!I.done&&(m=P.return)&&m.call(P)}finally{if(h)throw h.error}}for(var N=e._previousSibling;N;){if(N._nodeType===l.NodeType.Element)throw new s.HierarchyRequestError("Cannot insert a document type node before an element node. Node is "+t.nodeName+".");N=N._previousSibling}}var M=e._nextSibling;M===t&&(M=t._nextSibling);var R=e._previousSibling;v.document_adopt(t,r._nodeDocument);var F=[];null!==e._parent&&(F.push(e),S(e,e._parent,!0));var B=[];return t._nodeType===l.NodeType.DocumentFragment?B=Array.from(t._children):B.push(t),_(t,r,M,!0),a.dom.features.mutationObservers&&g.observer_queueTreeMutationRecord(r,B,F,R,M),e},t.mutation_replaceAll=function(e,t){var r,o;null!==e&&v.document_adopt(e,t._nodeDocument);var i=Array.from(t._children),s=[];e&&e._nodeType===l.NodeType.DocumentFragment?s=Array.from(e._children):null!==e&&s.push(e);try{for(var u=n(i),c=u.next();!c.done;c=u.next())S(c.value,t,!0)}catch(e){r={error:e}}finally{try{c&&!c.done&&(o=u.return)&&o.call(u)}finally{if(r)throw r.error}}null!==e&&_(e,t,null,!0),a.dom.features.mutationObservers&&g.observer_queueTreeMutationRecord(t,s,i,null,null)},t.mutation_preRemove=function(e,t){if(e._parent!==t)throw new s.NotFoundError("The child node cannot be found under parent node. Child node is "+e.nodeName+", parent node is "+t.nodeName+".");return S(e,t),e},t.mutation_remove=S},function(e,t,r){"use strict";function n(e){return null==e}e.exports.isNothing=n,e.exports.isObject=function(e){return"object"==typeof e&&null!==e},e.exports.toArray=function(e){return Array.isArray(e)?e:n(e)?[]:[e]},e.exports.repeat=function(e,t){var r,n="";for(r=0;r0?n:r)(e)}},function(e,t,r){"use strict";var n=r(8);e.exports=function(e,t){var r=[][e];return!!r&&n(function(){r.call(null,t||function(){throw 1},1)})}},function(e,t){e.exports={}},function(e,t,r){"use strict";r(31),r(32),r(33),r(220),r(64),r(19),r(65),r(20),r(68),r(66),r(92),r(144),r(22),r(94),r(23);var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},o=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a},i=this&&this.__spread||function(){for(var e=[],t=0;t/g,">");this.text(r)},e.prototype._serializeDocumentFragmentNS=function(e,t,r,o,i){var a,s;try{for(var l=n(e.childNodes),u=l.next();!u.done;u=l.next()){var c=u.value;this._serializeNodeNS(c,t,r,o,i)}}catch(e){a={error:e}}finally{try{u&&!u.done&&(s=l.return)&&s.call(l)}finally{if(a)throw a.error}}},e.prototype._serializeDocumentFragment=function(e,t){var r,o;try{for(var i=n(e._children),a=i.next();!a.done;a=i.next()){var s=a.value;this._serializeNode(s,t)}}catch(e){r={error:e}}finally{try{a&&!a.done&&(o=i.return)&&o.call(i)}finally{if(r)throw r.error}}},e.prototype._serializeDocumentType=function(e,t){if(t&&!c.xml_isPubidChar(e.publicId))throw new Error("DocType public identifier does not match PubidChar construct (well-formed required).");if(t&&(!c.xml_isLegalChar(e.systemId)||-1!==e.systemId.indexOf('"')&&-1!==e.systemId.indexOf("'")))throw new Error("DocType system identifier contains invalid characters (well-formed required).");this.docType(e.name,e.publicId,e.systemId)},e.prototype._serializeProcessingInstruction=function(e,t){if(t&&(-1!==e.target.indexOf(":")||/^xml$/i.test(e.target)))throw new Error("Processing instruction target contains invalid characters (well-formed required).");if(t&&(!c.xml_isLegalChar(e.data)||-1!==e.data.indexOf("?>")))throw new Error("Processing instruction data contains invalid characters (well-formed required).");this.instruction(e.target,e.data)},e.prototype._serializeCData=function(e,t){if(t&&-1!==e.data.indexOf("]]>"))throw new Error("CDATA contains invalid characters (well-formed required).");this.cdata(e.data)},e.prototype._serializeAttributesNS=function(e,t,r,o,i,a){var l,d,p=[],f=a?new s.LocalNameSet:void 0;try{for(var h=n(e.attributes),m=h.next();!m.done;m=h.next()){var g=m.value;if(a||i||null!==g.namespaceURI){if(a&&f&&f.has(g.namespaceURI,g.localName))throw new Error("Element contains duplicate attributes (well-formed required).");a&&f&&f.set(g.namespaceURI,g.localName);var y=g.namespaceURI,v=null;if(null!==y)if(v=t.get(g.prefix,y),y===u.namespace.XMLNS){if(g.value===u.namespace.XML||null===g.prefix&&i||null!==g.prefix&&(!(g.localName in o)||o[g.localName]!==g.value)&&t.has(g.localName,g.value))continue;if(a&&g.value===u.namespace.XMLNS)throw new Error("XMLNS namespace is reserved (well-formed required).");if(a&&""===g.value)throw new Error("Namespace prefix declarations cannot be used to undeclare a namespace (well-formed required).");"xmlns"===g.prefix&&(v="xmlns")}else null===v&&(v=null===g.prefix||t.hasPrefix(g.prefix)&&!t.has(g.prefix,y)?this._generatePrefix(y,t,r):g.prefix,p.push([null,"xmlns",v,this._serializeAttributeValue(y,a)]));if(a&&(-1!==g.localName.indexOf(":")||!c.xml_isName(g.localName)||"xmlns"===g.localName&&null===y))throw new Error("Attribute local name contains invalid characters (well-formed required).");p.push([y,v,g.localName,this._serializeAttributeValue(g.value,a)])}else p.push([null,null,g.localName,this._serializeAttributeValue(g.value,a)])}}catch(e){l={error:e}}finally{try{m&&!m.done&&(d=h.return)&&d.call(h)}finally{if(l)throw l.error}}return p},e.prototype._serializeAttributes=function(e,t){var r,o,i=[],a=t?{}:void 0;try{for(var s=n(e.attributes),l=s.next();!l.done;l=s.next()){var u=l.value;if(t){if(t&&a&&u.localName in a)throw new Error("Element contains duplicate attributes (well-formed required).");if(t&&a&&(a[u.localName]=!0),t&&(-1!==u.localName.indexOf(":")||!c.xml_isName(u.localName)))throw new Error("Attribute local name contains invalid characters (well-formed required).");i.push([null,null,u.localName,this._serializeAttributeValue(u.value,t)])}else i.push([null,null,u.localName,this._serializeAttributeValue(u.value,t)])}}catch(e){r={error:e}}finally{try{l&&!l.done&&(o=s.return)&&o.call(s)}finally{if(r)throw r.error}}return i},e.prototype._recordNamespaceInformation=function(e,t,r){var o,i,a=null;try{for(var s=n(e.attributes),l=s.next();!l.done;l=s.next()){var c=l.value,d=c.namespaceURI,p=c.prefix;if(d===u.namespace.XMLNS){if(null===p){a=c.value;continue}var f=c.localName,h=c.value;if(h===u.namespace.XML)continue;if(""===h&&(h=null),t.has(f,h))continue;t.set(f,h),r[f]=h||""}}}catch(e){o={error:e}}finally{try{l&&!l.done&&(i=s.return)&&i.call(s)}finally{if(o)throw o.error}}return a},e.prototype._generatePrefix=function(e,t,r){var n="ns"+r.value.toString();return r.value++,t.set(n,e),n},e.prototype._serializeAttributeValue=function(e,t){if(t&&null!==e&&!c.xml_isLegalChar(e))throw new Error("Invalid characters in attribute value.");return null===e?"":e.replace(/(?!&([^&;]*);)&/g,"&").replace(//g,">").replace(/"/g,""")},e._VoidElementNames=new Set(["area","base","basefont","bgsound","br","col","embed","frame","hr","img","input","keygen","link","menuitem","meta","param","source","track","wbr"]),e}();t.BaseWriter=d},function(e,t,r){"use strict";var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},o=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a};Object.defineProperty(t,"__esModule",{value:!0});var i=r(6),a=r(3),s=r(7),l=r(29),u=r(17),c=r(97);function d(){var e=i.dom.window;e._mutationObserverMicrotaskQueued||(e._mutationObserverMicrotaskQueued=!0,Promise.resolve().then(function(){p()}))}function p(){var e,t,r,o,l=i.dom.window;l._mutationObserverMicrotaskQueued=!1;var u=s.set.clone(l._mutationObservers),d=s.set.clone(l._signalSlots);s.set.empty(l._signalSlots);var p=function(e){var t=s.list.clone(e._recordQueue);s.list.empty(e._recordQueue);for(var r=0;r"+e+"<\/script>"},f=function(){try{n=document.domain&&new ActiveXObject("htmlfile")}catch(e){}var e,t;f=n?function(e){e.write(p("")),e.close();var t=e.parentWindow.Object;return e=null,t}(n):((t=u("iframe")).style.display="none",l.appendChild(t),t.src=String("javascript:"),(e=t.contentWindow.document).open(),e.write(p("document.F=Object")),e.close(),e.F);for(var r=a.length;r--;)delete f.prototype[a[r]];return f()};s[c]=!0,e.exports=Object.create||function(e,t){var r;return null!==e?(d.prototype=o(e),r=new d,d.prototype=null,r[c]=e):r=f(),void 0===t?r:i(r,t)}},function(e,t,r){var n=r(121),o=r(84);e.exports=Object.keys||function(e){return n(e,o)}},function(e,t,r){var n=r(15).f,o=r(14),i=r(5)("toStringTag");e.exports=function(e,t,r){e&&!o(e=r?e:e.prototype,i)&&n(e,i,{configurable:!0,value:t})}},function(e,t,r){var n=r(8),o=r(5),i=r(129),a=o("species");e.exports=function(e){return i>=51||!n(function(){var t=[];return(t.constructor={})[a]=function(){return{foo:1}},1!==t[e](Boolean).foo})}},function(e,t,r){"use strict";var n=r(4),o=r(122).indexOf,i=r(48),a=r(28),s=[].indexOf,l=!!s&&1/[1].indexOf(1,-0)<0,u=i("indexOf"),c=a("indexOf",{ACCESSORS:!0,1:0});n({target:"Array",proto:!0,forced:l||!u||!c},{indexOf:function(e){return l?s.apply(this,arguments)||0:o(this,e,arguments.length>1?arguments[1]:void 0)}})},function(e,t,r){var n=r(16),o=r(15).f,i=Function.prototype,a=i.toString,s=/^\s*function ([^ (]*)/;n&&!("name"in i)&&o(i,"name",{configurable:!0,get:function(){try{return a.call(this).match(s)[1]}catch(e){return""}}})},function(e,t,r){"use strict";var n=r(25),o=r(18),i=r(8),a=r(136),s=RegExp.prototype,l=s.toString,u=i(function(){return"/a/b"!=l.call({source:"a",flags:"b"})}),c="toString"!=l.name;(u||c)&&n(RegExp.prototype,"toString",function(){var e=o(this),t=String(e.source),r=e.flags;return"/"+t+"/"+String(void 0===r&&e instanceof RegExp&&!("flags"in s)?a.call(e):r)},{unsafe:!0})},function(e,t,r){"use strict";r(31),r(32),r(33),r(19),r(138),r(20),r(66),r(22),r(23);var n,o=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),i=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var a=r(1),s=r(2),l=function(e){function t(t,r){var n=e.call(this,t)||this;return n._writerOptions=a.applyDefaults(r,{format:"object",wellFormed:!1,group:!1,verbose:!1}),n}return o(t,e),t.prototype.serialize=function(e){return this._currentList=[],this._currentIndex=0,this._listRegister=[this._currentList],this.serializeNode(e,this._writerOptions.wellFormed),this._process(this._currentList,this._writerOptions)},t.prototype._process=function(e,t){var r,n,o,i,l,u,c;if(0===e.length)return{};for(var d={},p=!1,f=0,h=0,m=0,g=0,y=0;y2)try{for(var c=i(e),d=c.next();!d.done;d=c.next()){var p=d.value;t[n+(s++).toString()]=p}}catch(e){l={error:e}}finally{try{d&&!d.done&&(u=c.return)&&u.call(c)}finally{if(l)throw l.error}}else t[o>1?n+(s++).toString():n]=e;return s},t.prototype.beginElement=function(e){var t,r,n=[];if(0===this._currentList.length)this._currentList.push(((t={})[e]=n,t));else{var o=this._currentList[this._currentList.length-1];this._isElementNode(o,e)?0!==o[e].length&&a.isArray(o[e][0])?o[e].push(n):o[e]=[o[e],n]:this._currentList.push(((r={})[e]=n,r))}this._currentIndex++,this._listRegister.length>this._currentIndex?this._listRegister[this._currentIndex]=n:this._listRegister.push(n),this._currentList=n},t.prototype.endElement=function(){this._currentList=this._listRegister[--this._currentIndex]},t.prototype.attribute=function(e,t){var r,n;if(0===this._currentList.length)this._currentList.push({"@":(r={},r[e]=t,r)});else{var o=this._currentList[this._currentList.length-1];this._isAttrNode(o)?o["@"][e]=t:this._currentList.push({"@":(n={},n[e]=t,n)})}},t.prototype.comment=function(e){if(0===this._currentList.length)this._currentList.push({"!":e});else{var t=this._currentList[this._currentList.length-1];this._isCommentNode(t)?a.isArray(t["!"])?t["!"].push(e):t["!"]=[t["!"],e]:this._currentList.push({"!":e})}},t.prototype.text=function(e){if(0===this._currentList.length)this._currentList.push({"#":e});else{var t=this._currentList[this._currentList.length-1];this._isTextNode(t)?a.isArray(t["#"])?t["#"].push(e):t["#"]=[t["#"],e]:this._currentList.push({"#":e})}},t.prototype.instruction=function(e,t){var r=""===t?e:e+" "+t;if(0===this._currentList.length)this._currentList.push({"?":r});else{var n=this._currentList[this._currentList.length-1];this._isInstructionNode(n)?a.isArray(n["?"])?n["?"].push(r):n["?"]=[n["?"],r]:this._currentList.push({"?":r})}},t.prototype.cdata=function(e){if(0===this._currentList.length)this._currentList.push({$:e});else{var t=this._currentList[this._currentList.length-1];this._isCDATANode(t)?a.isArray(t.$)?t.$.push(e):t.$=[t.$,e]:this._currentList.push({$:e})}},t.prototype._isAttrNode=function(e){return"@"in e},t.prototype._isTextNode=function(e){return"#"in e},t.prototype._isCommentNode=function(e){return"!"in e},t.prototype._isInstructionNode=function(e){return"?"in e},t.prototype._isCDATANode=function(e){return"$"in e},t.prototype._isElementNode=function(e,t){return t in e},t.prototype._getAttrKey=function(){return this._builderOptions.convert.att},t.prototype._getNodeKey=function(e){switch(e){case s.NodeType.Comment:return this._builderOptions.convert.comment;case s.NodeType.Text:return this._builderOptions.convert.text;case s.NodeType.ProcessingInstruction:return this._builderOptions.convert.ins;case s.NodeType.CData:return this._builderOptions.convert.cdata;default:throw new Error("Invalid node type.")}},t}(r(50).BaseWriter);t.ObjectWriter=l},function(e,t,r){"use strict";var n=r(4),o=r(93);n({target:"RegExp",proto:!0,forced:/./.exec!==o},{exec:o})},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(){this._items={},this._nullItems={}}return e.prototype.set=function(e,t){null===e?this._nullItems[t]=!0:(this._items[e]||(this._items[e]={}),this._items[e][t]=!0)},e.prototype.has=function(e,t){return null===e?!0===this._nullItems[t]:!!this._items[e]&&!0===this._items[e][t]},e}();t.LocalNameSet=n},function(e,t,r){"use strict";var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a};Object.defineProperty(t,"__esModule",{value:!0});var o=r(9),i=r(3),a=r(0),s=function(){function e(){}return Object.defineProperty(e.prototype,"_eventListenerList",{get:function(){return this.__eventListenerList||(this.__eventListenerList=[])},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_eventHandlerMap",{get:function(){return this.__eventHandlerMap||(this.__eventHandlerMap={})},enumerable:!0,configurable:!0}),e.prototype.addEventListener=function(e,t,r){void 0===r&&(r={passive:!1,once:!1,capture:!1});var o,s=n(a.eventTarget_flattenMore(r),3),l=s[0],u=s[1],c=s[2];t&&(o=i.Guard.isEventListener(t)?t:{handleEvent:t},a.eventTarget_addEventListener(this,{type:e,callback:o,capture:l,passive:u,once:c,removed:!1}))},e.prototype.removeEventListener=function(e,t,r){void 0===r&&(r={capture:!1});var n=a.eventTarget_flatten(r);if(t)for(var o=0;o=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},o=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a},i=this&&this.__spread||function(){for(var e=[],t=0;t",amp:"&",quot:'"',apos:"'"},e}();t.BaseReader=o},function(e,t,r){"use strict";var n=r(39);e.exports=n.DEFAULT=new n({include:[r(54)],explicit:[r(299),r(300),r(301)]})},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(185);t.XMLBuilderImpl=n.XMLBuilderImpl;var o=r(304);t.XMLBuilderCBImpl=o.XMLBuilderCBImpl;var i=r(183);t.builder=i.builder,t.create=i.create,t.fragment=i.fragment,t.convert=i.convert;var a=r(309);t.createCB=a.createCB,t.fragmentCB=a.fragmentCB},function(e,t){var r;r=function(){return this}();try{r=r||new Function("return this")()}catch(e){"object"==typeof window&&(r=window)}e.exports=r},function(e,t,r){"use strict";var n={}.propertyIsEnumerable,o=Object.getOwnPropertyDescriptor,i=o&&!n.call({1:2},1);t.f=i?function(e){var t=o(this,e);return!!t&&t.enumerable}:n},function(e,t,r){var n=r(11),o=r(21);e.exports=function(e,t){try{o(n,e,t)}catch(r){n[e]=t}return t}},function(e,t,r){var n=r(44),o=r(118);(e.exports=function(e,t){return o[e]||(o[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.6.5",mode:n?"pure":"global",copyright:"© 2020 Denis Pushkarev (zloirock.ru)"})},function(e,t,r){var n=r(121),o=r(84).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return n(e,o)}},function(e,t,r){var n=r(47),o=Math.max,i=Math.min;e.exports=function(e,t){var r=n(e);return r<0?o(r+t,0):i(r,t)}},function(e,t){e.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t,r){var n=r(8);e.exports=!!Object.getOwnPropertySymbols&&!n(function(){return!String(Symbol())})},function(e,t,r){var n=r(127);e.exports=function(e,t,r){if(n(e),void 0===t)return e;switch(r){case 0:return function(){return e.call(t)};case 1:return function(r){return e.call(t,r)};case 2:return function(r,n){return e.call(t,r,n)};case 3:return function(r,n,o){return e.call(t,r,n,o)}}return function(){return e.apply(t,arguments)}}},function(e,t,r){"use strict";var n=r(4),o=r(195),i=r(132),a=r(133),s=r(62),l=r(21),u=r(25),c=r(5),d=r(44),p=r(49),f=r(131),h=f.IteratorPrototype,m=f.BUGGY_SAFARI_ITERATORS,g=c("iterator"),y=function(){return this};e.exports=function(e,t,r,c,f,v,b){o(r,t,c);var x,_,S,C=function(e){if(e===f&&D)return D;if(!m&&e in A)return A[e];switch(e){case"keys":case"values":case"entries":return function(){return new r(this,e)}}return function(){return new r(this)}},T=t+" Iterator",w=!1,A=e.prototype,E=A[g]||A["@@iterator"]||f&&A[f],D=!m&&E||C(f),P="Array"==t&&A.entries||E;if(P&&(x=i(P.call(new e)),h!==Object.prototype&&x.next&&(d||i(x)===h||(a?a(x,h):"function"!=typeof x[g]&&l(x,g,y)),s(x,T,!0,!0),d&&(p[T]=y))),"values"==f&&E&&"values"!==E.name&&(w=!0,D=function(){return E.call(this)}),d&&!b||A[g]===D||l(A,g,D),p[t]=D,f)if(_={values:C("values"),keys:v?D:C("keys"),entries:C("entries")},b)for(S in _)(m||w||!(S in A))&&u(A,S,_[S]);else n({target:t,proto:!0,forced:m||w},_);return _}},function(e,t,r){"use strict";var n=r(4),o=r(13),i=r(59),a=r(83),s=r(26),l=r(24),u=r(134),c=r(5),d=r(63),p=r(28),f=d("slice"),h=p("slice",{ACCESSORS:!0,0:0,1:2}),m=c("species"),g=[].slice,y=Math.max;n({target:"Array",proto:!0,forced:!f||!h},{slice:function(e,t){var r,n,c,d=l(this),p=s(d.length),f=a(e,p),h=a(void 0===t?p:t,p);if(i(d)&&("function"!=typeof(r=d.constructor)||r!==Array&&!i(r.prototype)?o(r)&&null===(r=r[m])&&(r=void 0):r=void 0,r===Array||void 0===r))return g.call(d,f,h);for(n=new(void 0===r?Array:r)(y(h-f,0)),c=0;f0&&(!a.multiline||a.multiline&&"\n"!==e[a.lastIndex-1])&&(h="(?: "+h+")",g=" "+g,m++),r=new RegExp("^(?:"+h+")",f)),p&&(r=new RegExp("^"+h+"$(?!\\s)",f)),c&&(t=a.lastIndex),n=s.call(u?r:a,g),u?n?(n.input=n.input.slice(m),n[0]=n[0].slice(m),n.index=a.lastIndex,a.lastIndex+=n[0].length):a.lastIndex=0:c&&n&&(a.lastIndex=a.global?n.index+n[0].length:t),p&&n&&n.length>1&&l.call(n[0],r,function(){for(o=1;o]*>)/g,m=/\$([$&'`]|\d\d?)/g;n("replace",2,function(e,t,r,n){var g=n.REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE,y=n.REPLACE_KEEPS_$0,v=g?"$":"$0";return[function(r,n){var o=l(this),i=null==r?void 0:r[e];return void 0!==i?i.call(r,o,n):t.call(String(o),r,n)},function(e,n){if(!g&&y||"string"==typeof n&&-1===n.indexOf(v)){var i=r(t,e,this,n);if(i.done)return i.value}var l=o(e),f=String(this),h="function"==typeof n;h||(n=String(n));var m=l.global;if(m){var x=l.unicode;l.lastIndex=0}for(var _=[];;){var S=c(l,f);if(null===S)break;if(_.push(S),!m)break;""===String(S[0])&&(l.lastIndex=u(f,a(l.lastIndex),x))}for(var C,T="",w=0,A=0;A<_.length;A++){S=_[A];for(var E=String(S[0]),D=d(p(s(S.index),f.length),0),P=[],I=1;I=w&&(T+=f.slice(w,D)+M,w=D+E.length)}return T+f.slice(w)}];function b(e,r,n,o,a,s){var l=n+e.length,u=o.length,c=m;return void 0!==a&&(a=i(a),c=h),t.call(s,c,function(t,i){var s;switch(i.charAt(0)){case"$":return"$";case"&":return e;case"`":return r.slice(0,n);case"'":return r.slice(l);case"<":s=a[i.slice(1,-1)];break;default:var c=+i;if(0===c)return t;if(c>u){var d=f(c/10);return 0===d?t:d<=u?void 0===o[d-1]?i.charAt(1):o[d-1]+i.charAt(1):t}s=o[c-1]}return void 0===s?"":s})}})},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(){this._items={},this._nullItems=[]}return e.prototype.copy=function(){var t=new e;for(var r in this._items)t._items[r]=this._items[r].slice(0);return t._nullItems=this._nullItems.slice(0),t},e.prototype.get=function(e,t){var r=null===t?this._nullItems:this._items[t]||null;if(null===r)return null;for(var n=null,o=0;o=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},o=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a},i=this&&this.__spread||function(){for(var e=[],t=0;t=0;M--)if(null!==(F=N[M]).shadowAdjustedTarget){O=F;break}if(null!==O)if(l.Guard.isNode(O.shadowAdjustedTarget)&&l.Guard.isShadowRoot(p.tree_rootNode(O.shadowAdjustedTarget,!0)))d=!0;else if(l.Guard.isNode(O.relatedTarget)&&l.Guard.isShadowRoot(p.tree_rootNode(O.relatedTarget,!0)))d=!0;else for(var R=0;R=0;M--)null!==(F=N[M]).shadowAdjustedTarget?e._eventPhase=s.EventPhase.AtTarget:e._eventPhase=s.EventPhase.Capturing,b(F,e,"capturing",o);for(M=0;M0&&null!==(l=o[a-1]).shadowAdjustedTarget)&&(t._target=l.shadowAdjustedTarget)}if(t._relatedTarget=e.relatedTarget,t._touchTargetList=e.touchTargetList,!t._stopPropagationFlag){t._currentTarget=e.invocationTarget;var u=t._currentTarget._eventListenerList,c=new(Array.bind.apply(Array,i([void 0],u)));if(!x(t,c,r,e,n)&&t._isTrusted){var d=t._type;"animationend"===d?t._type="webkitAnimationEnd":"animationiteration"===d?t._type="webkitAnimationIteration":"animationstart"===d?t._type="webkitAnimationStart":"transitionend"===d&&(t._type="webkitTransitionEnd"),x(t,c,r,e,n),t._type=d}}}function x(e,t,r,n,o){void 0===o&&(o={value:!1});for(var i=!1,a=0;a=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a};Object.defineProperty(t,"__esModule",{value:!0});var s=r(6),l=r(2),u=r(9),c=r(34),d=r(3),p=r(1),f=r(7),h=r(152),m=r(0),g=r(12),y=function(e){function t(){var t=e.call(this)||this;return t._children=new Set,t._encoding={name:"UTF-8",labels:["unicode-1-1-utf-8","utf-8","utf8"]},t._contentType="application/xml",t._URL={scheme:"about",username:"",password:"",host:null,port:null,path:["blank"],query:null,fragment:null,_cannotBeABaseURLFlag:!0,_blobURLEntry:null},t._origin=null,t._type="xml",t._mode="no-quirks",t._documentElement=null,t._hasNamespaces=!1,t._nodeDocumentOverwrite=null,t}return o(t,e),Object.defineProperty(t.prototype,"_nodeDocument",{get:function(){return this._nodeDocumentOverwrite||this},set:function(e){this._nodeDocumentOverwrite=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"implementation",{get:function(){return this._implementation||(this._implementation=m.create_domImplementation(this))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"URL",{get:function(){return h.urlSerializer(this._URL)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"documentURI",{get:function(){return this.URL},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"origin",{get:function(){return"null"},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"compatMode",{get:function(){return"quirks"===this._mode?"BackCompat":"CSS1Compat"},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"characterSet",{get:function(){return this._encoding.name},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"charset",{get:function(){return this._encoding.name},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputEncoding",{get:function(){return this._encoding.name},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"contentType",{get:function(){return this._contentType},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"doctype",{get:function(){var e,t;try{for(var r=i(this._children),n=r.next();!n.done;n=r.next()){var o=n.value;if(d.Guard.isDocumentTypeNode(o))return o}}catch(t){e={error:t}}finally{try{n&&!n.done&&(t=r.return)&&t.call(r)}finally{if(e)throw e.error}}return null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"documentElement",{get:function(){return this._documentElement},enumerable:!0,configurable:!0}),t.prototype.getElementsByTagName=function(e){return m.node_listOfElementsWithQualifiedName(e,this)},t.prototype.getElementsByTagNameNS=function(e,t){return m.node_listOfElementsWithNamespace(e,t,this)},t.prototype.getElementsByClassName=function(e){return m.node_listOfElementsWithClassNames(e,this)},t.prototype.createElement=function(e,t){if(!m.xml_isName(e))throw new u.InvalidCharacterError;"html"===this._type&&(e=e.toLowerCase());var r=null;void 0!==t&&(r=p.isString(t)?t:t.is);var n="html"===this._type||"application/xhtml+xml"===this._contentType?f.namespace.HTML:null;return m.element_createAnElement(this,e,n,null,r,!0)},t.prototype.createElementNS=function(e,t,r){return m.document_internalCreateElementNS(this,e,t,r)},t.prototype.createDocumentFragment=function(){return m.create_documentFragment(this)},t.prototype.createTextNode=function(e){return m.create_text(this,e)},t.prototype.createCDATASection=function(e){if("html"===this._type)throw new u.NotSupportedError;if(-1!==e.indexOf("]]>"))throw new u.InvalidCharacterError;return m.create_cdataSection(this,e)},t.prototype.createComment=function(e){return m.create_comment(this,e)},t.prototype.createProcessingInstruction=function(e,t){if(!m.xml_isName(e))throw new u.InvalidCharacterError;if(-1!==t.indexOf("?>"))throw new u.InvalidCharacterError;return m.create_processingInstruction(this,e,t)},t.prototype.importNode=function(e,t){if(void 0===t&&(t=!1),d.Guard.isDocumentNode(e)||d.Guard.isShadowRoot(e))throw new u.NotSupportedError;return m.node_clone(e,this,t)},t.prototype.adoptNode=function(e){if(d.Guard.isDocumentNode(e))throw new u.NotSupportedError;if(d.Guard.isShadowRoot(e))throw new u.HierarchyRequestError;return m.document_adopt(e,this),e},t.prototype.createAttribute=function(e){if(!m.xml_isName(e))throw new u.InvalidCharacterError;return"html"===this._type&&(e=e.toLowerCase()),m.create_attr(this,e)},t.prototype.createAttributeNS=function(e,t){var r=a(m.namespace_validateAndExtract(e,t),3),n=r[0],o=r[1],i=r[2],s=m.create_attr(this,i);return s._namespace=n,s._namespacePrefix=o,s},t.prototype.createEvent=function(e){return m.event_createLegacyEvent(e)},t.prototype.createRange=function(){var e=m.create_range();return e._start=[this,0],e._end=[this,0],e},t.prototype.createNodeIterator=function(e,t,r){void 0===t&&(t=l.WhatToShow.All),void 0===r&&(r=null);var n=m.create_nodeIterator(e,e,!0);return n._whatToShow=t,n._iteratorCollection=m.create_nodeList(e),p.isFunction(r)?(n._filter=m.create_nodeFilter(),n._filter.acceptNode=r):n._filter=r,n},t.prototype.createTreeWalker=function(e,t,r){void 0===t&&(t=l.WhatToShow.All),void 0===r&&(r=null);var n=m.create_treeWalker(e,e);return n._whatToShow=t,p.isFunction(r)?(n._filter=m.create_nodeFilter(),n._filter.acceptNode=r):n._filter=r,n},t.prototype._getTheParent=function(e){return"load"===e._type?null:s.dom.window},t.prototype.getElementById=function(e){throw new Error("Mixin: NonElementParentNode not implemented.")},Object.defineProperty(t.prototype,"children",{get:function(){throw new Error("Mixin: ParentNode not implemented.")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"firstElementChild",{get:function(){throw new Error("Mixin: ParentNode not implemented.")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"lastElementChild",{get:function(){throw new Error("Mixin: ParentNode not implemented.")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"childElementCount",{get:function(){throw new Error("Mixin: ParentNode not implemented.")},enumerable:!0,configurable:!0}),t.prototype.prepend=function(){for(var e=[],t=0;t=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a};Object.defineProperty(t,"__esModule",{value:!0});var s=r(2),l=r(34),u=r(9),c=r(7),d=r(0),p=r(12),f=function(e){function t(){var t=e.call(this)||this;return t._children=new Set,t._namespace=null,t._namespacePrefix=null,t._localName="",t._customElementState="undefined",t._customElementDefinition=null,t._is=null,t._shadowRoot=null,t._attributeList=d.create_namedNodeMap(t),t._attributeChangeSteps=[],t._name="",t._assignedSlot=null,t}return o(t,e),Object.defineProperty(t.prototype,"namespaceURI",{get:function(){return this._namespace},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"prefix",{get:function(){return this._namespacePrefix},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"localName",{get:function(){return this._localName},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"tagName",{get:function(){return this._htmlUppercasedQualifiedName},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"id",{get:function(){return d.element_getAnAttributeValue(this,"id")},set:function(e){d.element_setAnAttributeValue(this,"id",e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"className",{get:function(){return d.element_getAnAttributeValue(this,"class")},set:function(e){d.element_setAnAttributeValue(this,"class",e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"classList",{get:function(){var e=d.element_getAnAttributeByName("class",this);return null===e&&(e=d.create_attr(this._nodeDocument,"class")),d.create_domTokenList(this,e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"slot",{get:function(){return d.element_getAnAttributeValue(this,"slot")},set:function(e){d.element_setAnAttributeValue(this,"slot",e)},enumerable:!0,configurable:!0}),t.prototype.hasAttributes=function(){return 0!==this._attributeList.length},Object.defineProperty(t.prototype,"attributes",{get:function(){return this._attributeList},enumerable:!0,configurable:!0}),t.prototype.getAttributeNames=function(){var e,t,r=[];try{for(var n=i(this._attributeList),o=n.next();!o.done;o=n.next()){var a=o.value;r.push(a._qualifiedName)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}return r},t.prototype.getAttribute=function(e){var t=d.element_getAnAttributeByName(e,this);return t?t._value:null},t.prototype.getAttributeNS=function(e,t){var r=d.element_getAnAttributeByNamespaceAndLocalName(e,t,this);return r?r._value:null},t.prototype.setAttribute=function(e,t){if(!d.xml_isName(e))throw new u.InvalidCharacterError;this._namespace===c.namespace.HTML&&"html"===this._nodeDocument._type&&(e=e.toLowerCase());for(var r=null,n=0;n=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var a=r(2),s=r(71),l=r(0),u=r(12),c=function(e){function t(t){void 0===t&&(t="");var r=e.call(this,t)||this;return r._name="",r._assignedSlot=null,r}return o(t,e),Object.defineProperty(t.prototype,"wholeText",{get:function(){var e,t,r="";try{for(var n=i(l.text_contiguousTextNodes(this,!0)),o=n.next();!o.done;o=n.next())r+=o.value._data}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}return r},enumerable:!0,configurable:!0}),t.prototype.splitText=function(e){return l.text_split(this,e)},Object.defineProperty(t.prototype,"assignedSlot",{get:function(){throw new Error("Mixin: Slotable not implemented.")},enumerable:!0,configurable:!0}),t._create=function(e,r){void 0===r&&(r="");var n=new t(r);return n._nodeDocument=e,n},t}(s.CharacterDataImpl);t.TextImpl=c,u.idl_defineConst(c.prototype,"_nodeType",a.NodeType.Text)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(){}return Object.defineProperty(e.prototype,"_startNode",{get:function(){return this._start[0]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_startOffset",{get:function(){return this._start[1]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_endNode",{get:function(){return this._end[0]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_endOffset",{get:function(){return this._end[1]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_collapsed",{get:function(){return this._start[0]===this._end[0]&&this._start[1]===this._end[1]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"startContainer",{get:function(){return this._startNode},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"startOffset",{get:function(){return this._startOffset},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"endContainer",{get:function(){return this._endNode},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"endOffset",{get:function(){return this._endOffset},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"collapsed",{get:function(){return this._collapsed},enumerable:!0,configurable:!0}),e}();t.AbstractRangeImpl=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(2),o=function(){function e(e){this._activeFlag=!1,this._root=e,this._whatToShow=n.WhatToShow.All,this._filter=null}return Object.defineProperty(e.prototype,"root",{get:function(){return this._root},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"whatToShow",{get:function(){return this._whatToShow},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"filter",{get:function(){return this._filter},enumerable:!0,configurable:!0}),e}();t.TraverserImpl=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(2),o=r(0),i=r(12),a=function(){function e(e,t){this._target=null,this._relatedTarget=null,this._touchTargetList=[],this._path=[],this._currentTarget=null,this._eventPhase=n.EventPhase.None,this._stopPropagationFlag=!1,this._stopImmediatePropagationFlag=!1,this._canceledFlag=!1,this._inPassiveListenerFlag=!1,this._composedFlag=!1,this._initializedFlag=!1,this._dispatchFlag=!1,this._isTrusted=!1,this._bubbles=!1,this._cancelable=!1,this._type=e,t&&(this._bubbles=t.bubbles||!1,this._cancelable=t.cancelable||!1,this._composedFlag=t.composed||!1),this._initializedFlag=!0,this._timeStamp=(new Date).getTime()}return Object.defineProperty(e.prototype,"type",{get:function(){return this._type},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"target",{get:function(){return this._target},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"srcElement",{get:function(){return this._target},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"currentTarget",{get:function(){return this._currentTarget},enumerable:!0,configurable:!0}),e.prototype.composedPath=function(){var e=[],t=this._path;if(0===t.length)return e;var r=this._currentTarget;if(null===r)throw new Error("Event currentTarget is null.");e.push(r);for(var n=0,o=0,i=t.length-1;i>=0;){if(t[i].rootOfClosedTree&&o++,t[i].invocationTarget===r){n=i;break}t[i].slotInClosedTree&&o--,i--}var a=o,s=o;for(i=n-1;i>=0;)t[i].rootOfClosedTree&&a++,a<=s&&e.unshift(t[i].invocationTarget),t[i].slotInClosedTree&&--a0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a},o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var i=r(6),a=r(3),s=r(1),l=r(99),u=r(73),c=r(17),d=r(173),p=r(30),f=r(52),h=r(37);t.document_elementInterface=function(e,t){return l.ElementImpl},t.document_internalCreateElementNS=function(e,t,r,o){var i=n(d.namespace_validateAndExtract(t,r),3),a=i[0],l=i[1],u=i[2],c=null;return void 0!==o&&(c=s.isString(o)?o:o.is),f.element_createAnElement(e,u,a,l,c,!0)},t.document_adopt=function(e,t){var r,n;if(e._nodeDocument!==t||null!==e._parent){var s=e._nodeDocument;if(e._parent&&h.mutation_remove(e,e._parent),t!==s)for(var l=c.tree_getFirstDescendantNode(e,!0,!0);null!==l;){if(l._nodeDocument=t,a.Guard.isElementNode(l))try{for(var d=(r=void 0,o(l._attributeList._asArray())),f=d.next();!f.done;f=d.next())f.value._nodeDocument=t}catch(e){r={error:e}}finally{try{f&&!f.done&&(n=d.return)&&n.call(d)}finally{if(r)throw r.error}}i.dom.features.customElements&&a.Guard.isElementNode(l)&&"custom"===l._customElementState&&u.customElement_enqueueACustomElementCallbackReaction(l,"adoptedCallback",[s,t]),i.dom.features.steps&&p.dom_runAdoptingSteps(l,s),l=c.tree_getNextDescendantNode(e,l,!0,!0)}}}},function(e,t,r){"use strict";var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var o=r(6),i=r(3),a=r(9),s=r(17),l=r(51),u=r(30);t.characterData_replaceData=function(e,t,r,c){var d,p,f=s.tree_nodeLength(e);if(t>f)throw new a.IndexSizeError("Offset exceeds character data length. Offset: "+t+", Length: "+f+", Node is "+e.nodeName+".");t+r>f&&(r=f-t),o.dom.features.mutationObservers&&l.observer_queueMutationRecord("characterData",e,null,null,e._data,[],[],null,null);var h=e._data.substring(0,t)+c+e._data.substring(t+r);e._data=h;try{for(var m=n(o.dom.rangeList),g=m.next();!g.done;g=m.next()){var y=g.value;y._start[0]===e&&y._start[1]>t&&y._start[1]<=t+r&&(y._start[1]=t),y._end[0]===e&&y._end[1]>t&&y._end[1]<=t+r&&(y._end[1]=t),y._start[0]===e&&y._start[1]>t+r&&(y._start[1]+=c.length-r),y._end[0]===e&&y._end[1]>t+r&&(y._end[1]+=c.length-r)}}catch(e){d={error:e}}finally{try{g&&!g.done&&(p=m.return)&&p.call(m)}finally{if(d)throw d.error}}o.dom.features.steps&&i.Guard.isTextNode(e)&&null!==e._parent&&u.dom_runChildTextContentChangeSteps(e._parent)},t.characterData_substringData=function(e,t,r){var n=s.tree_nodeLength(e);if(t>n)throw new a.IndexSizeError("Offset exceeds character data length. Offset: "+t+", Length: "+n+", Node is "+e.nodeName+".");return t+r>n?e._data.substr(t):e._data.substr(t,r)}},function(e,t,r){"use strict";var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a},o=this&&this.__spread||function(){for(var e=[],t=0;t=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var a=r(7);function s(e){var t=a.string.splitAStringOnASCIIWhitespace(e);return new Set(t)}function l(e){return o(e).join(" ")}t.orderedSet_parse=s,t.orderedSet_serialize=l,t.orderedSet_sanitize=function(e){return l(s(e))},t.orderedSet_contains=function(e,t,r){var n,o,a,s;try{for(var l=i(t),u=l.next();!u.done;u=l.next()){var c=u.value,d=!1;try{for(var p=(a=void 0,i(e)),f=p.next();!f.done;f=p.next()){var h=f.value;if(r){if(h===c){d=!0;break}}else if(h.toUpperCase()===c.toUpperCase()){d=!0;break}}}catch(e){a={error:e}}finally{try{f&&!f.done&&(s=p.return)&&s.call(p)}finally{if(a)throw a.error}}if(!d)return!1}}catch(e){n={error:e}}finally{try{u&&!u.done&&(o=l.return)&&o.call(l)}finally{if(n)throw n.error}}return!0}},function(e,t,r){"use strict";r(179),Object.defineProperty(t,"__esModule",{value:!0});var n=r(262),o=r(110),i=r(1);o.dom.setFeatures(!1),t.createDocument=function(){var e=(new n.DOMImplementation).createDocument(null,"root",null);return e.documentElement&&e.removeChild(e.documentElement),e},t.sanitizeInput=function(e,t){if(null==e)return e;if(void 0===t)return e+"";var r="";e+="";for(var n=0;n=32&&o<=55295||o>=57344&&o<=65533)r+=e.charAt(n);else if(o>=55296&&o<=56319&&n=56320&&a<=57343?(o=1024*(o-55296)+a-56320+65536,r+=String.fromCodePoint(o),n++):r+=i.isString(t)?t:t(e.charAt(n),n,e)}else r+=i.isString(t)?t:t(e.charAt(n),n,e)}return r}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(1),o=r(153);t.AbortController=o.AbortControllerImpl;var i=r(154);t.AbortSignal=i.AbortSignalImpl;var a=r(102);t.AbstractRange=a.AbstractRangeImpl;var s=r(157);t.Attr=s.AttrImpl;var l=r(158);t.CDATASection=l.CDATASectionImpl;var u=r(71);t.CharacterData=u.CharacterDataImpl;var c=r(263),d=r(159);t.Comment=d.CommentImpl;var p=r(171);t.CustomEvent=p.CustomEventImpl;var f=r(100);t.DocumentFragment=f.DocumentFragmentImpl;var h=r(98);t.Document=h.DocumentImpl;var m=r(264),g=r(155);t.DocumentType=g.DocumentTypeImpl;var y=r(6);t.dom=y.dom;var v=r(148);t.DOMImplementation=v.DOMImplementationImpl;var b=r(170);t.DOMTokenList=b.DOMTokenListImpl;var x=r(99);t.Element=x.ElementImpl;var _=r(104);t.Event=_.EventImpl;var S=r(70);t.EventTarget=S.EventTargetImpl;var C=r(161);t.HTMLCollection=C.HTMLCollectionImpl;var T=r(265);t.MutationObserver=T.MutationObserverImpl;var w=r(169);t.MutationRecord=w.MutationRecordImpl;var A=r(164);t.NamedNodeMap=A.NamedNodeMapImpl;var E=r(168);t.NodeFilter=E.NodeFilterImpl;var D=r(34);t.Node=D.NodeImpl;var P=r(166);t.NodeIterator=P.NodeIteratorImpl;var I=r(162);t.NodeList=I.NodeListImpl;var O=r(163);t.NodeListStatic=O.NodeListStaticImpl;var N=r(266),M=r(267),R=r(268),F=r(160);t.ProcessingInstruction=F.ProcessingInstructionImpl;var B=r(165);t.Range=B.RangeImpl;var L=r(156);t.ShadowRoot=L.ShadowRootImpl;var k=r(269),U=r(270);t.StaticRange=U.StaticRangeImpl;var V=r(101);t.Text=V.TextImpl;var G=r(103);t.Traverser=G.TraverserImpl;var z=r(167);t.TreeWalker=z.TreeWalkerImpl;var j=r(149);t.Window=j.WindowImpl;var W=r(151);t.XMLDocument=W.XMLDocumentImpl,n.applyMixin(x.ElementImpl,c.ChildNodeImpl),n.applyMixin(u.CharacterDataImpl,c.ChildNodeImpl),n.applyMixin(g.DocumentTypeImpl,c.ChildNodeImpl),n.applyMixin(h.DocumentImpl,m.DocumentOrShadowRootImpl),n.applyMixin(L.ShadowRootImpl,m.DocumentOrShadowRootImpl),n.applyMixin(x.ElementImpl,N.NonDocumentTypeChildNodeImpl),n.applyMixin(u.CharacterDataImpl,N.NonDocumentTypeChildNodeImpl),n.applyMixin(h.DocumentImpl,M.NonElementParentNodeImpl),n.applyMixin(f.DocumentFragmentImpl,M.NonElementParentNodeImpl),n.applyMixin(h.DocumentImpl,R.ParentNodeImpl),n.applyMixin(f.DocumentFragmentImpl,R.ParentNodeImpl),n.applyMixin(x.ElementImpl,R.ParentNodeImpl),n.applyMixin(V.TextImpl,k.SlotableImpl),n.applyMixin(x.ElementImpl,k.SlotableImpl)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e[e.EOF=0]="EOF",e[e.Declaration=1]="Declaration",e[e.DocType=2]="DocType",e[e.Element=3]="Element",e[e.Text=4]="Text",e[e.CDATA=5]="CDATA",e[e.PI=6]="PI",e[e.Comment=7]="Comment",e[e.ClosingTag=8]="ClosingTag"}(t.TokenType||(t.TokenType={}))},function(e,t,r){"use strict";r(64),r(20),r(66);var n,o=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var i=r(1),a=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype._parse=function(e,t){var r=this,n=this._builderOptions,o=null;return i.isFunction(t)?o=this.parse(e,t.apply(this)):i.isArray(t)||i.isSet(t)?i.forEachArray(t,function(t){return o=r.parse(e,t)},this):i.isMap(t)||i.isObject(t)?i.forEachObject(t,function(t,a){if(i.isFunction(a)&&(a=a.apply(r)),n.ignoreConverters||0!==t.indexOf(n.convert.att))if(n.ignoreConverters||0!==t.indexOf(n.convert.text))if(n.ignoreConverters||0!==t.indexOf(n.convert.cdata))if(n.ignoreConverters||0!==t.indexOf(n.convert.comment))if(n.ignoreConverters||0!==t.indexOf(n.convert.ins)){if((i.isArray(a)||i.isSet(a))&&i.isEmpty(a));else if((i.isMap(a)||i.isObject(a))&&i.isEmpty(a))o=r.element(e,void 0,r.sanitize(t))||o;else if(n.keepNullNodes||null!=a)if(i.isArray(a)||i.isSet(a))i.forEachArray(a,function(n){var i={};i[t]=n,o=r.parse(e,i)},r);else if(i.isMap(a)||i.isObject(a))(s=r.element(e,void 0,r.sanitize(t)))&&(o=s,r.parse(s,a));else if(null!=a&&""!==a){var s;(s=r.element(e,void 0,r.sanitize(t)))&&(o=s,r.text(s,r._decodeText(r.sanitize(a))))}else o=r.element(e,void 0,r.sanitize(t))||o}else if(i.isString(a)){var l=a.indexOf(" "),u=-1===l?a:a.substr(0,l),c=-1===l?"":a.substr(l+1);o=r.instruction(e,r.sanitize(u),r.sanitize(c))||o}else i.isArray(a)||i.isSet(a)?i.forEachArray(a,function(t){var n=t.indexOf(" "),i=-1===n?t:t.substr(0,n),a=-1===n?"":t.substr(n+1);o=r.instruction(e,r.sanitize(i),r.sanitize(a))||o},r):i.forEachObject(a,function(t,n){return o=r.instruction(e,r.sanitize(t),r.sanitize(n))||o},r);else i.isArray(a)||i.isSet(a)?i.forEachArray(a,function(t){return o=r.comment(e,r.sanitize(t))||o},r):o=r.comment(e,r.sanitize(a))||o;else i.isArray(a)||i.isSet(a)?i.forEachArray(a,function(t){return o=r.cdata(e,r.sanitize(t))||o},r):o=r.cdata(e,r.sanitize(a))||o;else o=i.isMap(a)||i.isObject(a)?r.parse(e,a):r.text(e,r._decodeText(r.sanitize(a)))||o;else if(t===n.convert.att){if(i.isArray(a)||i.isSet(a))throw new Error("Invalid attribute: "+a.toString()+". "+e._debugInfo());i.forEachObject(a,function(t,n){o=r.attribute(e,void 0,r.sanitize(t),r._decodeAttributeValue(r.sanitize(n)))||o})}else o=r.attribute(e,void 0,r.sanitize(t.substr(n.convert.att.length)),r._decodeAttributeValue(r.sanitize(a)))||o},this):(n.keepNullNodes||null!=t)&&(o=this.text(e,this._decodeText(this.sanitize(t)))||o),o||e},t}(r(75).BaseReader);t.ObjectReader=a},function(e,t,r){"use strict";var n=r(39);e.exports=new n({explicit:[r(286),r(287),r(288)]})},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.BaseCBWriter=function(e){this.level=0,this._builderOptions=e,this._writerOptions=e}},function(e,t,r){var n=r(16),o=r(8),i=r(116);e.exports=!n&&!o(function(){return 7!=Object.defineProperty(i("div"),"a",{get:function(){return 7}}).a})},function(e,t,r){var n=r(11),o=r(13),i=n.document,a=o(i)&&o(i.createElement);e.exports=function(e){return a?i.createElement(e):{}}},function(e,t,r){var n=r(118),o=Function.toString;"function"!=typeof n.inspectSource&&(n.inspectSource=function(e){return o.call(e)}),e.exports=n.inspectSource},function(e,t,r){var n=r(11),o=r(80),i=n["__core-js_shared__"]||o("__core-js_shared__",{});e.exports=i},function(e,t,r){var n=r(14),o=r(187),i=r(55),a=r(15);e.exports=function(e,t){for(var r=o(t),s=a.f,l=i.f,u=0;ul;)n(s,r=t[l++])&&(~i(u,r)||u.push(r));return u}},function(e,t,r){var n=r(24),o=r(26),i=r(83),a=function(e){return function(t,r,a){var s,l=n(t),u=o(l.length),c=i(a,u);if(e&&r!=r){for(;u>c;)if((s=l[c++])!=s)return!0}else for(;u>c;c++)if((e||c in l)&&l[c]===r)return e||c||0;return!e&&-1}};e.exports={includes:a(!0),indexOf:a(!1)}},function(e,t,r){var n=r(8),o=/#|\.prototype\./,i=function(e,t){var r=s[a(e)];return r==u||r!=l&&("function"==typeof t?n(t):!!t)},a=i.normalize=function(e){return String(e).replace(o,".").toLowerCase()},s=i.data={},l=i.NATIVE="N",u=i.POLYFILL="P";e.exports=i},function(e,t,r){var n=r(86);e.exports=n&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},function(e,t,r){var n=r(5);t.f=n},function(e,t,r){var n=r(120),o=r(14),i=r(125),a=r(15).f;e.exports=function(e){var t=n.Symbol||(n.Symbol={});o(t,e)||a(t,e,{value:i.f(e)})}},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(String(e)+" is not a function");return e}},function(e,t,r){var n=r(13),o=r(59),i=r(5)("species");e.exports=function(e,t){var r;return o(e)&&("function"!=typeof(r=e.constructor)||r!==Array&&!o(r.prototype)?n(r)&&null===(r=r[i])&&(r=void 0):r=void 0),new(void 0===r?Array:r)(0===t?0:t)}},function(e,t,r){var n,o,i=r(11),a=r(193),s=i.process,l=s&&s.versions,u=l&&l.v8;u?o=(n=u.split("."))[0]+n[1]:a&&(!(n=a.match(/Edge\/(\d+)/))||n[1]>=74)&&(n=a.match(/Chrome\/(\d+)/))&&(o=n[1]),e.exports=o&&+o},function(e,t,r){var n=r(5),o=r(60),i=r(15),a=n("unscopables"),s=Array.prototype;null==s[a]&&i.f(s,a,{configurable:!0,value:o(null)}),e.exports=function(e){s[a][e]=!0}},function(e,t,r){"use strict";var n,o,i,a=r(132),s=r(21),l=r(14),u=r(5),c=r(44),d=u("iterator"),p=!1;[].keys&&("next"in(i=[].keys())?(o=a(a(i)))!==Object.prototype&&(n=o):p=!0),null==n&&(n={}),c||l(n,d)||s(n,d,function(){return this}),e.exports={IteratorPrototype:n,BUGGY_SAFARI_ITERATORS:p}},function(e,t,r){var n=r(14),o=r(27),i=r(57),a=r(196),s=i("IE_PROTO"),l=Object.prototype;e.exports=a?Object.getPrototypeOf:function(e){return e=o(e),n(e,s)?e[s]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?l:null}},function(e,t,r){var n=r(18),o=r(197);e.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,r={};try{(e=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set).call(r,[]),t=r instanceof Array}catch(e){}return function(r,i){return n(r),o(i),t?e.call(r,i):r.__proto__=i,r}}():void 0)},function(e,t,r){"use strict";var n=r(56),o=r(15),i=r(40);e.exports=function(e,t,r){var a=n(t);a in e?o.f(e,a,i(0,r)):e[a]=r}},function(e,t,r){var n=r(90),o=r(42),i=r(5)("toStringTag"),a="Arguments"==o(function(){return arguments}());e.exports=n?o:function(e){var t,r,n;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(r=function(e,t){try{return e[t]}catch(e){}}(t=Object(e),i))?r:a?o(t):"Object"==(n=o(t))&&"function"==typeof t.callee?"Arguments":n}},function(e,t,r){"use strict";var n=r(18);e.exports=function(){var e=n(this),t="";return e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.sticky&&(t+="y"),t}},function(e,t,r){var n=r(47),o=r(35),i=function(e){return function(t,r){var i,a,s=String(o(t)),l=n(r),u=s.length;return l<0||l>=u?e?"":void 0:(i=s.charCodeAt(l))<55296||i>56319||l+1===u||(a=s.charCodeAt(l+1))<56320||a>57343?e?s.charAt(l):i:e?s.slice(l,l+2):a-56320+(i-55296<<10)+65536}};e.exports={codeAt:i(!1),charAt:i(!0)}},function(e,t,r){var n=r(4),o=r(27),i=r(61);n({target:"Object",stat:!0,forced:r(8)(function(){i(1)})},{keys:function(e){return i(o(e))}})},function(e,t,r){"use strict";var n=r(4),o=r(11),i=r(123),a=r(25),s=r(140),l=r(141),u=r(142),c=r(13),d=r(8),p=r(208),f=r(62),h=r(209);e.exports=function(e,t,r){var m=-1!==e.indexOf("Map"),g=-1!==e.indexOf("Weak"),y=m?"set":"add",v=o[e],b=v&&v.prototype,x=v,_={},S=function(e){var t=b[e];a(b,e,"add"==e?function(e){return t.call(this,0===e?0:e),this}:"delete"==e?function(e){return!(g&&!c(e))&&t.call(this,0===e?0:e)}:"get"==e?function(e){return g&&!c(e)?void 0:t.call(this,0===e?0:e)}:"has"==e?function(e){return!(g&&!c(e))&&t.call(this,0===e?0:e)}:function(e,r){return t.call(this,0===e?0:e,r),this})};if(i(e,"function"!=typeof v||!(g||b.forEach&&!d(function(){(new v).entries().next()}))))x=r.getConstructor(t,e,m,y),s.REQUIRED=!0;else if(i(e,!0)){var C=new x,T=C[y](g?{}:-0,1)!=C,w=d(function(){C.has(1)}),A=p(function(e){new v(e)}),E=!g&&d(function(){for(var e=new v,t=5;t--;)e[y](t,t);return!e.has(-0)});A||((x=t(function(t,r){u(t,x,e);var n=h(new v,t,x);return null!=r&&l(r,n[y],n,m),n})).prototype=b,b.constructor=x),(w||E)&&(S("delete"),S("has"),m&&S("get")),(E||T)&&S(y),g&&b.clear&&delete b.clear}return _[e]=x,n({global:!0,forced:x!=v},_),f(x,e),g||r.setStrong(x,e,m),x}},function(e,t,r){var n=r(45),o=r(13),i=r(14),a=r(15).f,s=r(58),l=r(204),u=s("meta"),c=0,d=Object.isExtensible||function(){return!0},p=function(e){a(e,u,{value:{objectID:"O"+ ++c,weakData:{}}})},f=e.exports={REQUIRED:!1,fastKey:function(e,t){if(!o(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!i(e,u)){if(!d(e))return"F";if(!t)return"E";p(e)}return e[u].objectID},getWeakData:function(e,t){if(!i(e,u)){if(!d(e))return!0;if(!t)return!1;p(e)}return e[u].weakData},onFreeze:function(e){return l&&f.REQUIRED&&d(e)&&!i(e,u)&&p(e),e}};n[u]=!0},function(e,t,r){var n=r(18),o=r(205),i=r(26),a=r(87),s=r(206),l=r(207),u=function(e,t){this.stopped=e,this.result=t};(e.exports=function(e,t,r,c,d){var p,f,h,m,g,y,v,b=a(t,r,c?2:1);if(d)p=e;else{if("function"!=typeof(f=s(e)))throw TypeError("Target is not iterable");if(o(f)){for(h=0,m=i(e.length);m>h;h++)if((g=c?b(n(v=e[h])[0],v[1]):b(e[h]))&&g instanceof u)return g;return new u(!1)}p=f.call(e)}for(y=p.next;!(v=y.call(p)).done;)if("object"==typeof(g=l(p,b,v.value,c))&&g&&g instanceof u)return g;return new u(!1)}).stop=function(e){return new u(!0,e)}},function(e,t){e.exports=function(e,t,r){if(!(e instanceof t))throw TypeError("Incorrect "+(r?r+" ":"")+"invocation");return e}},function(e,t,r){"use strict";var n=r(15).f,o=r(60),i=r(210),a=r(87),s=r(142),l=r(141),u=r(88),c=r(211),d=r(16),p=r(140).fastKey,f=r(43),h=f.set,m=f.getterFor;e.exports={getConstructor:function(e,t,r,u){var c=e(function(e,n){s(e,c,t),h(e,{type:t,index:o(null),first:void 0,last:void 0,size:0}),d||(e.size=0),null!=n&&l(n,e[u],e,r)}),f=m(t),g=function(e,t,r){var n,o,i=f(e),a=y(e,t);return a?a.value=r:(i.last=a={index:o=p(t,!0),key:t,value:r,previous:n=i.last,next:void 0,removed:!1},i.first||(i.first=a),n&&(n.next=a),d?i.size++:e.size++,"F"!==o&&(i.index[o]=a)),e},y=function(e,t){var r,n=f(e),o=p(t);if("F"!==o)return n.index[o];for(r=n.first;r;r=r.next)if(r.key==t)return r};return i(c.prototype,{clear:function(){for(var e=f(this),t=e.index,r=e.first;r;)r.removed=!0,r.previous&&(r.previous=r.previous.next=void 0),delete t[r.index],r=r.next;e.first=e.last=void 0,d?e.size=0:this.size=0},delete:function(e){var t=f(this),r=y(this,e);if(r){var n=r.next,o=r.previous;delete t.index[r.index],r.removed=!0,o&&(o.next=n),n&&(n.previous=o),t.first==r&&(t.first=n),t.last==r&&(t.last=o),d?t.size--:this.size--}return!!r},forEach:function(e){for(var t,r=f(this),n=a(e,arguments.length>1?arguments[1]:void 0,3);t=t?t.next:r.first;)for(n(t.value,t.key,this);t&&t.removed;)t=t.previous},has:function(e){return!!y(this,e)}}),i(c.prototype,r?{get:function(e){var t=y(this,e);return t&&t.value},set:function(e,t){return g(this,0===e?0:e,t)}}:{add:function(e){return g(this,e=0===e?0:e,e)}}),d&&n(c.prototype,"size",{get:function(){return f(this).size}}),c},setStrong:function(e,t,r){var n=t+" Iterator",o=m(t),i=m(n);u(e,t,function(e,t){h(this,{type:n,target:e,state:o(e),kind:t,last:void 0})},function(){for(var e=i(this),t=e.kind,r=e.last;r&&r.removed;)r=r.previous;return e.target&&(e.last=r=r?r.next:e.state.first)?"keys"==t?{value:r.key,done:!1}:"values"==t?{value:r.value,done:!1}:{value:[r.key,r.value],done:!1}:(e.target=void 0,{value:void 0,done:!0})},r?"entries":"values",!r,!0),c(t)}}},function(e,t,r){"use strict";var n,o=r(4),i=r(55).f,a=r(26),s=r(222),l=r(35),u=r(224),c=r(44),d="".endsWith,p=Math.min,f=u("endsWith");o({target:"String",proto:!0,forced:!(!c&&!f&&(n=i(String.prototype,"endsWith"),n&&!n.writable)||f)},{endsWith:function(e){var t=String(l(this));s(e);var r=arguments.length>1?arguments[1]:void 0,n=a(t.length),o=void 0===r?n:p(a(r),n),i=String(e);return d?d.call(t,i,o):t.slice(o-i.length,o)===i}})},function(e,t,r){"use strict";(function(e){var n=r(229),o=r(230),i=r(231);function a(){return l.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function s(e,t){if(a()=a())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a().toString(16)+" bytes");return 0|e}function h(e,t){if(l.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return V(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(n)return V(e).length;t=(""+t).toLowerCase(),n=!0}}function m(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return P(this,t,r);case"utf8":case"utf-8":return A(this,t,r);case"ascii":return E(this,t,r);case"latin1":case"binary":return D(this,t,r);case"base64":return w(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function g(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function y(e,t,r,n,o){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=l.from(t,n)),l.isBuffer(t))return 0===t.length?-1:v(e,t,r,n,o);if("number"==typeof t)return t&=255,l.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):v(e,[t],r,n,o);throw new TypeError("val must be string, number or Buffer")}function v(e,t,r,n,o){var i,a=1,s=e.length,l=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,l/=2,r/=2}function u(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(o){var c=-1;for(i=r;is&&(r=s-l),i=r;i>=0;i--){for(var d=!0,p=0;po&&(n=o):n=o;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");n>i/2&&(n=i/2);for(var a=0;a>8,o=r%256,i.push(o),i.push(n);return i}(t,e.length-r),e,r,n)}function w(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function A(e,t,r){r=Math.min(e.length,r);for(var n=[],o=t;o239?4:u>223?3:u>191?2:1;if(o+d<=r)switch(d){case 1:u<128&&(c=u);break;case 2:128==(192&(i=e[o+1]))&&(l=(31&u)<<6|63&i)>127&&(c=l);break;case 3:i=e[o+1],a=e[o+2],128==(192&i)&&128==(192&a)&&(l=(15&u)<<12|(63&i)<<6|63&a)>2047&&(l<55296||l>57343)&&(c=l);break;case 4:i=e[o+1],a=e[o+2],s=e[o+3],128==(192&i)&&128==(192&a)&&128==(192&s)&&(l=(15&u)<<18|(63&i)<<12|(63&a)<<6|63&s)>65535&&l<1114112&&(c=l)}null===c?(c=65533,d=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),o+=d}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);for(var r="",n=0;nn)&&(r=n);for(var o="",i=t;ir)throw new RangeError("Trying to access beyond buffer length")}function N(e,t,r,n,o,i){if(!l.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function M(e,t,r,n){t<0&&(t=65535+t+1);for(var o=0,i=Math.min(e.length-r,2);o>>8*(n?o:1-o)}function R(e,t,r,n){t<0&&(t=4294967295+t+1);for(var o=0,i=Math.min(e.length-r,4);o>>8*(n?o:3-o)&255}function F(e,t,r,n,o,i){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function B(e,t,r,n,i){return i||F(e,0,r,4),o.write(e,t,r,n,23,4),r+4}function L(e,t,r,n,i){return i||F(e,0,r,8),o.write(e,t,r,n,52,8),r+8}t.Buffer=l,t.SlowBuffer=function(e){return+e!=e&&(e=0),l.alloc(+e)},t.INSPECT_MAX_BYTES=50,l.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}(),t.kMaxLength=a(),l.poolSize=8192,l._augment=function(e){return e.__proto__=l.prototype,e},l.from=function(e,t,r){return u(null,e,t,r)},l.TYPED_ARRAY_SUPPORT&&(l.prototype.__proto__=Uint8Array.prototype,l.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&l[Symbol.species]===l&&Object.defineProperty(l,Symbol.species,{value:null,configurable:!0})),l.alloc=function(e,t,r){return function(e,t,r,n){return c(t),t<=0?s(e,t):void 0!==r?"string"==typeof n?s(e,t).fill(r,n):s(e,t).fill(r):s(e,t)}(null,e,t,r)},l.allocUnsafe=function(e){return d(null,e)},l.allocUnsafeSlow=function(e){return d(null,e)},l.isBuffer=function(e){return!(null==e||!e._isBuffer)},l.compare=function(e,t){if(!l.isBuffer(e)||!l.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,n=t.length,o=0,i=Math.min(r,n);o0&&(e=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(e+=" ... ")),""},l.prototype.compare=function(e,t,r,n,o){if(!l.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||r>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=r)return 0;if(n>=o)return-1;if(t>=r)return 1;if(this===e)return 0;for(var i=(o>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0),s=Math.min(i,a),u=this.slice(n,o),c=e.slice(t,r),d=0;do)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return b(this,e,t,r);case"utf8":case"utf-8":return x(this,e,t,r);case"ascii":return _(this,e,t,r);case"latin1":case"binary":return S(this,e,t,r);case"base64":return C(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,e,t,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},l.prototype.slice=function(e,t){var r,n=this.length;if((e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t0&&(o*=256);)n+=this[e+--t]*o;return n},l.prototype.readUInt8=function(e,t){return t||O(e,1,this.length),this[e]},l.prototype.readUInt16LE=function(e,t){return t||O(e,2,this.length),this[e]|this[e+1]<<8},l.prototype.readUInt16BE=function(e,t){return t||O(e,2,this.length),this[e]<<8|this[e+1]},l.prototype.readUInt32LE=function(e,t){return t||O(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},l.prototype.readUInt32BE=function(e,t){return t||O(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},l.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||O(e,t,this.length);for(var n=this[e],o=1,i=0;++i=(o*=128)&&(n-=Math.pow(2,8*t)),n},l.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||O(e,t,this.length);for(var n=t,o=1,i=this[e+--n];n>0&&(o*=256);)i+=this[e+--n]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*t)),i},l.prototype.readInt8=function(e,t){return t||O(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},l.prototype.readInt16LE=function(e,t){t||O(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},l.prototype.readInt16BE=function(e,t){t||O(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},l.prototype.readInt32LE=function(e,t){return t||O(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},l.prototype.readInt32BE=function(e,t){return t||O(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},l.prototype.readFloatLE=function(e,t){return t||O(e,4,this.length),o.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return t||O(e,4,this.length),o.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return t||O(e,8,this.length),o.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return t||O(e,8,this.length),o.read(this,e,!1,52,8)},l.prototype.writeUIntLE=function(e,t,r,n){e=+e,t|=0,r|=0,n||N(this,e,t,r,Math.pow(2,8*r)-1,0);var o=1,i=0;for(this[t]=255&e;++i=0&&(i*=256);)this[t+o]=e/i&255;return t+r},l.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||N(this,e,t,1,255,0),l.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},l.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||N(this,e,t,2,65535,0),l.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):M(this,e,t,!0),t+2},l.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||N(this,e,t,2,65535,0),l.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):M(this,e,t,!1),t+2},l.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||N(this,e,t,4,4294967295,0),l.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):R(this,e,t,!0),t+4},l.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||N(this,e,t,4,4294967295,0),l.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):R(this,e,t,!1),t+4},l.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var o=Math.pow(2,8*r-1);N(this,e,t,r,o-1,-o)}var i=0,a=1,s=0;for(this[t]=255&e;++i=0&&(a*=256);)e<0&&0===s&&0!==this[t+i+1]&&(s=1),this[t+i]=(e/a|0)-s&255;return t+r},l.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||N(this,e,t,1,127,-128),l.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},l.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||N(this,e,t,2,32767,-32768),l.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):M(this,e,t,!0),t+2},l.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||N(this,e,t,2,32767,-32768),l.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):M(this,e,t,!1),t+2},l.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||N(this,e,t,4,2147483647,-2147483648),l.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):R(this,e,t,!0),t+4},l.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),l.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):R(this,e,t,!1),t+4},l.prototype.writeFloatLE=function(e,t,r){return B(this,e,t,!0,r)},l.prototype.writeFloatBE=function(e,t,r){return B(this,e,t,!1,r)},l.prototype.writeDoubleLE=function(e,t,r){return L(this,e,t,!0,r)},l.prototype.writeDoubleBE=function(e,t,r){return L(this,e,t,!1,r)},l.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--o)e[o+t]=this[o+r];else if(i<1e3||!l.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function G(e){return n.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(k,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function z(e,t,r,n){for(var o=0;o=t.length||o>=e.length);++o)t[o+r]=e[o];return o}}).call(this,r(78))},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isASCIIByte=function(e){return e>=0&&e<=127}},function(e,t,r){"use strict";var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a},o=this&&this.__spread||function(){for(var e=[],t=0;t=65&&r<=90&&(e[t]=r+32)}},t.byteUppercase=function(e){for(var t=0;t=97&&r<=122&&(e[t]=r-32)}},t.byteCaseInsensitiveMatch=function(e,t){if(e.length!==t.length)return!1;for(var r=0;r=65&&n<=90&&(n+=32),o>=65&&o<=90&&(o+=32),n!==o)return!1}return!0},t.startsWith=function(e,t){for(var r=0;;){if(r>=e.length)return!1;if(r>=t.length)return!0;if(e[r]!==t[r])return!1;r++}},t.byteLessThan=function(e,t){for(var r=0;;){if(r>=e.length)return!1;if(r>=t.length)return!0;var n=e[r],o=t[r];if(no)return!1;r++}},t.isomorphicDecode=function(e){return String.fromCodePoint.apply(String,o(e))}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(6),o=r(7),i=r(0),a=r(12),s=function(){function e(e){this._associatedDocument=e||n.dom.window.document}return e.prototype.createDocumentType=function(e,t,r){return i.namespace_validate(e),i.create_documentType(this._associatedDocument,e,t,r)},e.prototype.createDocument=function(e,t,r){void 0===r&&(r=null);var n=i.create_xmlDocument(),a=null;return t&&(a=i.document_internalCreateElementNS(n,e,t)),r&&n.appendChild(r),a&&n.appendChild(a),n._origin=this._associatedDocument._origin,e===o.namespace.HTML?n._contentType="application/xhtml+xml":e===o.namespace.SVG?n._contentType="image/svg+xml":n._contentType="application/xml",n},e.prototype.createHTMLDocument=function(e){var t=i.create_document();t._type="html",t._contentType="text/html",t.appendChild(i.create_documentType(t,"html","",""));var r=i.element_createAnElement(t,"html",o.namespace.HTML);t.appendChild(r);var n=i.element_createAnElement(t,"head",o.namespace.HTML);if(r.appendChild(n),void 0!==e){var a=i.element_createAnElement(t,"title",o.namespace.HTML);n.appendChild(a);var s=i.create_text(t,e);a.appendChild(s)}var l=i.element_createAnElement(t,"body",o.namespace.HTML);return r.appendChild(l),t._origin=this._associatedDocument._origin,t},e.prototype.hasFeature=function(){return!0},e._create=function(t){return new e(t)},e}();t.DOMImplementationImpl=s,a.idl_defineConst(s.prototype,"_ID","@oozcitak/dom")},function(e,t,r){"use strict";var n,o=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var i=r(70),a=r(1),s=r(0),l=function(e){function t(){var t=e.call(this)||this;return t._signalSlots=new Set,t._mutationObserverMicrotaskQueued=!1,t._mutationObservers=new Set,t._iteratorList=new a.FixedSizeSet,t._associatedDocument=s.create_document(),t}return o(t,e),Object.defineProperty(t.prototype,"document",{get:function(){return this._associatedDocument},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"event",{get:function(){return this._currentEvent},enumerable:!0,configurable:!0}),t._create=function(){return new t},t}(i.EventTargetImpl);t.WindowImpl=l},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(2),o=function(){function e(){}return e.isNode=function(e){return!!e&&void 0!==e._nodeType},e.isDocumentNode=function(t){return e.isNode(t)&&t._nodeType===n.NodeType.Document},e.isDocumentTypeNode=function(t){return e.isNode(t)&&t._nodeType===n.NodeType.DocumentType},e.isDocumentFragmentNode=function(t){return e.isNode(t)&&t._nodeType===n.NodeType.DocumentFragment},e.isAttrNode=function(t){return e.isNode(t)&&t._nodeType===n.NodeType.Attribute},e.isCharacterDataNode=function(t){if(!e.isNode(t))return!1;var r=t._nodeType;return r===n.NodeType.Text||r===n.NodeType.ProcessingInstruction||r===n.NodeType.Comment||r===n.NodeType.CData},e.isTextNode=function(t){return e.isNode(t)&&(t._nodeType===n.NodeType.Text||t._nodeType===n.NodeType.CData)},e.isExclusiveTextNode=function(t){return e.isNode(t)&&t._nodeType===n.NodeType.Text},e.isCDATASectionNode=function(t){return e.isNode(t)&&t._nodeType===n.NodeType.CData},e.isCommentNode=function(t){return e.isNode(t)&&t._nodeType===n.NodeType.Comment},e.isProcessingInstructionNode=function(t){return e.isNode(t)&&t._nodeType===n.NodeType.ProcessingInstruction},e.isElementNode=function(t){return e.isNode(t)&&t._nodeType===n.NodeType.Element},e.isCustomElementNode=function(t){return e.isElementNode(t)&&"custom"===t._customElementState},e.isShadowRoot=function(e){return!!e&&void 0!==e.host},e.isMouseEvent=function(e){return!!e&&void 0!==e.screenX&&null!=e.screenY},e.isSlotable=function(t){return!!t&&void 0!==t._name&&void 0!==t._assignedSlot&&(e.isTextNode(t)||e.isElementNode(t))},e.isSlot=function(t){return!!t&&void 0!==t._name&&void 0!==t._assignedNodes&&e.isElementNode(t)},e.isWindow=function(e){return!!e&&void 0!==e.navigator},e.isEventListener=function(e){return!!e&&void 0!==e.handleEvent},e.isRegisteredObserver=function(e){return!!e&&void 0!==e.observer&&void 0!==e.options},e.isTransientRegisteredObserver=function(t){return!!t&&void 0!==t.source&&e.isRegisteredObserver(t)},e}();t.Guard=o},function(e,t,r){"use strict";var n,o=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var i=function(e){function t(){return e.call(this)||this}return o(t,e),t}(r(98).DocumentImpl);t.XMLDocumentImpl=i},function(e,t,r){"use strict";var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},o=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a};Object.defineProperty(t,"__esModule",{value:!0});var i,a=r(1),s=r(243),l=r(7),u=r(244),c={ftp:21,file:null,http:80,https:443,ws:80,wss:443},d=/[\0-\x1F\x7F-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,p=/[ "<>`]|[\0-\x1F\x7F-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,f=/[ "<>`#?{}]|[\0-\x1F\x7F-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,h=/[ "<>`#?{}/:;=@\[\]\\\^\|]|[\0-\x1F\x7F-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,m=/[0-9A-Za-z!\$&-\/:;=\?@_~\xA0-\uD7FF\uE000-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uD83E\uD840-\uD87E\uD880-\uD8BE\uD8C0-\uD8FE\uD900-\uD93E\uD940-\uD97E\uD980-\uD9BE\uD9C0-\uD9FE\uDA00-\uDA3E\uDA40-\uDA7E\uDA80-\uDABE\uDAC0-\uDAFE\uDB00-\uDB3E\uDB40-\uDB7E\uDB80-\uDBBE\uDBC0-\uDBFE][\uDC00-\uDFFF]|[\uD83F\uD87F\uD8BF\uD8FF\uD93F\uD97F\uD9BF\uD9FF\uDA3F\uDA7F\uDABF\uDAFF\uDB3F\uDB7F\uDBBF\uDBFF][\uDC00-\uDFFD]/,g=/[\0\t\f\r #%/:?@\[\\\]]/;function y(e){void 0!==i&&i.call(null,"Validation Error: "+e)}function v(e){return e in c}function b(e){return v(e.scheme)}function x(e){return c[e]||null}function _(e){return""!==e.username||""!==e.password}function S(e,t){var r,o;void 0===t&&(t=!1);var i=e.scheme+":";if(null!==e.host?(i+="//",_(e)&&(i+=e.username,""!==e.password&&(i+=":"+e.password),i+="@"),i+=C(e.host),null!==e.port&&(i+=":"+e.port)):null===e.host&&"file"===e.scheme&&(i+="//"),e._cannotBeABaseURLFlag)i+=e.path[0];else try{for(var a=n(e.path),s=a.next();!s.done;s=a.next())i+="/"+s.value}catch(e){r={error:e}}finally{try{s&&!s.done&&(o=a.return)&&o.call(a)}finally{if(r)throw r.error}}return null!==e.query&&(i+="?"+e.query),t||null===e.fragment||(i+="#"+e.fragment),i}function C(e){return a.isNumber(e)?T(e):a.isArray(e)?"["+w(e)+"]":e}function T(e){for(var t="",r=e,n=1;n<=4;n++)t=(r%256).toString()+t,4!==n&&(t="."+t),r=Math.floor(r/256);return t}function w(e){for(var t="",r=null,n=-1,o=0,i=0,a=0;a<8;a++)if(0===e[a]){o=1;for(var s=a+1;s<8&&0===e[s];s++)o++;o>i&&(i=o,n=a)}i>1&&(r=n);for(var l=!1,u=0;u<8;u++)l&&0===e[u]||(l&&(l=!1),r!==u?(t+=e[u].toString(16),7!==u&&(t+=":")):(t+=0===u?"::":":",l=!0));return t}function A(e,t,r,o,i){var u,c,g,S;if(void 0===o){o={scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,_cannotBeABaseURLFlag:!1,_blobURLEntry:null};var C=/^[\u0000-\u001F\u0020]+/,T=/[\u0000-\u001F\u0020]+$/;(C.test(e)||T.test(e))&&y("Input string contains leading or trailing control characters or space."),e=(e=e.replace(C,"")).replace(T,"")}var w=/[\u0009\u000A\u000D]/g;w.test(e)&&y("Input string contains tab or newline characters."),e=e.replace(w,"");var A=void 0===i?s.ParserState.SchemeStart:i;void 0===t&&(t=null);for(var R=void 0===r||"replacement"===r||"UTF-16BE"===r||"UTF-16LE"===r?"UTF-8":r,F="",B=!1,L=!1,U=!1,V=new a.StringWalker(e);;){switch(A){case s.ParserState.SchemeStart:if(l.codePoint.ASCIIAlpha.test(V.c()))F+=V.c().toLowerCase(),A=s.ParserState.Scheme;else{if(void 0!==i)return y("Invalid scheme start character."),null;A=s.ParserState.NoScheme,V.pointer--}break;case s.ParserState.Scheme:if(l.codePoint.ASCIIAlphanumeric.test(V.c())||"+"===V.c()||"-"===V.c()||"."===V.c())F+=V.c().toLowerCase();else{if(":"!==V.c()){if(void 0===i){F="",A=s.ParserState.NoScheme,V.pointer=0;continue}return y("Invalid input string."),null}if(void 0!==i){if(v(o.scheme)&&!v(F))return o;if(!v(o.scheme)&&v(F))return o;if((_(o)||null!==o.port)&&"file"===F)return o;if("file"===o.scheme&&(""===o.host||null===o.host))return o}if(o.scheme=F,void 0!==i)return o.port===x(o.scheme)&&(o.port=null),o;F="","file"===o.scheme?(V.remaining().startsWith("//")||y("Invalid file URL scheme, '//' expected."),A=s.ParserState.File):b(o)&&null!==t&&t.scheme===o.scheme?A=s.ParserState.SpecialRelativeOrAuthority:b(o)?A=s.ParserState.SpecialAuthoritySlashes:V.remaining().startsWith("/")?(A=s.ParserState.PathOrAuthority,V.pointer++):(o._cannotBeABaseURLFlag=!0,o.path.push(""),A=s.ParserState.CannotBeABaseURLPath)}break;case s.ParserState.NoScheme:if(null===t||t._cannotBeABaseURLFlag&&"#"!==V.c())return y("Invalid input string."),null;t._cannotBeABaseURLFlag&&"#"===V.c()?(o.scheme=t.scheme,o.path=l.list.clone(t.path),o.query=t.query,o.fragment="",o._cannotBeABaseURLFlag=!0,A=s.ParserState.Fragment):"file"!==t.scheme?(A=s.ParserState.Relative,V.pointer--):(A=s.ParserState.File,V.pointer--);break;case s.ParserState.SpecialRelativeOrAuthority:"/"===V.c()&&V.remaining().startsWith("/")?(A=s.ParserState.SpecialAuthorityIgnoreSlashes,V.pointer++):(y("Invalid input string."),A=s.ParserState.Relative,V.pointer--);break;case s.ParserState.PathOrAuthority:"/"===V.c()?A=s.ParserState.Authority:(A=s.ParserState.Path,V.pointer--);break;case s.ParserState.Relative:if(null===t)throw new Error("Invalid parser state. Base URL is null.");switch(o.scheme=t.scheme,V.c()){case"":o.username=t.username,o.password=t.password,o.host=t.host,o.port=t.port,o.path=l.list.clone(t.path),o.query=t.query;break;case"/":A=s.ParserState.RelativeSlash;break;case"?":o.username=t.username,o.password=t.password,o.host=t.host,o.port=t.port,o.path=l.list.clone(t.path),o.query="",A=s.ParserState.Query;break;case"#":o.username=t.username,o.password=t.password,o.host=t.host,o.port=t.port,o.path=l.list.clone(t.path),o.query=t.query,o.fragment="",A=s.ParserState.Fragment;break;default:b(o)&&"\\"===V.c()?(y("Invalid input string."),A=s.ParserState.RelativeSlash):(o.username=t.username,o.password=t.password,o.host=t.host,o.port=t.port,o.path=l.list.clone(t.path),0!==o.path.length&&o.path.splice(o.path.length-1,1),A=s.ParserState.Path,V.pointer--)}break;case s.ParserState.RelativeSlash:if(!b(o)||"/"!==V.c()&&"\\"!==V.c())if("/"===V.c())A=s.ParserState.Authority;else{if(null===t)throw new Error("Invalid parser state. Base URL is null.");o.username=t.username,o.password=t.password,o.host=t.host,o.port=t.port,A=s.ParserState.Path,V.pointer--}else"\\"===V.c()&&y("Invalid input string."),A=s.ParserState.SpecialAuthorityIgnoreSlashes;break;case s.ParserState.SpecialAuthoritySlashes:"/"===V.c()&&V.remaining().startsWith("/")?(A=s.ParserState.SpecialAuthorityIgnoreSlashes,V.pointer++):(y("Expected '//'."),A=s.ParserState.SpecialAuthorityIgnoreSlashes,V.pointer--);break;case s.ParserState.SpecialAuthorityIgnoreSlashes:"/"!==V.c()&&"\\"!==V.c()?(A=s.ParserState.Authority,V.pointer--):y("Unexpected '/' or '\\'.");break;case s.ParserState.Authority:if("@"===V.c()){y("Unexpected '@'."),B&&(F="%40"+F),B=!0;try{for(var z=(u=void 0,n(F)),j=z.next();!j.done;j=z.next()){var W=j.value;if(":"!==W||U){var H=G(W,h);U?o.password+=H:o.username+=H}else U=!0}}catch(e){u={error:e}}finally{try{j&&!j.done&&(c=z.return)&&c.call(z)}finally{if(u)throw u.error}}F=""}else if(""===V.c()||"/"===V.c()||"?"===V.c()||"#"===V.c()||b(o)&&"\\"===V.c()){if(B&&""===F)return y("Invalid input string."),null;V.pointer-=F.length+1,F="",A=s.ParserState.Host}else F+=V.c();break;case s.ParserState.Host:case s.ParserState.Hostname:if(void 0!==i&&"file"===o.scheme)V.pointer--,A=s.ParserState.FileHost;else if(":"!==V.c()||L)if(""===V.c()||"/"===V.c()||"?"===V.c()||"#"===V.c()||b(o)&&"\\"===V.c()){if(V.pointer--,b(o)&&""===F)return y("Invalid input string."),null;if(void 0!==i&&""===F&&(_(o)||null!==o.port))return y("Invalid input string."),o;if(null===(X=M(F,!b(o))))return null;if(o.host=X,F="",A=s.ParserState.PathStart,void 0!==i)return o}else"["===V.c()&&(L=!0),"]"===V.c()&&(L=!1),F+=V.c();else{if(""===F)return y("Invalid input string."),null;if(null===(X=M(F,!b(o))))return null;if(o.host=X,F="",A=s.ParserState.Port,i===s.ParserState.Hostname)return o}break;case s.ParserState.Port:if(l.codePoint.ASCIIDigit.test(V.c()))F+=V.c();else{if(!(""===V.c()||"/"===V.c()||"?"===V.c()||"#"===V.c()||b(o)&&"\\"===V.c()||i))return y("Invalid input string."),null;if(""!==F&&""!==F){var K=parseInt(F,10);if(K>Math.pow(2,16)-1)return y("Invalid port number."),null;o.port=K===x(o.scheme)?null:K,F=""}if(void 0!==i)return o;A=s.ParserState.PathStart,V.pointer--}break;case s.ParserState.File:if(o.scheme="file","/"===V.c()||"\\"===V.c())"\\"===V.c()&&y("Invalid input string."),A=s.ParserState.FileSlash;else if(null!==t&&"file"===t.scheme)switch(V.c()){case"":o.host=t.host,o.path=l.list.clone(t.path),o.query=t.query;break;case"?":o.host=t.host,o.path=l.list.clone(t.path),o.query="",A=s.ParserState.Query;break;case"#":o.host=t.host,o.path=l.list.clone(t.path),o.query=t.query,o.fragment="",A=s.ParserState.Fragment;break;default:N(V.substring())?y("Unexpected windows drive letter in input string."):(o.host=t.host,o.path=l.list.clone(t.path),P(o)),A=s.ParserState.Path,V.pointer--}else A=s.ParserState.Path,V.pointer--;break;case s.ParserState.FileSlash:"/"===V.c()||"\\"===V.c()?("\\"===V.c()&&y("Invalid input string."),A=s.ParserState.FileHost):(null===t||"file"!==t.scheme||N(V.substring())||(I(t.path[0])?o.path.push(t.path[0]):o.host=t.host),A=s.ParserState.Path,V.pointer--);break;case s.ParserState.FileHost:if(""===V.c()||"/"===V.c()||"\\"===V.c()||"?"===V.c()||"#"===V.c())if(V.pointer--,void 0===i&&O(F))y("Unexpected windows drive letter in input string."),A=s.ParserState.Path;else if(""===F){if(o.host="",void 0!==i)return o;A=s.ParserState.PathStart}else{var X;if(null===(X=M(F,!b(o))))return null;if("localhost"===X&&(X=""),o.host=X,void 0!==i)return o;F="",A=s.ParserState.PathStart}else F+=V.c();break;case s.ParserState.PathStart:b(o)?("\\"===V.c()&&y("Invalid input string."),A=s.ParserState.Path,"/"!==V.c()&&"\\"!==V.c()&&V.pointer--):void 0===i&&"?"===V.c()?(o.query="",A=s.ParserState.Query):void 0===i&&"#"===V.c()?(o.fragment="",A=s.ParserState.Fragment):""!==V.c()&&(A=s.ParserState.Path,"/"!==V.c()&&V.pointer--);break;case s.ParserState.Path:if(""===V.c()||"/"===V.c()||b(o)&&"\\"===V.c()||void 0===i&&("?"===V.c()||"#"===V.c())){if(b(o)&&"\\"===V.c()&&y("Invalid input string."),D(F))P(o),"/"===V.c()||b(o)&&"\\"===V.c()||o.path.push("");else if(!E(F)||"/"===V.c()||b(o)&&"\\"===V.c()){if(!E(F)){if("file"===o.scheme&&0===o.path.length&&O(F)){null!==o.host&&""!==o.host&&(y("Invalid input string."),o.host="");var $=Array.from(F);F=$.slice(0,1)+":"+$.slice(2)}o.path.push(F)}}else o.path.push("");if(F="","file"===o.scheme&&(""===V.c()||"?"===V.c()||"#"===V.c()))for(;o.path.length>1&&""===o.path[0];)y("Invalid input string."),o.path.splice(0,1);"?"===V.c()&&(o.query="",A=s.ParserState.Query),"#"===V.c()&&(o.fragment="",A=s.ParserState.Fragment)}else m.test(V.c())||"%"===V.c()||y("Character is not a URL code point or a percent encoded character."),"%"!==V.c()||/^[0-9a-fA-F][0-9a-fA-F]/.test(V.remaining())||y("Percent encoded character must be followed by two hex digits."),F+=G(V.c(),f);break;case s.ParserState.CannotBeABaseURLPath:"?"===V.c()?(o.query="",A=s.ParserState.Query):"#"===V.c()?(o.fragment="",A=s.ParserState.Fragment):(""===V.c()||m.test(V.c())||"%"===V.c()||y("Character is not a URL code point or a percent encoded character."),"%"!==V.c()||/^[0-9a-fA-F][0-9a-fA-F]/.test(V.remaining())||y("Percent encoded character must be followed by two hex digits."),""!==V.c()&&(o.path[0]+=G(V.c(),d)));break;case s.ParserState.Query:if("UTF-8"===R||b(o)&&"ws"!==o.scheme&&"wss"!==o.scheme||(R="UTF-8"),void 0===i&&"#"===V.c())o.fragment="",A=s.ParserState.Fragment;else if(""!==V.c()){if(m.test(V.c())||"%"===V.c()||y("Character is not a URL code point or a percent encoded character."),"%"!==V.c()||/^[0-9a-fA-F][0-9a-fA-F]/.test(V.remaining())||y("Percent encoded character must be followed by two hex digits."),"UTF-8"!==R.toUpperCase())throw new Error("Only UTF-8 encoding is supported.");var q=a.utf8Encode(V.c());if(q.length>=3&&38===q[0]&&35===q[1]&&59===q[q.length-1])q=q.subarray(2,q.length-1),o.query+="%26%23"+l.byteSequence.isomorphicDecode(q)+"%3B";else try{for(var Y=(g=void 0,n(q)),J=Y.next();!J.done;J=Y.next()){var Q=J.value;Q<33||Q>126||34===Q||35===Q||60===Q||62===Q||39===Q&&b(o)?o.query+=k(Q):o.query+=String.fromCharCode(Q)}}catch(e){g={error:e}}finally{try{J&&!J.done&&(S=Y.return)&&S.call(Y)}finally{if(g)throw g.error}}}break;case s.ParserState.Fragment:""===V.c()||("\0"===V.c()?y("NULL character in input string."):(m.test(V.c())||"%"===V.c()||y("Unexpected character in fragment string."),"%"!==V.c()||/^[A-Za-z0-9][A-Za-z0-9]/.test(V.remaining())||y("Unexpected character in fragment string."),o.fragment+=G(V.c(),p)))}if(V.eof)break;V.pointer++}return o}function E(e){return"."===e||"%2e"===e.toLowerCase()}function D(e){var t=e.toLowerCase();return".."===t||".%2e"===t||"%2e."===t||"%2e%2e"===t}function P(e){var t=e.path;0!==t.length&&("file"===e.scheme&&1===t.length&&I(t[0])||e.path.splice(e.path.length-1,1))}function I(e){return e.length>=2&&l.codePoint.ASCIIAlpha.test(e[0])&&":"===e[1]}function O(e){return e.length>=2&&l.codePoint.ASCIIAlpha.test(e[0])&&(":"===e[1]||"|"===e[1])}function N(e){return e.length>=2&&O(e)&&(2===e.length||"/"===e[2]||"\\"===e[2]||"?"===e[2]||"#"===e[2])}function M(e,t){if(void 0===t&&(t=!1),e.startsWith("["))return e.endsWith("]")?B(e.substring(1,e.length-1)):(y("Expected ']' after '['."),null);if(t)return L(e);var r=W(a.utf8Decode(V(e)));if(null===r)return y("Invalid domain."),null;if(g.test(r))return y("Invalid domain."),null;var n=F(r);return null===n||a.isNumber(n)?n:r}function R(e,t){void 0===t&&(t={value:!1});var r=10;return e.startsWith("0x")||e.startsWith("0X")?(t.value=!0,e=e.substr(2),r=16):e.length>=2&&"0"===e[0]&&(t.value=!0,e=e.substr(1),r=8),""===e?0:(10===r?/^[0-9]+$/:16===r?/^[0-9A-Fa-f]+$/:/^[0-7]+$/).test(e)?parseInt(e,r):null}function F(e){var t,r,o,i,a={value:!1},s=e.split(".");if(""===s[s.length-1]&&(a.value=!0,s.length>1&&s.pop()),s.length>4)return e;var l=[];try{for(var u=n(s),c=u.next();!c.done;c=u.next()){var d=c.value;if(""===d)return e;if(null===(v=R(d,a)))return e;l.push(v)}}catch(e){t={error:e}}finally{try{c&&!c.done&&(r=u.return)&&r.call(u)}finally{if(t)throw t.error}}a.value&&y("Invalid IP v4 address.");for(var p=0;p255&&(y("Invalid IP v4 address."),p=Math.pow(256,5-l.length))return y("Invalid IP v4 address."),null;var f=l[l.length-1];l.pop();var h=0;try{for(var m=n(l),g=m.next();!g.done;g=m.next()){var v;f+=(v=g.value)*Math.pow(256,3-h),h++}}catch(e){o={error:e}}finally{try{g&&!g.done&&(i=m.return)&&i.call(m)}finally{if(o)throw o.error}}return f}function B(e){var t,r=[0,0,0,0,0,0,0,0],n=0,i=null,s=new a.StringWalker(e);if(":"===s.c()){if(!s.remaining().startsWith(":"))return y("Invalid IP v6 address."),null;s.pointer+=2,i=n+=1}for(;""!==s.c();){if(8===n)return y("Invalid IP v6 address."),null;if(":"!==s.c()){for(var u=0,c=0;c<4&&l.codePoint.ASCIIHexDigit.test(s.c());)u=16*u+parseInt(s.c(),16),s.pointer++,c++;if("."===s.c()){if(0===c)return y("Invalid IP v6 address."),null;if(s.pointer-=c,n>6)return y("Invalid IP v6 address."),null;for(var d=0;""!==s.c();){var p=null;if(d>0){if(!("."===s.c()&&d<4))return y("Invalid IP v6 address."),null;s.pointer++}if(!l.codePoint.ASCIIDigit.test(s.c()))return y("Invalid IP v6 address."),null;for(;l.codePoint.ASCIIDigit.test(s.c());){var f=parseInt(s.c(),10);if(null===p)p=f;else{if(0===p)return y("Invalid IP v6 address."),null;p=10*p+f}if(p>255)return y("Invalid IP v6 address."),null;s.pointer++}if(null===p)return y("Invalid IP v6 address."),null;r[n]=256*r[n]+p,2!==++d&&4!==d||n++}if(4!==d)return y("Invalid IP v6 address."),null;break}if(":"===s.c()){if(s.pointer++,""===s.c())return y("Invalid IP v6 address."),null}else if(""!==s.c())return y("Invalid IP v6 address."),null;r[n]=u,n++}else{if(null!==i)return y("Invalid IP v6 address."),null;s.pointer++,i=++n}}if(null!==i){var h=n-i;for(n=7;0!==n&&h>0;)t=o([r[i+h-1],r[n]],2),r[n]=t[0],r[i+h-1]=t[1],n--,h--}else if(null===i&&8!==n)return y("Invalid IP v6 address."),null;return r}function L(e){var t,r;if(/[\x00\t\f\r #/:?@\[\\\]]/.test(e))return y("Invalid host string."),null;var o="";try{for(var i=n(e),a=i.next();!a.done;a=i.next())o+=G(a.value,d)}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return o}function k(e){return"%"+("00"+e.toString(16).toUpperCase()).slice(-2)}function U(e){for(var t=function(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102},r=new Uint8Array(e.length),n=0,o=0;o=e.length-2)r[n]=i,n++;else if(37!==i||t(e[o+1])&&t(e[o+2])){var s=parseInt(a.utf8Decode(Uint8Array.of(e[o+1],e[o+2])),16);r[n]=s,n++,o+=2}else r[n]=i,n++}return r.subarray(0,n)}function V(e){return U(a.utf8Encode(e))}function G(e,t){var r,o;if(!t.test(e))return e;var i=a.utf8Encode(e),s="";try{for(var l=n(i),u=l.next();!u.done;u=l.next())s+=k(u.value)}catch(e){r={error:e}}finally{try{u&&!u.done&&(o=l.return)&&o.call(l)}finally{if(r)throw r.error}}return s}function z(e){var t,r,o,i,s=[],l=[];try{for(var u=n(e),c=u.next();!c.done;c=u.next()){var d=c.value;38===d?(s.push(Uint8Array.from(l)),l=[]):l.push(d)}}catch(e){t={error:e}}finally{try{c&&!c.done&&(r=u.return)&&r.call(u)}finally{if(t)throw t.error}}0!==l.length&&s.push(Uint8Array.from(l));var p=[];try{for(var f=n(s),h=f.next();!h.done;h=f.next()){var m=h.value;if(0!==m.length){for(var g=m.indexOf(61),y=-1!==g?m.slice(0,g):m,v=-1!==g?m.slice(g+1):new Uint8Array,b=0;b=48&&s<=57||s>=65&&s<=90||95===s||s>=97&&s<=122?String.fromCodePoint(s):k(s)}}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return o}function W(e,t){void 0===t&&(t=!1);var r=u.domainToASCII(e);return""===r?(y("Invalid domain name."),null):r}t.setValidationErrorCallback=function(e){i=e},t.newURL=function(){return{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,_cannotBeABaseURLFlag:!1,_blobURLEntry:null}},t.isSpecialScheme=v,t.isSpecial=b,t.defaultPort=x,t.includesCredentials=_,t.cannotHaveAUsernamePasswordPort=function(e){return null===e.host||""===e.host||e._cannotBeABaseURLFlag||"file"===e.scheme},t.urlSerializer=S,t.hostSerializer=C,t.iPv4Serializer=T,t.iPv6Serializer=w,t.urlParser=function(e,t,r){var n=A(e,t,r);return null===n?null:("blob"!==n.scheme||(n._blobURLEntry=null),n)},t.basicURLParser=A,t.setTheUsername=function(e,t){var r,o,i="";try{for(var a=n(t),s=a.next();!s.done;s=a.next())i+=G(s.value,h)}catch(e){r={error:e}}finally{try{s&&!s.done&&(o=a.return)&&o.call(a)}finally{if(r)throw r.error}}e.username=i},t.setThePassword=function(e,t){var r,o,i="";try{for(var a=n(t),s=a.next();!s.done;s=a.next())i+=G(s.value,h)}catch(e){r={error:e}}finally{try{s&&!s.done&&(o=a.return)&&o.call(a)}finally{if(r)throw r.error}}e.password=i},t.isSingleDotPathSegment=E,t.isDoubleDotPathSegment=D,t.shorten=P,t.isNormalizedWindowsDriveLetter=I,t.isWindowsDriveLetter=O,t.startsWithAWindowsDriveLetter=N,t.hostParser=M,t.iPv4NumberParser=R,t.iPv4Parser=F,t.iPv6Parser=B,t.opaqueHostParser=L,t.resolveABlobURL=function(e){return null},t.percentEncode=k,t.percentDecode=U,t.stringPercentDecode=V,t.utf8PercentEncode=G,t.hostEquals=function(e,t){return e===t},t.urlEquals=function(e,t,r){return void 0===r&&(r=!1),S(e,r)===S(t,r)},t.urlEncodedStringParser=function(e){return z(a.utf8Encode(e))},t.urlEncodedParser=z,t.urlEncodedByteSerializer=j,t.urlEncodedSerializer=function(e,t){var r,o;if("UTF-8"!==(void 0===t||"replacement"===t||"UTF-16BE"===t||"UTF-16LE"===t?"UTF-8":t).toUpperCase())throw new Error("Only UTF-8 encoding is supported.");var i="";try{for(var s=n(e),l=s.next();!l.done;l=s.next()){var u=l.value,c=j(a.utf8Encode(u[0])),d=u[1];d=j(a.utf8Encode(d)),""!==i&&(i+="&"),i+=c+"="+d}}catch(e){r={error:e}}finally{try{l&&!l.done&&(o=s.return)&&o.call(s)}finally{if(r)throw r.error}}return i},t.origin=function e(t){switch(t.scheme){case"blob":t._blobURLEntry;var r=A(t.path[0]);return null===r?s.OpaqueOrigin:e(r);case"ftp":case"http":case"https":case"ws":case"wss":return[t.scheme,null===t.host?"":t.host,t.port,null];default:return s.OpaqueOrigin}},t.domainToASCII=W,t.domainToUnicode=function(e,t){void 0===t&&(t=!1);var r=u.domainToUnicode(e);return""===r&&y("Invalid domain name."),r},t.asciiSerializationOfAnOrigin=function(e){if(""===e[0]&&""===e[1]&&null===e[2]&&null===e[3])return"null";var t=e[0]+"://"+C(e[1]);return null!==e[2]&&(t+=":"+e[2].toString()),t}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),o=function(){function e(){this._signal=n.create_abortSignal()}return Object.defineProperty(e.prototype,"signal",{get:function(){return this._signal},enumerable:!0,configurable:!0}),e.prototype.abort=function(){n.abort_signalAbort(this._signal)},e}();t.AbortControllerImpl=o},function(e,t,r){"use strict";var n,o=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var i=r(70),a=r(0),s=function(e){function t(){var t=e.call(this)||this;return t._abortedFlag=!1,t._abortAlgorithms=new Set,t}return o(t,e),Object.defineProperty(t.prototype,"aborted",{get:function(){return this._abortedFlag},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onabort",{get:function(){return a.event_getterEventHandlerIDLAttribute(this,"onabort")},set:function(e){a.event_setterEventHandlerIDLAttribute(this,"onabort",e)},enumerable:!0,configurable:!0}),t._create=function(){return new t},t}(i.EventTargetImpl);t.AbortSignalImpl=s},function(e,t,r){"use strict";var n,o=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var i=r(2),a=r(34),s=r(12),l=function(e){function t(t,r,n){var o=e.call(this)||this;return o._name="",o._publicId="",o._systemId="",o._name=t,o._publicId=r,o._systemId=n,o}return o(t,e),Object.defineProperty(t.prototype,"name",{get:function(){return this._name},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"publicId",{get:function(){return this._publicId},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"systemId",{get:function(){return this._systemId},enumerable:!0,configurable:!0}),t.prototype.before=function(){for(var e=[],t=0;t=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var o=r(6),i=r(1),a=r(0),s=function(){function e(e){return this._live=!0,this._filter=null,this._length=0,this._root=e,new Proxy(this,this)}return Object.defineProperty(e.prototype,"length",{get:function(){return this._root._children.size},enumerable:!0,configurable:!0}),e.prototype.item=function(e){if(e<0||e>this.length-1)return null;if(e=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var o=r(6),i=r(1),a=function(){function e(e){return this._live=!1,this._items=[],this._length=0,this._root=e,this._items=[],this._filter=function(e){return!0},new Proxy(this,this)}return Object.defineProperty(e.prototype,"length",{get:function(){return this._items.length},enumerable:!0,configurable:!0}),e.prototype.item=function(e){return e<0||e>this.length-1?null:this._items[e]},e.prototype.keys=function(){var e;return(e={})[Symbol.iterator]=function(){var e=0;return{next:function(){return e===this.length?{done:!0,value:null}:{done:!1,value:e++}}.bind(this)}}.bind(this),e},e.prototype.values=function(){var e;return(e={})[Symbol.iterator]=function(){var e=this[Symbol.iterator]();return{next:function(){return e.next()}}}.bind(this),e},e.prototype.entries=function(){var e;return(e={})[Symbol.iterator]=function(){var e=this[Symbol.iterator](),t=0;return{next:function(){var r=e.next();return r.done?{done:!0,value:null}:{done:!1,value:[t++,r.value]}}}}.bind(this),e},e.prototype[Symbol.iterator]=function(){var e=this._items[Symbol.iterator]();return{next:function(){return e.next()}}},e.prototype.forEach=function(e,t){var r,i;void 0===t&&(t=o.dom.window);var a=0;try{for(var s=n(this._items),l=s.next();!l.done;l=s.next()){var u=l.value;e.call(t,u,a++,this)}}catch(e){r={error:e}}finally{try{l&&!l.done&&(i=s.return)&&i.call(s)}finally{if(r)throw r.error}}},e.prototype.get=function(e,t,r){if(!i.isString(t))return Reflect.get(e,t,r);var n=Number(t);return isNaN(n)?Reflect.get(e,t,r):e._items[n]||void 0},e.prototype.set=function(e,t,r,n){if(!i.isString(t))return Reflect.set(e,t,r,n);var o=Number(t);return isNaN(o)?Reflect.set(e,t,r,n):o>=0&&o=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var a=r(6),s=r(2),l=r(102),u=r(9),c=r(0),d=r(12),p=r(3),f=function(e){function t(){var t=e.call(this)||this,r=a.dom.window._associatedDocument;return t._start=[r,0],t._end=[r,0],a.dom.rangeList.add(t),t}return o(t,e),Object.defineProperty(t.prototype,"commonAncestorContainer",{get:function(){for(var e=this._start[0];!c.tree_isAncestorOf(this._end[0],e,!0);){if(null===e._parent)throw new Error("Parent node is null.");e=e._parent}return e},enumerable:!0,configurable:!0}),t.prototype.setStart=function(e,t){c.range_setTheStart(this,e,t)},t.prototype.setEnd=function(e,t){c.range_setTheEnd(this,e,t)},t.prototype.setStartBefore=function(e){var t=e._parent;if(null===t)throw new u.InvalidNodeTypeError;c.range_setTheStart(this,t,c.tree_index(e))},t.prototype.setStartAfter=function(e){var t=e._parent;if(null===t)throw new u.InvalidNodeTypeError;c.range_setTheStart(this,t,c.tree_index(e)+1)},t.prototype.setEndBefore=function(e){var t=e._parent;if(null===t)throw new u.InvalidNodeTypeError;c.range_setTheEnd(this,t,c.tree_index(e))},t.prototype.setEndAfter=function(e){var t=e._parent;if(null===t)throw new u.InvalidNodeTypeError;c.range_setTheEnd(this,t,c.tree_index(e)+1)},t.prototype.collapse=function(e){e?this._end=this._start:this._start=this._end},t.prototype.selectNode=function(e){c.range_select(e,this)},t.prototype.selectNodeContents=function(e){if(p.Guard.isDocumentTypeNode(e))throw new u.InvalidNodeTypeError;var t=c.tree_nodeLength(e);this._start=[e,0],this._end=[e,t]},t.prototype.compareBoundaryPoints=function(e,t){if(e!==s.HowToCompare.StartToStart&&e!==s.HowToCompare.StartToEnd&&e!==s.HowToCompare.EndToEnd&&e!==s.HowToCompare.EndToStart)throw new u.NotSupportedError;if(c.range_root(this)!==c.range_root(t))throw new u.WrongDocumentError;var r,n;switch(e){case s.HowToCompare.StartToStart:r=this._start,n=t._start;break;case s.HowToCompare.StartToEnd:r=this._end,n=t._start;break;case s.HowToCompare.EndToEnd:r=this._end,n=t._end;break;case s.HowToCompare.EndToStart:r=this._start,n=t._end;break;default:throw new u.NotSupportedError}var o=c.boundaryPoint_position(r,n);return o===s.BoundaryPosition.Before?-1:o===s.BoundaryPosition.After?1:0},t.prototype.deleteContents=function(){var e,t,r,n;if(!c.range_collapsed(this)){var o=this._startNode,a=this._startOffset,s=this._endNode,l=this._endOffset;if(o===s&&p.Guard.isCharacterDataNode(o))c.characterData_replaceData(o,a,l-a,"");else{var u,d,f=[];try{for(var h=i(c.range_getContainedNodes(this)),m=h.next();!m.done;m=h.next()){var g=(x=m.value)._parent;null!==g&&c.range_isContained(g,this)||f.push(x)}}catch(t){e={error:t}}finally{try{m&&!m.done&&(t=h.return)&&t.call(h)}finally{if(e)throw e.error}}if(c.tree_isAncestorOf(s,o,!0))u=o,d=a;else{for(var y=o;null!==y._parent&&!c.tree_isAncestorOf(s,y._parent,!0);)y=y._parent;if(null===y._parent)throw new Error("Parent node is null.");u=y._parent,d=c.tree_index(y)+1}p.Guard.isCharacterDataNode(o)&&c.characterData_replaceData(o,a,c.tree_nodeLength(o)-a,"");try{for(var v=i(f),b=v.next();!b.done;b=v.next()){var x;(x=b.value)._parent&&c.mutation_remove(x,x._parent)}}catch(e){r={error:e}}finally{try{b&&!b.done&&(n=v.return)&&n.call(v)}finally{if(r)throw r.error}}p.Guard.isCharacterDataNode(s)&&c.characterData_replaceData(s,0,l,""),this._start=[u,d],this._end=[u,d]}}},t.prototype.extractContents=function(){return c.range_extract(this)},t.prototype.cloneContents=function(){return c.range_cloneTheContents(this)},t.prototype.insertNode=function(e){return c.range_insert(e,this)},t.prototype.surroundContents=function(e){var t,r;try{for(var n=i(c.range_getPartiallyContainedNodes(this)),o=n.next();!o.done;o=n.next()){var a=o.value;if(!p.Guard.isTextNode(a))throw new u.InvalidStateError}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}if(p.Guard.isDocumentNode(e)||p.Guard.isDocumentTypeNode(e)||p.Guard.isDocumentFragmentNode(e))throw new u.InvalidNodeTypeError;var s=c.range_extract(this);0!==e._children.size&&c.mutation_replaceAll(null,e),c.range_insert(e,this),c.mutation_append(s,e),c.range_select(e,this)},t.prototype.cloneRange=function(){return c.create_range(this._start,this._end)},t.prototype.detach=function(){a.dom.rangeList.delete(this)},t.prototype.isPointInRange=function(e,t){if(c.tree_rootNode(e)!==c.range_root(this))return!1;if(p.Guard.isDocumentTypeNode(e))throw new u.InvalidNodeTypeError;if(t>c.tree_nodeLength(e))throw new u.IndexSizeError;var r=[e,t];return c.boundaryPoint_position(r,this._start)!==s.BoundaryPosition.Before&&c.boundaryPoint_position(r,this._end)!==s.BoundaryPosition.After},t.prototype.comparePoint=function(e,t){if(c.tree_rootNode(e)!==c.range_root(this))throw new u.WrongDocumentError;if(p.Guard.isDocumentTypeNode(e))throw new u.InvalidNodeTypeError;if(t>c.tree_nodeLength(e))throw new u.IndexSizeError;var r=[e,t];return c.boundaryPoint_position(r,this._start)===s.BoundaryPosition.Before?-1:c.boundaryPoint_position(r,this._end)===s.BoundaryPosition.After?1:0},t.prototype.intersectsNode=function(e){if(c.tree_rootNode(e)!==c.range_root(this))return!1;var t=e._parent;if(null===t)return!0;var r=c.tree_index(e);return c.boundaryPoint_position([t,r],this._end)===s.BoundaryPosition.Before&&c.boundaryPoint_position([t,r+1],this._start)===s.BoundaryPosition.After},t.prototype.toString=function(){var e,t,r="";if(this._startNode===this._endNode&&p.Guard.isTextNode(this._startNode))return this._startNode._data.substring(this._startOffset,this._endOffset);p.Guard.isTextNode(this._startNode)&&(r+=this._startNode._data.substring(this._startOffset));try{for(var n=i(c.range_getContainedNodes(this)),o=n.next();!o.done;o=n.next()){var a=o.value;p.Guard.isTextNode(a)&&(r+=a._data)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}return p.Guard.isTextNode(this._endNode)&&(r+=this._endNode._data.substring(0,this._endOffset)),r},t._create=function(e,r){var n=new t;return e&&(n._start=e),r&&(n._end=r),n},t.START_TO_START=0,t.START_TO_END=1,t.END_TO_END=2,t.END_TO_START=3,t}(l.AbstractRangeImpl);t.RangeImpl=f,d.idl_defineConst(f.prototype,"START_TO_START",0),d.idl_defineConst(f.prototype,"START_TO_END",1),d.idl_defineConst(f.prototype,"END_TO_END",2),d.idl_defineConst(f.prototype,"END_TO_START",3)},function(e,t,r){"use strict";var n,o=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var i=r(103),a=r(0),s=function(e){function t(t,r,n){var o=e.call(this,t)||this;return o._iteratorCollection=void 0,o._reference=r,o._pointerBeforeReference=n,a.nodeIterator_iteratorList().add(o),o}return o(t,e),Object.defineProperty(t.prototype,"referenceNode",{get:function(){return this._reference},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pointerBeforeReferenceNode",{get:function(){return this._pointerBeforeReference},enumerable:!0,configurable:!0}),t.prototype.nextNode=function(){return a.nodeIterator_traverse(this,!0)},t.prototype.previousNode=function(){return a.nodeIterator_traverse(this,!1)},t.prototype.detach=function(){a.nodeIterator_iteratorList().delete(this)},t._create=function(e,r,n){return new t(e,r,n)},t}(i.TraverserImpl);t.NodeIteratorImpl=s},function(e,t,r){"use strict";var n,o=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var i=r(2),a=r(103),s=r(0),l=function(e){function t(t,r){var n=e.call(this,t)||this;return n._current=r,n}return o(t,e),Object.defineProperty(t.prototype,"currentNode",{get:function(){return this._current},set:function(e){this._current=e},enumerable:!0,configurable:!0}),t.prototype.parentNode=function(){for(var e=this._current;null!==e&&e!==this._root;)if(null!==(e=e._parent)&&s.traversal_filter(this,e)===i.FilterResult.Accept)return this._current=e,e;return null},t.prototype.firstChild=function(){return s.treeWalker_traverseChildren(this,!0)},t.prototype.lastChild=function(){return s.treeWalker_traverseChildren(this,!1)},t.prototype.nextSibling=function(){return s.treeWalker_traverseSiblings(this,!0)},t.prototype.previousNode=function(){for(var e=this._current;e!==this._root;){for(var t=e._previousSibling;t;){e=t;for(var r=s.traversal_filter(this,e);r!==i.FilterResult.Reject&&e._lastChild;)e=e._lastChild,r=s.traversal_filter(this,e);if(r===i.FilterResult.Accept)return this._current=e,e;t=e._previousSibling}if(e===this._root||null===e._parent)return null;if(e=e._parent,s.traversal_filter(this,e)===i.FilterResult.Accept)return this._current=e,e}return null},t.prototype.previousSibling=function(){return s.treeWalker_traverseSiblings(this,!1)},t.prototype.nextNode=function(){for(var e=this._current,t=i.FilterResult.Accept;;){for(;t!==i.FilterResult.Reject&&e._firstChild;)if(e=e._firstChild,(t=s.traversal_filter(this,e))===i.FilterResult.Accept)return this._current=e,e;for(var r=null,n=e;null!==n;){if(n===this._root)return null;if(null!==(r=n._nextSibling)){e=r;break}n=n._parent}if((t=s.traversal_filter(this,e))===i.FilterResult.Accept)return this._current=e,e}},t._create=function(e,r){return new t(e,r)},t}(a.TraverserImpl);t.TreeWalkerImpl=l},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(2),o=r(12),i=function(){function e(){}return e.prototype.acceptNode=function(e){return n.FilterResult.Accept},e._create=function(){return new e},e.FILTER_ACCEPT=1,e.FILTER_REJECT=2,e.FILTER_SKIP=3,e.SHOW_ALL=4294967295,e.SHOW_ELEMENT=1,e.SHOW_ATTRIBUTE=2,e.SHOW_TEXT=4,e.SHOW_CDATA_SECTION=8,e.SHOW_ENTITY_REFERENCE=16,e.SHOW_ENTITY=32,e.SHOW_PROCESSING_INSTRUCTION=64,e.SHOW_COMMENT=128,e.SHOW_DOCUMENT=256,e.SHOW_DOCUMENT_TYPE=512,e.SHOW_DOCUMENT_FRAGMENT=1024,e.SHOW_NOTATION=2048,e}();t.NodeFilterImpl=i,o.idl_defineConst(i.prototype,"FILTER_ACCEPT",1),o.idl_defineConst(i.prototype,"FILTER_REJECT",2),o.idl_defineConst(i.prototype,"FILTER_SKIP",3),o.idl_defineConst(i.prototype,"SHOW_ALL",4294967295),o.idl_defineConst(i.prototype,"SHOW_ELEMENT",1),o.idl_defineConst(i.prototype,"SHOW_ATTRIBUTE",2),o.idl_defineConst(i.prototype,"SHOW_TEXT",4),o.idl_defineConst(i.prototype,"SHOW_CDATA_SECTION",8),o.idl_defineConst(i.prototype,"SHOW_ENTITY_REFERENCE",16),o.idl_defineConst(i.prototype,"SHOW_ENTITY",32),o.idl_defineConst(i.prototype,"SHOW_PROCESSING_INSTRUCTION",64),o.idl_defineConst(i.prototype,"SHOW_COMMENT",128),o.idl_defineConst(i.prototype,"SHOW_DOCUMENT",256),o.idl_defineConst(i.prototype,"SHOW_DOCUMENT_TYPE",512),o.idl_defineConst(i.prototype,"SHOW_DOCUMENT_FRAGMENT",1024),o.idl_defineConst(i.prototype,"SHOW_NOTATION",2048)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(e,t,r,n,o,i,a,s,l){this._type=e,this._target=t,this._addedNodes=r,this._removedNodes=n,this._previousSibling=o,this._nextSibling=i,this._attributeName=a,this._attributeNamespace=s,this._oldValue=l}return Object.defineProperty(e.prototype,"type",{get:function(){return this._type},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"target",{get:function(){return this._target},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"addedNodes",{get:function(){return this._addedNodes},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"removedNodes",{get:function(){return this._removedNodes},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"previousSibling",{get:function(){return this._previousSibling},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nextSibling",{get:function(){return this._nextSibling},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"attributeName",{get:function(){return this._attributeName},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"attributeNamespace",{get:function(){return this._attributeNamespace},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"oldValue",{get:function(){return this._oldValue},enumerable:!0,configurable:!0}),e._create=function(t,r,n,o,i,a,s,l,u){return new e(t,r,n,o,i,a,s,l,u)},e}();t.MutationRecordImpl=n},function(e,t,r){"use strict";var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var o=r(6),i=r(9),a=r(7),s=r(0),l=function(){function e(e,t){this._element=e,this._attribute=t,this._tokenSet=new Set;var r=t._localName,n=s.element_getAnAttributeValue(e,r),i=this;this._element._attributeChangeSteps.push(function(e,t,r,n,o){t===i._attribute._localName&&null===o&&(n?i._tokenSet=s.orderedSet_parse(n):i._tokenSet.clear())}),o.dom.features.steps&&s.dom_runAttributeChangeSteps(e,r,n,n,null)}return Object.defineProperty(e.prototype,"length",{get:function(){return this._tokenSet.size},enumerable:!0,configurable:!0}),e.prototype.item=function(e){var t,r,o=0;try{for(var i=n(this._tokenSet),a=i.next();!a.done;a=i.next()){var s=a.value;if(o===e)return s;o++}}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return null},e.prototype.contains=function(e){return this._tokenSet.has(e)},e.prototype.add=function(){for(var e,t,r=[],o=0;o=97&&r<=122||r>=65&&r<=90||58===r||95===r||r>=192&&r<=214||r>=216&&r<=246||r>=248&&r<=767||r>=880&&r<=893||r>=895&&r<=8191||r>=8204&&r<=8205||r>=8304&&r<=8591||r>=11264&&r<=12271||r>=12289&&r<=55295||r>=63744&&r<=64975||r>=65008&&r<=65533||0!==t&&(45===r||46===r||r>=48&&r<=57||183===r||r>=768&&r<=879||r>=8255&&r<=8256))){if(r>=55296&&r<=56319&&t=56320&&n<=57343&&(t++,(r=1024*(r-55296)+n-56320+65536)>=65536&&r<=983039))continue}return!1}}return!0},t.xml_isQName=function(e){for(var t=!1,r=0;r=97&&n<=122||n>=65&&n<=90||95===n||n>=192&&n<=214||n>=216&&n<=246||n>=248&&n<=767||n>=880&&n<=893||n>=895&&n<=8191||n>=8204&&n<=8205||n>=8304&&n<=8591||n>=11264&&n<=12271||n>=12289&&n<=55295||n>=63744&&n<=64975||n>=65008&&n<=65533||0!==r&&(45===n||46===n||n>=48&&n<=57||183===n||n>=768&&n<=879||n>=8255&&n<=8256))){if(0===r||58!==n){if(n>=55296&&n<=56319&&r=56320&&o<=57343&&(r++,(n=1024*(n-55296)+o-56320+65536)>=65536&&n<=983039))continue}return!1}if(t)return!1;if(r===e.length-1)return!1;t=!0}}return!0},t.xml_isLegalChar=function(e){for(var t=0;t=32&&r<=55295||r>=57344&&r<=65533)){if(r>=55296&&r<=56319&&t=56320&&n<=57343&&(t++,(r=1024*(r-55296)+n-56320+65536)>=65536&&r<=1114111))continue}return!1}}return!0},t.xml_isPubidChar=function(e){for(var t=0;t=97&&r<=122||r>=65&&r<=90||r>=39&&r<=59||32===r||13===r||10===r||r>=35&&r<=37||33===r||61===r||63===r||64===r||95===r))return!1}return!0}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(2),o=r(17);t.boundaryPoint_position=function e(t,r){var i=t[0],a=t[1],s=r[0],l=r[1];if(console.assert(o.tree_rootNode(i)===o.tree_rootNode(s),"Boundary points must share the same root node."),i===s)return a===l?n.BoundaryPosition.Equal:a=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var o=r(6),i=r(3),a=r(7),s=r(29),l=r(108),u=r(30),c=r(37),d=r(52);t.node_stringReplaceAll=function(e,t){var r=null;""!==e&&(r=s.create_text(t._nodeDocument,e)),c.mutation_replaceAll(r,t)},t.node_clone=function e(t,r,a){var l,p,f,h,m;if(void 0===r&&(r=null),void 0===a&&(a=!1),null===r&&(r=t._nodeDocument),i.Guard.isElementNode(t)){m=d.element_createAnElement(r,t._localName,t._namespace,t._namespacePrefix,t._is,!1);try{for(var g=n(t._attributeList),y=g.next();!y.done;y=g.next()){var v=e(y.value,r);d.element_append(v,m)}}catch(e){l={error:e}}finally{try{y&&!y.done&&(p=g.return)&&p.call(g)}finally{if(l)throw l.error}}}else if(i.Guard.isDocumentNode(t)){var b=s.create_document();b._encoding=t._encoding,b._contentType=t._contentType,b._URL=t._URL,b._origin=t._origin,b._type=t._type,b._mode=t._mode,m=b}else if(i.Guard.isDocumentTypeNode(t))m=s.create_documentType(r,t._name,t._publicId,t._systemId);else if(i.Guard.isAttrNode(t)){var x=s.create_attr(r,t.localName);x._namespace=t._namespace,x._namespacePrefix=t._namespacePrefix,x._value=t._value,m=x}else m=i.Guard.isExclusiveTextNode(t)?s.create_text(r,t._data):i.Guard.isCDATASectionNode(t)?s.create_cdataSection(r,t._data):i.Guard.isCommentNode(t)?s.create_comment(r,t._data):i.Guard.isProcessingInstructionNode(t)?s.create_processingInstruction(r,t._target,t._data):i.Guard.isDocumentFragmentNode(t)?s.create_documentFragment(r):Object.create(t);if(i.Guard.isDocumentNode(m)?(m._nodeDocument=m,r=m):m._nodeDocument=r,o.dom.features.steps&&u.dom_runCloningSteps(m,t,r,a),a)try{for(var _=n(t._children),S=_.next();!S.done;S=_.next()){var C=e(S.value,r,!0);c.mutation_append(C,m)}}catch(e){f={error:e}}finally{try{S&&!S.done&&(h=_.return)&&h.call(_)}finally{if(f)throw f.error}}return m},t.node_equals=function e(t,r){var o,a,s,l;if(t._nodeType!==r._nodeType)return!1;if(i.Guard.isDocumentTypeNode(t)&&i.Guard.isDocumentTypeNode(r)){if(t._name!==r._name||t._publicId!==r._publicId||t._systemId!==r._systemId)return!1}else if(i.Guard.isElementNode(t)&&i.Guard.isElementNode(r)){if(t._namespace!==r._namespace||t._namespacePrefix!==r._namespacePrefix||t._localName!==r._localName||t._attributeList.length!==r._attributeList.length)return!1}else if(i.Guard.isAttrNode(t)&&i.Guard.isAttrNode(r)){if(t._namespace!==r._namespace||t._localName!==r._localName||t._value!==r._value)return!1}else if(i.Guard.isProcessingInstructionNode(t)&&i.Guard.isProcessingInstructionNode(r)){if(t._target!==r._target||t._data!==r._data)return!1}else if(i.Guard.isCharacterDataNode(t)&&i.Guard.isCharacterDataNode(r)&&t._data!==r._data)return!1;if(i.Guard.isElementNode(t)&&i.Guard.isElementNode(r)){var u={};try{for(var c=n(t._attributeList),d=c.next();!d.done;d=c.next())u[(h=d.value)._localName]=h}catch(e){o={error:e}}finally{try{d&&!d.done&&(a=c.return)&&a.call(c)}finally{if(o)throw o.error}}try{for(var p=n(r._attributeList),f=p.next();!f.done;f=p.next()){var h,m=f.value;if(!(h=u[m._localName]))return!1;if(!e(h,m))return!1}}catch(e){s={error:e}}finally{try{f&&!f.done&&(l=p.return)&&l.call(p)}finally{if(s)throw s.error}}}if(t._children.size!==r._children.size)return!1;for(var g=t._children[Symbol.iterator](),y=r._children[Symbol.iterator](),v=g.next(),b=y.next();!v.done&&!b.done;){if(!e(v.value,b.value))return!1;v=g.next(),b=y.next()}return!0},t.node_listOfElementsWithQualifiedName=function(e,t){return"*"===e?s.create_htmlCollection(t):"html"===t._nodeDocument._type?s.create_htmlCollection(t,function(t){return t._namespace===a.namespace.HTML&&t._qualifiedName===e.toLowerCase()||t._namespace!==a.namespace.HTML&&t._qualifiedName===e}):s.create_htmlCollection(t,function(t){return t._qualifiedName===e})},t.node_listOfElementsWithNamespace=function(e,t,r){return""===e&&(e=null),"*"===e&&"*"===t?s.create_htmlCollection(r):"*"===e?s.create_htmlCollection(r,function(e){return e._localName===t}):"*"===t?s.create_htmlCollection(r,function(t){return t._namespace===e}):s.create_htmlCollection(r,function(r){return r._localName===t&&r._namespace===e})},t.node_listOfElementsWithClassNames=function(e,t){var r=l.orderedSet_parse(e);if(0===r.size)return s.create_htmlCollection(t,function(){return!1});var n="quirks"!==t._nodeDocument._mode;return s.create_htmlCollection(t,function(e){var t=e.classList;return l.orderedSet_contains(t._tokenSet,r,n)})},t.node_locateANamespacePrefix=function e(t,r){if(t._namespace===r&&null!==t._namespacePrefix)return t._namespacePrefix;for(var n=0;n=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var o=r(6),i=r(3),a=r(9),s=r(29),l=r(17),u=r(107),c=r(37);t.text_contiguousTextNodes=function(e,t){var r;return void 0===t&&(t=!1),(r={})[Symbol.iterator]=function(){for(var r=e;r&&i.Guard.isTextNode(r._previousSibling);)r=r._previousSibling;return{next:function(){if(r&&!t&&r===e&&(r=i.Guard.isTextNode(r._nextSibling)?r._nextSibling:null),null===r)return{done:!0,value:null};var n={done:!1,value:r};return r=i.Guard.isTextNode(r._nextSibling)?r._nextSibling:null,n}}},r},t.text_contiguousExclusiveTextNodes=function(e,t){var r;return void 0===t&&(t=!1),(r={})[Symbol.iterator]=function(){for(var r=e;r&&i.Guard.isExclusiveTextNode(r._previousSibling);)r=r._previousSibling;return{next:function(){if(r&&!t&&r===e&&(r=i.Guard.isExclusiveTextNode(r._nextSibling)?r._nextSibling:null),null===r)return{done:!0,value:null};var n={done:!1,value:r};return r=i.Guard.isExclusiveTextNode(r._nextSibling)?r._nextSibling:null,n}}},r},t.text_descendantTextContent=function(e){for(var t="",r=l.tree_getFirstDescendantNode(e,!1,!1,function(e){return i.Guard.isTextNode(e)});null!==r;)t+=r._data,r=l.tree_getNextDescendantNode(e,r,!1,!1,function(e){return i.Guard.isTextNode(e)});return t},t.text_split=function(e,t){var r,i,d=e._data.length;if(t>d)throw new a.IndexSizeError;var p=d-t,f=u.characterData_substringData(e,t,p),h=s.create_text(e._nodeDocument,f),m=e._parent;if(null!==m){c.mutation_insert(h,m,e._nextSibling);try{for(var g=n(o.dom.rangeList),y=g.next();!y.done;y=g.next()){var v=y.value;v._start[0]===e&&v._start[1]>t&&(v._start[0]=h,v._start[1]-=t),v._end[0]===e&&v._end[1]>t&&(v._end[0]=h,v._end[1]-=t);var b=l.tree_index(e);v._start[0]===m&&v._start[1]===b+1&&v._start[1]++,v._end[0]===m&&v._end[1]===b+1&&v._end[1]++}}catch(e){r={error:e}}finally{try{y&&!y.done&&(i=g.return)&&i.call(g)}finally{if(r)throw r.error}}}return u.characterData_replaceData(e,t,p,""),h}},function(e,t,r){"use strict";var n=r(4),o=r(41),i=r(24),a=r(48),s=[].join,l=o!=Object,u=a("join",",");n({target:"Array",proto:!0,forced:l||!u},{join:function(e){return s.call(i(this),void 0===e?",":e)}})},function(e,t,r){var n=r(4),o=r(83),i=String.fromCharCode,a=String.fromCodePoint;n({target:"String",stat:!0,forced:!!a&&1!=a.length},{fromCodePoint:function(e){for(var t,r=[],n=arguments.length,a=0;n>a;){if(t=+arguments[a++],o(t,1114111)!==t)throw RangeError(t+" is not a valid code point");r.push(t<65536?i(t):i(55296+((t-=65536)>>10),t%1024+56320))}return r.join("")}})},function(e,t,r){"use strict";var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a};Object.defineProperty(t,"__esModule",{value:!0});var o=r(111),i=function(){function e(e,t){this._options={skipWhitespaceOnlyText:!1},this.err={line:-1,col:-1,index:-1,str:""},this._str=e,this._index=0,this._length=e.length,t&&(this._options.skipWhitespaceOnlyText=t.skipWhitespaceOnlyText||!1)}return e.prototype.nextToken=function(){if(this.eof())return{type:o.TokenType.EOF};var t=this.skipIfStartsWith("<")?this.openBracket():this.text();return this._options.skipWhitespaceOnlyText&&t.type===o.TokenType.Text&&e.isWhiteSpaceToken(t)&&(t=this.nextToken()),t},e.prototype.openBracket=function(){return this.skipIfStartsWith("?")?this.skipIfStartsWith("xml")?e.isSpace(this._str[this._index])?this.declaration():(this.seek(-3),this.pi()):this.pi():this.skipIfStartsWith("!")?this.skipIfStartsWith("--")?this.comment():this.skipIfStartsWith("[CDATA[")?this.cdata():this.skipIfStartsWith("DOCTYPE")?this.doctype():void this.throwError("Invalid '!' in opening tag."):this.skipIfStartsWith("/")?this.closeTag():this.openTag()},e.prototype.declaration=function(){for(var e="",t="",r="";!this.eof();){if(this.skipSpace(),this.skipIfStartsWith("?>"))return{type:o.TokenType.Declaration,version:e,encoding:t,standalone:r};var i=n(this.attribute(),2),a=i[0],s=i[1];"version"===a?e=s:"encoding"===a?t=s:"standalone"===a?r=s:this.throwError("Invalid attribute name: "+a)}this.throwError("Missing declaration end symbol `?>`")},e.prototype.doctype=function(){var e="",t="";this.skipSpace();var r=this.takeUntil2("[",">",!0);return this.skipSpace(),this.skipIfStartsWith("PUBLIC")?(e=this.quotedString(),t=this.quotedString()):this.skipIfStartsWith("SYSTEM")&&(t=this.quotedString()),this.skipSpace(),this.skipIfStartsWith("[")&&(this.skipUntil("]"),this.skipIfStartsWith("]")||this.throwError("Missing end bracket of DTD internal subset")),this.skipSpace(),this.skipIfStartsWith(">")||this.throwError("Missing doctype end symbol `>`"),{type:o.TokenType.DocType,name:r,pubId:e,sysId:t}},e.prototype.pi=function(){var e=this.takeUntilStartsWith("?>",!0);if(this.eof()&&this.throwError("Missing processing instruction end symbol `?>`"),this.skipSpace(),this.skipIfStartsWith("?>"))return{type:o.TokenType.PI,target:e,data:""};var t=this.takeUntilStartsWith("?>");return this.eof()&&this.throwError("Missing processing instruction end symbol `?>`"),this.seek(2),{type:o.TokenType.PI,target:e,data:t}},e.prototype.text=function(){var e=this.takeUntil("<");return{type:o.TokenType.Text,data:e}},e.prototype.comment=function(){var e=this.takeUntilStartsWith("--\x3e");return this.eof()&&this.throwError("Missing comment end symbol `--\x3e`"),this.seek(3),{type:o.TokenType.Comment,data:e}},e.prototype.cdata=function(){var e=this.takeUntilStartsWith("]]>");return this.eof()&&this.throwError("Missing CDATA end symbol `]>`"),this.seek(3),{type:o.TokenType.CDATA,data:e}},e.prototype.openTag=function(){this.skipSpace();var e=this.takeUntil2(">","/",!0);if(this.skipSpace(),this.skipIfStartsWith(">"))return{type:o.TokenType.Element,name:e,attributes:[],selfClosing:!1};if(this.skipIfStartsWith("/>"))return{type:o.TokenType.Element,name:e,attributes:[],selfClosing:!0};for(var t=[];!this.eof();){if(this.skipSpace(),this.skipIfStartsWith(">"))return{type:o.TokenType.Element,name:e,attributes:t,selfClosing:!1};if(this.skipIfStartsWith("/>"))return{type:o.TokenType.Element,name:e,attributes:t,selfClosing:!0};var r=this.attribute();t.push(r)}this.throwError("Missing opening element tag end symbol `>`")},e.prototype.closeTag=function(){this.skipSpace();var e=this.takeUntil(">",!0);return this.skipSpace(),this.skipIfStartsWith(">")||this.throwError("Missing closing element tag end symbol `>`"),{type:o.TokenType.ClosingTag,name:e}},e.prototype.attribute=function(){this.skipSpace();var e=this.takeUntil("=",!0);return this.skipSpace(),this.skipIfStartsWith("=")||this.throwError("Missing equals sign before attribute value"),[e,this.quotedString()]},e.prototype.quotedString=function(){this.skipSpace();var t=this.take(1);e.isQuote(t)||this.throwError("Missing start quote character before quoted value");var r=this.takeUntil(t);return this.skipIfStartsWith(t)||this.throwError("Missing end quote character after quoted value"),r},e.prototype.eof=function(){return this._index>=this._length},e.prototype.skipIfStartsWith=function(e){var t=e.length;if(1===t)return this._str[this._index]===e&&(this._index++,!0);for(var r=0;rthis._length&&(this._index=this._length)},e.prototype.skipSpace=function(){for(;!this.eof()&&e.isSpace(this._str[this._index]);)this._index++},e.prototype.take=function(e){if(1===e)return this._str[this._index++];var t=this._index;return this.seek(e),this._str.slice(t,this._index)},e.prototype.takeUntil=function(t,r){void 0===r&&(r=!1);for(var n=this._index;this._indexthis._index){i=r.index;break}throw this.err={line:n,col:this._index-o,index:this._index,str:this._str.substring(o,i)},new Error(e+"\nIndex: "+this.err.index+"\nLn: "+this.err.line+", Col: "+this.err.col+"\nInput: "+this.err.str)},e.prototype[Symbol.iterator]=function(){return this._index=0,{next:function(){var e=this.nextToken();return e.type===o.TokenType.EOF?{done:!0,value:null}:{done:!1,value:e}}.bind(this)}},e}();t.XMLStringLexer=i},function(e,t,r){"use strict";var n=r(39);e.exports=new n({include:[r(182)]})},function(e,t,r){"use strict";var n=r(39);e.exports=new n({include:[r(113)],implicit:[r(289),r(290),r(291),r(292)]})},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(91),o=r(1),i=r(3),a=r(77),s=r(109);function l(e,t){var r=c(void 0===e||u(e)?e:n.DefaultBuilderOptions),o=u(e)?t:e,i=s.createDocument();d(i,r);var l=new a.XMLBuilderImpl(i);return void 0!==o&&l.ele(o),l}function u(e){if(!o.isPlainObject(e))return!1;for(var t in e)if(e.hasOwnProperty(t)&&!n.XMLBuilderOptionKeys.has(t))return!1;return!0}function c(e){void 0===e&&(e={});var t=o.applyDefaults(e,n.DefaultBuilderOptions);if(0===t.convert.att.length||0===t.convert.ins.length||0===t.convert.text.length||0===t.convert.cdata.length||0===t.convert.comment.length)throw new Error("JS object converter strings cannot be zero length.");return t}function d(e,t,r){var n=e;n._xmlBuilderOptions=t,n._isFragment=r}t.builder=function(e,t){var r=c(u(e)?e:n.DefaultBuilderOptions),s=i.Guard.isNode(e)||o.isArray(e)?e:t;if(void 0===s)throw new Error("Invalid arguments.");if(o.isArray(s)){for(var l=[],d=0;d0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a},o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var i=r(91),a=r(1),s=r(217),l=r(2),u=r(3),c=r(0),d=r(109),p=r(7),f=r(276),h=function(){function e(e){this._domNode=e}return Object.defineProperty(e.prototype,"node",{get:function(){return this._domNode},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"options",{get:function(){return this._options},enumerable:!0,configurable:!0}),e.prototype.set=function(e){return this._options=a.applyDefaults(a.applyDefaults(this._options,e,!0),i.DefaultBuilderOptions),this},e.prototype.ele=function(t,r,o){var i,s,l,u,p,h;if(a.isObject(t))return new f.ObjectReader(this._options).parse(this,t);if(null!==t&&/^\s*0&&(void 0===e&&(e=t.slice(n+1)),t=t.slice(0,n)),void 0===e)e=r?this._options.defaultNamespace.ele:this._options.defaultNamespace.att;else if(null!==e&&"@"===e[0]){var o=e.slice(1);if(void 0===(e=this._options.namespaceAlias[o]))throw new Error("Namespace alias `"+o+"` is not defined. "+this._debugInfo())}return[e,t]},e.prototype._updateNamespace=function(t){var r,i,a,s,l=this._domNode;if(u.Guard.isElementNode(l)&&null!==t&&l.namespaceURI!==t){var d=n(c.namespace_extractQName(l.prefix?l.prefix+":"+l.localName:l.localName),2),p=d[0],f=d[1],h=c.create_element(this._doc,f,t,p);try{for(var m=o(l.attributes),g=m.next();!g.done;g=m.next()){var y=g.value,v=y.prefix?y.prefix+":"+y.localName:y.localName,b=n(c.namespace_extractQName(v),1)[0],x=y.namespaceURI;null===x&&null!==b&&(x=l.lookupNamespaceURI(b)),null===x?h.setAttribute(v,y.value):h.setAttributeNS(x,v,y.value)}}catch(e){r={error:e}}finally{try{g&&!g.done&&(i=m.return)&&i.call(m)}finally{if(r)throw r.error}}var _=l.parentNode;if(null===_)throw new Error("Parent node is null."+this._debugInfo());_.replaceChild(h,l),this._domNode=h;try{for(var S=o(l.childNodes),C=S.next();!C.done;C=S.next()){var T=C.value.cloneNode(!0);if(h.appendChild(T),u.Guard.isElementNode(T)){var w=n(c.namespace_extractQName(T.prefix?T.prefix+":"+T.localName:T.localName),1)[0],A=h.lookupNamespaceURI(w);new e(T)._updateNamespace(A)}}}catch(e){a={error:e}}finally{try{C&&!C.done&&(s=S.return)&&s.call(S)}finally{if(a)throw a.error}}}},Object.defineProperty(e.prototype,"_doc",{get:function(){var e=this.node;if(u.Guard.isDocumentNode(e))return e;var t=e.ownerDocument;if(!t)throw new Error("Owner document is null. "+this._debugInfo());return t},enumerable:!0,configurable:!0}),e.prototype._debugInfo=function(e){var t=this.node,r=t.parentNode;e=e||t.nodeName;var n=r?r.nodeName:"";return n?"node: <"+e+">, parent: <"+n+">":"node: <"+e+">"},Object.defineProperty(e.prototype,"_options",{get:function(){var e=this._doc;if(void 0===e._xmlBuilderOptions)throw new Error("Builder options is not set.");return e._xmlBuilderOptions},set:function(e){this._doc._xmlBuilderOptions=e},enumerable:!0,configurable:!0}),e}();t.XMLBuilderImpl=h},function(e,t,r){var n=r(11),o=r(117),i=n.WeakMap;e.exports="function"==typeof i&&/native code/.test(o(i))},function(e,t,r){var n=r(46),o=r(82),i=r(85),a=r(18);e.exports=n("Reflect","ownKeys")||function(e){var t=o.f(a(e)),r=i.f;return r?t.concat(r(e)):t}},function(e,t,r){var n=r(16),o=r(15),i=r(18),a=r(61);e.exports=n?Object.defineProperties:function(e,t){i(e);for(var r,n=a(t),s=n.length,l=0;s>l;)o.f(e,r=n[l++],t[r]);return e}},function(e,t,r){var n=r(46);e.exports=n("document","documentElement")},function(e,t,r){var n=r(24),o=r(82).f,i={}.toString,a="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];e.exports.f=function(e){return a&&"[object Window]"==i.call(e)?function(e){try{return o(e)}catch(e){return a.slice()}}(e):o(n(e))}},function(e,t,r){"use strict";var n=r(4),o=r(36).every,i=r(48),a=r(28),s=i("every"),l=a("every");n({target:"Array",proto:!0,forced:!s||!l},{every:function(e){return o(this,e,arguments.length>1?arguments[1]:void 0)}})},function(e,t,r){"use strict";var n=r(4),o=r(36).filter,i=r(63),a=r(28),s=i("filter"),l=a("filter");n({target:"Array",proto:!0,forced:!s||!l},{filter:function(e){return o(this,e,arguments.length>1?arguments[1]:void 0)}})},function(e,t,r){var n=r(46);e.exports=n("navigator","userAgent")||""},function(e,t,r){"use strict";var n=r(4),o=r(36).find,i=r(130),a=r(28),s=!0,l=a("find");"find"in[]&&Array(1).find(function(){s=!1}),n({target:"Array",proto:!0,forced:s||!l},{find:function(e){return o(this,e,arguments.length>1?arguments[1]:void 0)}}),i("find")},function(e,t,r){"use strict";var n=r(131).IteratorPrototype,o=r(60),i=r(40),a=r(62),s=r(49),l=function(){return this};e.exports=function(e,t,r){var u=t+" Iterator";return e.prototype=o(n,{next:i(1,r)}),a(e,u,!1,!0),s[u]=l,e}},function(e,t,r){var n=r(8);e.exports=!n(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})},function(e,t,r){var n=r(13);e.exports=function(e){if(!n(e)&&null!==e)throw TypeError("Can't set "+String(e)+" as a prototype");return e}},function(e,t,r){"use strict";var n=r(4),o=r(36).map,i=r(63),a=r(28),s=i("map"),l=a("map");n({target:"Array",proto:!0,forced:!s||!l},{map:function(e){return o(this,e,arguments.length>1?arguments[1]:void 0)}})},function(e,t,r){"use strict";var n=r(4),o=r(200).left,i=r(48),a=r(28),s=i("reduce"),l=a("reduce",{1:0});n({target:"Array",proto:!0,forced:!s||!l},{reduce:function(e){return o(this,e,arguments.length,arguments.length>1?arguments[1]:void 0)}})},function(e,t,r){var n=r(127),o=r(27),i=r(41),a=r(26),s=function(e){return function(t,r,s,l){n(r);var u=o(t),c=i(u),d=a(u.length),p=e?d-1:0,f=e?-1:1;if(s<2)for(;;){if(p in c){l=c[p],p+=f;break}if(p+=f,e?p<0:d<=p)throw TypeError("Reduce of empty array with no initial value")}for(;e?p>=0:d>p;p+=f)p in c&&(l=r(l,c[p],p,u));return l}};e.exports={left:s(!1),right:s(!0)}},function(e,t,r){"use strict";var n=r(4),o=r(36).some,i=r(48),a=r(28),s=i("some"),l=a("some");n({target:"Array",proto:!0,forced:!s||!l},{some:function(e){return o(this,e,arguments.length>1?arguments[1]:void 0)}})},function(e,t,r){"use strict";var n=r(90),o=r(135);e.exports=n?{}.toString:function(){return"[object "+o(this)+"]"}},function(e,t){e.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}},function(e,t,r){var n=r(8);e.exports=!n(function(){return Object.isExtensible(Object.preventExtensions({}))})},function(e,t,r){var n=r(5),o=r(49),i=n("iterator"),a=Array.prototype;e.exports=function(e){return void 0!==e&&(o.Array===e||a[i]===e)}},function(e,t,r){var n=r(135),o=r(49),i=r(5)("iterator");e.exports=function(e){if(null!=e)return e[i]||e["@@iterator"]||o[n(e)]}},function(e,t,r){var n=r(18);e.exports=function(e,t,r,o){try{return o?t(n(r)[0],r[1]):t(r)}catch(t){var i=e.return;throw void 0!==i&&n(i.call(e)),t}}},function(e,t,r){var n=r(5)("iterator"),o=!1;try{var i=0,a={next:function(){return{done:!!i++}},return:function(){o=!0}};a[n]=function(){return this},Array.from(a,function(){throw 2})}catch(e){}e.exports=function(e,t){if(!t&&!o)return!1;var r=!1;try{var i={};i[n]=function(){return{next:function(){return{done:r=!0}}}},e(i)}catch(e){}return r}},function(e,t,r){var n=r(13),o=r(133);e.exports=function(e,t,r){var i,a;return o&&"function"==typeof(i=t.constructor)&&i!==r&&n(a=i.prototype)&&a!==r.prototype&&o(e,a),e}},function(e,t,r){var n=r(25);e.exports=function(e,t,r){for(var o in t)n(e,o,t[o],r);return e}},function(e,t,r){"use strict";var n=r(46),o=r(15),i=r(5),a=r(16),s=i("species");e.exports=function(e){var t=n(e),r=o.f;a&&t&&!t[s]&&r(t,s,{configurable:!0,get:function(){return this}})}},function(e,t,r){"use strict";var n=this&&this.__generator||function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(o=2&i[0]?n.return:i[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,i[1])).done)return o;switch(n=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,n=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e){void 0===e&&(e=1e3),this._items=new Set,this._limit=e}return e.prototype.add=function(e){if(this._items.add(e),this._items.size>this._limit){var t=this._items.values().next();t.done||this._items.delete(t.value)}return this},e.prototype.delete=function(e){return this._items.delete(e)},e.prototype.has=function(e){return this._items.has(e)},e.prototype.clear=function(){this._items.clear()},Object.defineProperty(e.prototype,"size",{get:function(){return this._items.size},enumerable:!0,configurable:!0}),e.prototype.forEach=function(e,t){var r=this;this._items.forEach(function(n){return e.call(t,n,n,r)})},e.prototype.keys=function(){return n(this,function(e){switch(e.label){case 0:return[5,o(this._items.keys())];case 1:return e.sent(),[2]}})},e.prototype.values=function(){return n(this,function(e){switch(e.label){case 0:return[5,o(this._items.values())];case 1:return e.sent(),[2]}})},e.prototype.entries=function(){return n(this,function(e){switch(e.label){case 0:return[5,o(this._items.entries())];case 1:return e.sent(),[2]}})},e.prototype[Symbol.iterator]=function(){return n(this,function(e){switch(e.label){case 0:return[5,o(this._items)];case 1:return e.sent(),[2]}})},Object.defineProperty(e.prototype,Symbol.toStringTag,{get:function(){return"FixedSizeSet"},enumerable:!0,configurable:!0}),e}();t.FixedSizeSet=i},function(e,t,r){"use strict";var n=this&&this.__generator||function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(o=2&i[0]?n.return:i[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,i[1])).done)return o;switch(n=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,n=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e){void 0===e&&(e=1e3),this._items=new Map,this._limit=e}return e.prototype.get=function(e){return this._items.get(e)},e.prototype.set=function(e,t){if(this._items.set(e,t),this._items.size>this._limit){var r=this._items.keys().next();r.done||this._items.delete(r.value)}},e.prototype.delete=function(e){return this._items.delete(e)},e.prototype.has=function(e){return this._items.has(e)},e.prototype.clear=function(){this._items.clear()},Object.defineProperty(e.prototype,"size",{get:function(){return this._items.size},enumerable:!0,configurable:!0}),e.prototype.forEach=function(e,t){this._items.forEach(function(r,n){return e.call(t,n,r)})},e.prototype.keys=function(){return n(this,function(e){switch(e.label){case 0:return[5,o(this._items.keys())];case 1:return e.sent(),[2]}})},e.prototype.values=function(){return n(this,function(e){switch(e.label){case 0:return[5,o(this._items.values())];case 1:return e.sent(),[2]}})},e.prototype.entries=function(){return n(this,function(e){switch(e.label){case 0:return[5,o(this._items.entries())];case 1:return e.sent(),[2]}})},e.prototype[Symbol.iterator]=function(){return n(this,function(e){switch(e.label){case 0:return[5,o(this._items)];case 1:return e.sent(),[2]}})},Object.defineProperty(e.prototype,Symbol.toStringTag,{get:function(){return"ObjectCache"},enumerable:!0,configurable:!0}),e}();t.ObjectCache=i},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(e){void 0===e&&(e=1e3),this._items=new Map,this._limit=e}return e.prototype.check=function(e,t){if(this._items.get(e)===t)return!0;if(this._items.get(t)===e)return!1;var r=Math.random()<.5;if(r?this._items.set(e,t):this._items.set(t,e),this._items.size>this._limit){var n=this._items.keys().next();n.done||this._items.delete(n.value)}return r},e}();t.CompareCache=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(e){this._initialized=!1,this._value=void 0,this._initFunc=e}return Object.defineProperty(e.prototype,"value",{get:function(){return this._initialized||(this._value=this._initFunc(),this._initialized=!0),this._value},enumerable:!0,configurable:!0}),e}();t.Lazy=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(e){this._pointer=0,this._chars=Array.from(e),this._length=this._chars.length}return Object.defineProperty(e.prototype,"eof",{get:function(){return this._pointer>=this._length},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"length",{get:function(){return this._length},enumerable:!0,configurable:!0}),e.prototype.codePoint=function(){if(void 0===this._codePoint)if(this.eof)this._codePoint=-1;else{var e=this._chars[this._pointer].codePointAt(0);this._codePoint=void 0!==e?e:-1}return this._codePoint},e.prototype.c=function(){return void 0===this._c&&(this._c=this.eof?"":this._chars[this._pointer]),this._c},e.prototype.remaining=function(){return void 0===this._remaining&&(this._remaining=this.eof?"":this._chars.slice(this._pointer+1).join("")),this._remaining},e.prototype.substring=function(){return void 0===this._substring&&(this._substring=this.eof?"":this._chars.slice(this._pointer).join("")),this._substring},Object.defineProperty(e.prototype,"pointer",{get:function(){return this._pointer},set:function(e){e!==this._pointer&&(this._pointer=e,this._codePoint=void 0,this._c=void 0,this._remaining=void 0,this._substring=void 0)},enumerable:!0,configurable:!0}),e}();t.StringWalker=n},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(218);t.MapWriter=n.MapWriter;var o=r(258);t.XMLWriter=o.XMLWriter;var i=r(67);t.ObjectWriter=i.ObjectWriter;var a=r(260);t.JSONWriter=a.JSONWriter;var s=r(261);t.YAMLWriter=s.YAMLWriter},function(e,t,r){"use strict";r(19),r(219),r(20),r(22),r(23);var n,o=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var i=r(1),a=r(67),s=function(e){function t(t,r){var n=e.call(this,t)||this;return n._writerOptions=i.applyDefaults(r,{format:"map",wellFormed:!1,group:!1,verbose:!1}),n}return o(t,e),t.prototype.serialize=function(e){var t=i.applyDefaults(this._writerOptions,{format:"object",wellFormed:!1,verbose:!1}),r=new a.ObjectWriter(this._builderOptions,t).serialize(e);return this._convertObject(r)},t.prototype._convertObject=function(e){if(i.isArray(e)){for(var t=0;t=51||!o(function(){var e=[];return e[h]=!1,e.concat()[0]!==e}),g=d("concat"),y=function(e){if(!a(e))return!1;var t=e[h];return void 0!==t?!!t:i(e)};n({target:"Array",proto:!0,forced:!m||!g},{concat:function(e){var t,r,n,o,i,a=s(this),d=c(a,0),p=0;for(t=-1,n=arguments.length;t9007199254740991)throw TypeError("Maximum allowed index exceeded");for(r=0;r=9007199254740991)throw TypeError("Maximum allowed index exceeded");u(d,p++,i)}return d.length=p,d}})},function(e,t,r){"use strict";var n=r(8);function o(e,t){return RegExp(e,t)}t.UNSUPPORTED_Y=n(function(){var e=o("a","y");return e.lastIndex=2,null!=e.exec("abcd")}),t.BROKEN_CARET=n(function(){var e=o("^r","gy");return e.lastIndex=2,null!=e.exec("str")})},function(e,t,r){var n=r(223);e.exports=function(e){if(n(e))throw TypeError("The method doesn't accept regular expressions");return e}},function(e,t,r){var n=r(13),o=r(42),i=r(5)("match");e.exports=function(e){var t;return n(e)&&(void 0!==(t=e[i])?!!t:"RegExp"==o(e))}},function(e,t,r){var n=r(5)("match");e.exports=function(e){var t=/./;try{"/./"[e](t)}catch(r){try{return t[n]=!1,"/./"[e](t)}catch(e){}}return!1}},function(e,t,r){"use strict";r(68);var n=r(25),o=r(8),i=r(5),a=r(93),s=r(21),l=i("species"),u=!o(function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$")}),c="$0"==="a".replace(/./,"$0"),d=i("replace"),p=!!/./[d]&&""===/./[d]("a","$0"),f=!o(function(){var e=/(?:)/,t=e.exec;e.exec=function(){return t.apply(this,arguments)};var r="ab".split(e);return 2!==r.length||"a"!==r[0]||"b"!==r[1]});e.exports=function(e,t,r,d){var h=i(e),m=!o(function(){var t={};return t[h]=function(){return 7},7!=""[e](t)}),g=m&&!o(function(){var t=!1,r=/a/;return"split"===e&&((r={}).constructor={},r.constructor[l]=function(){return r},r.flags="",r[h]=/./[h]),r.exec=function(){return t=!0,null},r[h](""),!t});if(!m||!g||"replace"===e&&(!u||!c||p)||"split"===e&&!f){var y=/./[h],v=r(h,""[e],function(e,t,r,n,o){return t.exec===a?m&&!o?{done:!0,value:y.call(t,r,n)}:{done:!0,value:e.call(r,t,n)}:{done:!1}},{REPLACE_KEEPS_$0:c,REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE:p}),b=v[0],x=v[1];n(String.prototype,e,b),n(RegExp.prototype,h,2==t?function(e,t){return x.call(e,this,t)}:function(e){return x.call(e,this)})}d&&s(RegExp.prototype[h],"sham",!0)}},function(e,t,r){"use strict";var n=r(137).charAt;e.exports=function(e,t,r){return t+(r?n(e,t).length:1)}},function(e,t,r){var n=r(42),o=r(93);e.exports=function(e,t){var r=e.exec;if("function"==typeof r){var i=r.call(e,t);if("object"!=typeof i)throw TypeError("RegExp exec method returned something other than an Object or null");return i}if("RegExp"!==n(e))throw TypeError("RegExp#exec called on incompatible receiver");return o.call(e,t)}},function(e,t,r){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0});var n=r(96);t.forgivingBase64Encode=function(t){return e.from(t).toString("base64")},t.forgivingBase64Decode=function(t){return""===t?"":((t=t.replace(n.ASCIIWhiteSpace,"")).length%4==0&&(t.endsWith("==")?t=t.substr(0,t.length-2):t.endsWith("=")&&(t=t.substr(0,t.length-1))),t.length%4==1?null:/[0-9A-Za-z+/]/.test(t)?e.from(t,"base64").toString("utf8"):null)}}).call(this,r(145).Buffer)},function(e,t,r){"use strict";t.byteLength=function(e){var t=l(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,n=l(e),a=n[0],s=n[1],u=new i(function(e,t,r){return 3*(t+r)/4-r}(0,a,s)),c=0,d=s>0?a-4:a;for(r=0;r>16&255,u[c++]=t>>8&255,u[c++]=255&t;return 2===s&&(t=o[e.charCodeAt(r)]<<2|o[e.charCodeAt(r+1)]>>4,u[c++]=255&t),1===s&&(t=o[e.charCodeAt(r)]<<10|o[e.charCodeAt(r+1)]<<4|o[e.charCodeAt(r+2)]>>2,u[c++]=t>>8&255,u[c++]=255&t),u},t.fromByteArray=function(e){for(var t,r=e.length,o=r%3,i=[],a=0,s=r-o;as?s:a+16383));return 1===o?(t=e[r-1],i.push(n[t>>2]+n[t<<4&63]+"==")):2===o&&(t=(e[r-2]<<8)+e[r-1],i.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"=")),i.join("")};for(var n=[],o=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)n[s]=a[s],o[a.charCodeAt(s)]=s;function l(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function u(e,t,r){for(var o,i,a=[],s=t;s>18&63]+n[i>>12&63]+n[i>>6&63]+n[63&i]);return a.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},function(e,t){t.read=function(e,t,r,n,o){var i,a,s=8*o-n-1,l=(1<>1,c=-7,d=r?o-1:0,p=r?-1:1,f=e[t+d];for(d+=p,i=f&(1<<-c)-1,f>>=-c,c+=s;c>0;i=256*i+e[t+d],d+=p,c-=8);for(a=i&(1<<-c)-1,i>>=-c,c+=n;c>0;a=256*a+e[t+d],d+=p,c-=8);if(0===i)i=1-u;else{if(i===l)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,n),i-=u}return(f?-1:1)*a*Math.pow(2,i-n)},t.write=function(e,t,r,n,o,i){var a,s,l,u=8*i-o-1,c=(1<>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:i-1,h=n?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=c):(a=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-a))<1&&(a--,l*=2),(t+=a+d>=1?p/l:p*Math.pow(2,1-d))*l>=2&&(a++,l/=2),a+d>=c?(s=0,a=c):a+d>=1?(s=(t*l-1)*Math.pow(2,o),a+=d):(s=t*Math.pow(2,d-1)*Math.pow(2,o),a=0));o>=8;e[r+f]=255&s,f+=h,s/=256,o-=8);for(a=a<0;e[r+f]=255&a,f+=h,a/=256,u-=8);e[r+f-h]|=128*m}},function(e,t){var r={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==r.call(e)}},function(e,t,r){"use strict";var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var o=r(1);function i(e){var t,r;if(null===e||o.isString(e)||o.isNumber(e))return e;if(o.isArray(e)){var a=new Array;try{for(var s=n(e),l=s.next();!l.done;l=s.next()){var u=l.value;a.push(i(u))}}catch(e){t={error:e}}finally{try{l&&!l.done&&(r=s.return)&&r.call(s)}finally{if(t)throw t.error}}return a}if(o.isObject(e)){for(var c in a=new Map,e)if(e.hasOwnProperty(c)){var d=e[c];a.set(c,i(d))}return a}return e}t.parseJSONFromBytes=function(e){var t=o.utf8Decode(e);return JSON.parse.call(void 0,t)},t.serializeJSONToBytes=function(e){var t=JSON.stringify.call(void 0,e);return o.utf8Encode(t)},t.parseJSONIntoInfraValues=function(e){return i(JSON.parse.call(void 0,e))},t.convertAJSONDerivedJavaScriptValueToAnInfraValue=i},function(e,t,r){"use strict";var n=this&&this.__generator||function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(o=2&i[0]?n.return:i[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,i[1])).done)return o;switch(n=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,n=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a},i=this&&this.__spread||function(){for(var e=[],t=0;t=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var s=r(1);t.append=function(e,t){e.push(t)},t.extend=function(e,t){e.push.apply(e,i(t))},t.prepend=function(e,t){e.unshift(t)},t.replace=function(e,t,r){var n,o,i=0;try{for(var l=a(e),u=l.next();!u.done;u=l.next()){var c=u.value;if(s.isFunction(t))t.call(null,c)&&(e[i]=r);else if(c===t)return void(e[i]=r);i++}}catch(e){n={error:e}}finally{try{u&&!u.done&&(o=l.return)&&o.call(l)}finally{if(n)throw n.error}}},t.insert=function(e,t,r){e.splice(r,0,t)},t.remove=function(e,t){for(var r=e.length;r--;){var n=e[r];if(s.isFunction(t))t.call(null,n)&&e.splice(r,1);else if(n===t)return void e.splice(r,1)}},t.empty=function(e){e.length=0},t.contains=function(e,t){var r,n;try{for(var o=a(e),i=o.next();!i.done;i=o.next()){var l=i.value;if(s.isFunction(t)){if(t.call(null,l))return!0}else if(l===t)return!0}}catch(e){r={error:e}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return!1},t.size=function(e,t){var r,n;if(void 0===t)return e.length;var o=0;try{for(var i=a(e),s=i.next();!s.done;s=i.next()){var l=s.value;t.call(null,l)&&o++}}catch(e){r={error:e}}finally{try{s&&!s.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}return o},t.isEmpty=function(e){return 0===e.length},t.forEach=function(e,t){var r,o,i,s,l,u;return n(this,function(n){switch(n.label){case 0:return void 0!==t?[3,2]:[5,a(e)];case 1:return n.sent(),[3,9];case 2:n.trys.push([2,7,8,9]),r=a(e),o=r.next(),n.label=3;case 3:return o.done?[3,6]:(i=o.value,t.call(null,i)?[4,i]:[3,5]);case 4:n.sent(),n.label=5;case 5:return o=r.next(),[3,3];case 6:return[3,9];case 7:return s=n.sent(),l={error:s},[3,9];case 8:try{o&&!o.done&&(u=r.return)&&u.call(r)}finally{if(l)throw l.error}return[7];case 9:return[2]}})},t.clone=function(e){return new(Array.bind.apply(Array,i([void 0],e)))},t.sortInAscendingOrder=function(e,t){return e.sort(function(e,r){return t.call(null,e,r)?-1:1})},t.sortInDescendingOrder=function(e,t){return e.sort(function(e,r){return t.call(null,e,r)?1:-1})}},function(e,t,r){"use strict";var n=this&&this.__generator||function(e,t){var r,n,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(o=2&i[0]?n.return:i[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,i[1])).done)return o;switch(n=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,n=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},i=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a},a=this&&this.__spread||function(){for(var e=[],t=0;t0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},i=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a},a=this&&this.__spread||function(){for(var e=[],t=0;t=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var o=r(96),i=r(147),a=r(146),s=r(1);function l(e,t){for(var r=0;;){var n=r=65&&l<=90?String.fromCodePoint(l+32):s}}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return o}function p(e){return e.replace(/^[\t\n\f\r ]+/,"").replace(/[\t\n\f\r ]+$/,"")}function f(e,t,r){if(!s.isArray(t))return f(e,Array.from(t),r);for(var n="";r.position=97&&l<=122?String.fromCodePoint(l-32):s}}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return o},t.asciiCaseInsensitiveMatch=function(e,t){return d(e)===d(t)},t.asciiEncode=function(e){return console.assert(c(e),"asciiEncode requires an ASCII string."),u(e)},t.asciiDecode=function(e){var t,r;try{for(var o=n(e),s=o.next();!s.done;s=o.next()){var l=s.value;console.assert(a.isASCIIByte(l),"asciiDecode requires an ASCII byte sequence.")}}catch(e){t={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}return i.isomorphicDecode(e)},t.stripNewlines=function(e){return e.replace(/[\n\r]/g,"")},t.normalizeNewlines=function(e){return e.replace(/\r\n/g,"\n").replace(/\r/g,"\n")},t.stripLeadingAndTrailingASCIIWhitespace=p,t.stripAndCollapseASCIIWhitespace=function(e){return p(e.replace(/[\t\n\f\r ]{2,}/g," "))},t.collectASequenceOfCodePoints=f,t.skipASCIIWhitespace=h,t.strictlySplit=function e(t,r){if(!s.isArray(t))return e(Array.from(t),r);var n={position:0},o=[],i=f(function(e){return r!==e},t,n);for(o.push(i);n.position=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var o=r(97);t.abort_add=function(e,t){t._abortedFlag||t._abortAlgorithms.add(e)},t.abort_remove=function(e,t){t._abortAlgorithms.delete(e)},t.abort_signalAbort=function(e){var t,r;if(!e._abortedFlag){e._abortedFlag=!0;try{for(var i=n(e._abortAlgorithms),a=i.next();!a.done;a=i.next())a.value.call(e)}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}e._abortAlgorithms.clear(),o.event_fireAnEvent("abort",e)}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(150),o=function(){function e(){}return e.asNode=function(e){if(n.Guard.isNode(e))return e;throw new Error("Invalid object. Node expected.")},e}();t.Cast=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(){}return Object.defineProperty(e.prototype,"size",{get:function(){return 0},enumerable:!0,configurable:!0}),e.prototype.add=function(e){throw new Error("Cannot add to an empty set.")},e.prototype.clear=function(){},e.prototype.delete=function(e){return!1},e.prototype.forEach=function(e,t){},e.prototype.has=function(e){return!1},e.prototype[Symbol.iterator]=function(){return new o},e.prototype.entries=function(){return new o},e.prototype.keys=function(){return new o},e.prototype.values=function(){return new o},Object.defineProperty(e.prototype,Symbol.toStringTag,{get:function(){return"EmptySet"},enumerable:!0,configurable:!0}),e}();t.EmptySet=n;var o=function(){function e(){}return e.prototype[Symbol.iterator]=function(){return this},e.prototype.next=function(){return{done:!0,value:null}},e}()},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e[e.SchemeStart=0]="SchemeStart",e[e.Scheme=1]="Scheme",e[e.NoScheme=2]="NoScheme",e[e.SpecialRelativeOrAuthority=3]="SpecialRelativeOrAuthority",e[e.PathOrAuthority=4]="PathOrAuthority",e[e.Relative=5]="Relative",e[e.RelativeSlash=6]="RelativeSlash",e[e.SpecialAuthoritySlashes=7]="SpecialAuthoritySlashes",e[e.SpecialAuthorityIgnoreSlashes=8]="SpecialAuthorityIgnoreSlashes",e[e.Authority=9]="Authority",e[e.Host=10]="Host",e[e.Hostname=11]="Hostname",e[e.Port=12]="Port",e[e.File=13]="File",e[e.FileSlash=14]="FileSlash",e[e.FileHost=15]="FileHost",e[e.PathStart=16]="PathStart",e[e.Path=17]="Path",e[e.CannotBeABaseURLPath=18]="CannotBeABaseURLPath",e[e.Query=19]="Query",e[e.Fragment=20]="Fragment"}(t.ParserState||(t.ParserState={})),t.OpaqueOrigin=["","",null,null]},function(e,t,r){"use strict";var n=r(245),o=r(247);function i(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}t.parse=b,t.resolve=function(e,t){return b(e,!1,!0).resolve(t)},t.resolveObject=function(e,t){return e?b(e,!1,!0).resolveObject(t):t},t.format=function(e){return o.isString(e)&&(e=b(e)),e instanceof i?e.format():i.prototype.format.call(e)},t.Url=i;var a=/^([a-z0-9.+-]+:)/i,s=/:[0-9]*$/,l=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,u=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),c=["'"].concat(u),d=["%","/","?",";","#"].concat(c),p=["/","?","#"],f=/^[+a-z0-9A-Z_-]{0,63}$/,h=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,m={javascript:!0,"javascript:":!0},g={javascript:!0,"javascript:":!0},y={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},v=r(248);function b(e,t,r){if(e&&o.isObject(e)&&e instanceof i)return e;var n=new i;return n.parse(e,t,r),n}i.prototype.parse=function(e,t,r){if(!o.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var i=e.indexOf("?"),s=-1!==i&&i127?M+="x":M+=N[R];if(!M.match(f)){var B=I.slice(0,E),L=I.slice(E+1),k=N.match(h);k&&(B.push(k[1]),L.unshift(k[2])),L.length&&(b="/"+L.join(".")+b),this.hostname=B.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),P||(this.hostname=n.toASCII(this.hostname));var U=this.port?":"+this.port:"",V=this.hostname||"";this.host=V+U,this.href+=this.host,P&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==b[0]&&(b="/"+b))}if(!m[S])for(E=0,O=c.length;E0)&&r.host.split("@"))&&(r.auth=P.shift(),r.host=r.hostname=P.shift())),r.search=e.search,r.query=e.query,o.isNull(r.pathname)&&o.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r;if(!C.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var w=C.slice(-1)[0],A=(r.host||e.host||C.length>1)&&("."===w||".."===w)||""===w,E=0,D=C.length;D>=0;D--)"."===(w=C[D])?C.splice(D,1):".."===w?(C.splice(D,1),E++):E&&(C.splice(D,1),E--);if(!_&&!S)for(;E--;E)C.unshift("..");!_||""===C[0]||C[0]&&"/"===C[0].charAt(0)||C.unshift(""),A&&"/"!==C.join("/").substr(-1)&&C.push("");var P,I=""===C[0]||C[0]&&"/"===C[0].charAt(0);return T&&(r.hostname=r.host=I?"":C.length?C.shift():"",(P=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@"))&&(r.auth=P.shift(),r.host=r.hostname=P.shift())),(_=_||r.host&&C.length)&&!I&&C.unshift(""),C.length?r.pathname=C.join("/"):(r.pathname=null,r.path=null),o.isNull(r.pathname)&&o.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=e.auth||r.auth,r.slashes=r.slashes||e.slashes,r.href=r.format(),r},i.prototype.parseHost=function(){var e=this.host,t=s.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},function(e,t,r){(function(e,n){var o;!function(){t&&t.nodeType,e&&e.nodeType;var i="object"==typeof n&&n;i.global!==i&&i.window!==i&&i.self;var a,s=2147483647,l=/^xn--/,u=/[^\x20-\x7E]/,c=/[\x2E\u3002\uFF0E\uFF61]/g,d={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},p=Math.floor,f=String.fromCharCode;function h(e){throw new RangeError(d[e])}function m(e,t){for(var r=e.length,n=[];r--;)n[r]=t(e[r]);return n}function g(e,t){var r=e.split("@"),n="";return r.length>1&&(n=r[0]+"@",e=r[1]),n+m((e=e.replace(c,".")).split("."),t).join(".")}function y(e){for(var t,r,n=[],o=0,i=e.length;o=55296&&t<=56319&&o65535&&(t+=f((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+f(e)}).join("")}function b(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function x(e,t,r){var n=0;for(e=r?p(e/700):e>>1,e+=p(e/t);e>455;n+=36)e=p(e/35);return p(n+36*e/(e+38))}function _(e){var t,r,n,o,i,a,l,u,c,d,f,m=[],g=e.length,y=0,b=128,_=72;for((r=e.lastIndexOf("-"))<0&&(r=0),n=0;n=128&&h("not-basic"),m.push(e.charCodeAt(n));for(o=r>0?r+1:0;o=g&&h("invalid-input"),((u=(f=e.charCodeAt(o++))-48<10?f-22:f-65<26?f-65:f-97<26?f-97:36)>=36||u>p((s-y)/a))&&h("overflow"),y+=u*a,!(u<(c=l<=_?1:l>=_+26?26:l-_));l+=36)a>p(s/(d=36-c))&&h("overflow"),a*=d;_=x(y-i,t=m.length+1,0==i),p(y/t)>s-b&&h("overflow"),b+=p(y/t),y%=t,m.splice(y++,0,b)}return v(m)}function S(e){var t,r,n,o,i,a,l,u,c,d,m,g,v,_,S,C=[];for(g=(e=y(e)).length,t=128,r=0,i=72,a=0;a=t&&mp((s-r)/(v=n+1))&&h("overflow"),r+=(l-t)*v,t=l,a=0;as&&h("overflow"),m==t){for(u=r,c=36;!(u<(d=c<=i?1:c>=i+26?26:c-i));c+=36)S=u-d,_=36-d,C.push(f(b(d+S%_,0))),u=p(S/_);C.push(f(b(u,0))),i=x(r,v,n==o),r=0,++n}++r,++t}return C.join("")}a={version:"1.4.1",ucs2:{decode:y,encode:v},decode:_,encode:S,toASCII:function(e){return g(e,function(e){return u.test(e)?"xn--"+S(e):e})},toUnicode:function(e){return g(e,function(e){return l.test(e)?_(e.slice(4).toLowerCase()):e})}},void 0===(o=function(){return a}.call(t,r,t,e))||(e.exports=o)}()}).call(this,r(246)(e),r(78))},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,r){"use strict";e.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},function(e,t,r){"use strict";t.decode=t.parse=r(249),t.encode=t.stringify=r(250)},function(e,t,r){"use strict";function n(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.exports=function(e,t,r,i){t=t||"&",r=r||"=";var a={};if("string"!=typeof e||0===e.length)return a;var s=/\+/g;e=e.split(t);var l=1e3;i&&"number"==typeof i.maxKeys&&(l=i.maxKeys);var u=e.length;l>0&&u>l&&(u=l);for(var c=0;c=0?(d=m.substr(0,g),p=m.substr(g+1)):(d=m,p=""),f=decodeURIComponent(d),h=decodeURIComponent(p),n(a,f)?o(a[f])?a[f].push(h):a[f]=[a[f],h]:a[f]=h}return a};var o=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},function(e,t,r){"use strict";var n=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};e.exports=function(e,t,r,s){return t=t||"&",r=r||"=",null===e&&(e=void 0),"object"==typeof e?i(a(e),function(a){var s=encodeURIComponent(n(a))+r;return o(e[a])?i(e[a],function(e){return s+encodeURIComponent(n(e))}).join(t):s+encodeURIComponent(n(e[a]))}).join(t):s?encodeURIComponent(n(s))+r+encodeURIComponent(n(e)):""};var o=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function i(e,t){if(e.map)return e.map(t);for(var r=[],n=0;n=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var o=r(1);function i(e){return o.isBoolean(e)?e:e.capture||!1}t.eventTarget_flatten=i,t.eventTarget_flattenMore=function(e){var t=i(e),r=!1,n=!1;return o.isBoolean(e)||(r=e.once||!1,n=e.passive||!1),[t,n,r]},t.eventTarget_addEventListener=function(e,t){if(null!==t.callback){for(var r=0;r=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),i=r(29);t.parentNode_convertNodesIntoANode=function(e,t){for(var r,a,s=null,l=0;l=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},o=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a},i=this&&this.__spread||function(){for(var e=[],t=0;t0;O--){var N;if(b(N=I[O],e)){P=N;break}}var M,R,F=[];try{for(var B=n(w._children),L=B.next();!L.done;L=B.next())if(v(j=L.value,e)){if(l.Guard.isDocumentTypeNode(j))throw new s.HierarchyRequestError;F.push(j)}}catch(e){o={error:e}}finally{try{L&&!L.done&&(a=B.return)&&a.call(B)}finally{if(o)throw o.error}}if(c.tree_isAncestorOf(C,_,!0))M=_,R=S;else{for(var k=_;null!==k._parent&&!c.tree_isAncestorOf(C,k._parent);)k=k._parent;if(null===k._parent)throw new Error("Parent node is null.");M=k._parent,R=1+c.tree_index(k)}if(l.Guard.isCharacterDataNode(A))(U=f.node_clone(_))._data=p.characterData_substringData(_,S,c.tree_nodeLength(_)-S),h.mutation_append(U,y),p.characterData_replaceData(_,S,c.tree_nodeLength(_)-S,"");else if(null!==A){var U=f.node_clone(A);h.mutation_append(U,y);var V=x(u.create_range([_,S],[A,c.tree_nodeLength(A)]));h.mutation_append(V,U)}try{for(var G=n(F),z=G.next();!z.done;z=G.next()){var j=z.value;h.mutation_append(j,y)}}catch(e){d={error:e}}finally{try{z&&!z.done&&(m=G.return)&&m.call(G)}finally{if(d)throw d.error}}return l.Guard.isCharacterDataNode(P)?((U=f.node_clone(C))._data=p.characterData_substringData(C,0,T),h.mutation_append(U,y),p.characterData_replaceData(C,0,T,"")):null!==P&&(U=f.node_clone(P),h.mutation_append(U,y),V=x(u.create_range([P,0],[C,T])),h.mutation_append(V,U)),e._start=[M,R],e._end=[M,R],y}t.range_collapsed=g,t.range_root=y,t.range_isContained=v,t.range_isPartiallyContained=b,t.range_setTheStart=function(e,t,r){if(l.Guard.isDocumentTypeNode(t))throw new s.InvalidNodeTypeError;if(r>c.tree_nodeLength(t))throw new s.IndexSizeError;var n=[t,r];y(e)===c.tree_rootNode(t)&&d.boundaryPoint_position(n,e._end)!==a.BoundaryPosition.After||(e._end=n),e._start=n},t.range_setTheEnd=function(e,t,r){if(l.Guard.isDocumentTypeNode(t))throw new s.InvalidNodeTypeError;if(r>c.tree_nodeLength(t))throw new s.IndexSizeError;var n=[t,r];y(e)===c.tree_rootNode(t)&&d.boundaryPoint_position(n,e._start)!==a.BoundaryPosition.Before||(e._start=n),e._end=n},t.range_select=function(e,t){var r=e._parent;if(null===r)throw new s.InvalidNodeTypeError;var n=c.tree_index(e);t._start=[r,n],t._end=[r,n+1]},t.range_extract=x,t.range_cloneTheContents=function e(t){var r,o,a,d,m,y,_=u.create_documentFragment(t._startNode._nodeDocument);if(g(t))return _;var S=t._startNode,C=t._startOffset,T=t._endNode,w=t._endOffset;S===T&&l.Guard.isCharacterDataNode(S)&&((L=f.node_clone(S))._data=p.characterData_substringData(S,C,w-C),h.mutation_append(L,_));for(var A=S;!c.tree_isAncestorOf(T,A,!0);){if(null===A._parent)throw new Error("Parent node is null.");A=A._parent}var E=null;if(!c.tree_isAncestorOf(T,S,!0))try{for(var D=n(A._children),P=D.next();!P.done;P=D.next())if(b(M=P.value,t)){E=M;break}}catch(e){r={error:e}}finally{try{P&&!P.done&&(o=D.return)&&o.call(D)}finally{if(r)throw r.error}}var I=null;if(!c.tree_isAncestorOf(S,T,!0))for(var O=i(A._children),N=O.length-1;N>0;N--){var M;if(b(M=O[N],t)){I=M;break}}var R=[];try{for(var F=n(A._children),B=F.next();!B.done;B=F.next())if(v(G=B.value,t)){if(l.Guard.isDocumentTypeNode(G))throw new s.HierarchyRequestError;R.push(G)}}catch(e){a={error:e}}finally{try{B&&!B.done&&(d=F.return)&&d.call(F)}finally{if(a)throw a.error}}if(l.Guard.isCharacterDataNode(E))(L=f.node_clone(S))._data=p.characterData_substringData(S,C,c.tree_nodeLength(S)-C),h.mutation_append(L,_);else if(null!==E){var L=f.node_clone(E);h.mutation_append(L,_);var k=e(u.create_range([S,C],[E,c.tree_nodeLength(E)]));h.mutation_append(k,L)}try{for(var U=n(R),V=U.next();!V.done;V=U.next()){var G=V.value;L=f.node_clone(G),h.mutation_append(L,_)}}catch(e){m={error:e}}finally{try{V&&!V.done&&(y=U.return)&&y.call(U)}finally{if(m)throw m.error}}return l.Guard.isCharacterDataNode(I)?((L=f.node_clone(T))._data=p.characterData_substringData(T,0,w),h.mutation_append(L,_)):null!==I&&(L=f.node_clone(I),_.append(L),k=x(u.create_range([I,0],[T,w])),h.mutation_append(k,L)),_},t.range_insert=function(e,t){var r,o;if(l.Guard.isProcessingInstructionNode(t._startNode)||l.Guard.isCommentNode(t._startNode)||l.Guard.isTextNode(t._startNode)&&null===t._startNode._parent||t._startNode===e)throw new s.HierarchyRequestError;var i,a=null;if(l.Guard.isTextNode(t._startNode))a=t._startNode;else{var u=0;try{for(var d=n(t._startNode._children),p=d.next();!p.done;p=d.next()){var f=p.value;if(u===t._startOffset){a=f;break}u++}}catch(e){r={error:e}}finally{try{p&&!p.done&&(o=d.return)&&o.call(d)}finally{if(r)throw r.error}}}if(null===a)i=t._startNode;else{if(null===a._parent)throw new Error("Parent node is null.");i=a._parent}h.mutation_ensurePreInsertionValidity(e,i,a),l.Guard.isTextNode(t._startNode)&&(a=m.text_split(t._startNode,t._startOffset)),e===a&&(a=e._nextSibling),null!==e._parent&&h.mutation_remove(e,e._parent);var y=null===a?c.tree_nodeLength(i):c.tree_index(a);l.Guard.isDocumentFragmentNode(e)?y+=c.tree_nodeLength(e):y++,h.mutation_preInsert(e,i,a),g(t)&&(t._end=[i,y])},t.range_getContainedNodes=function(e){var t;return(t={})[Symbol.iterator]=function(){var t=e.commonAncestorContainer,r=c.tree_getFirstDescendantNode(t);return{next:function(){for(;r&&!v(r,e);)r=c.tree_getNextDescendantNode(t,r);if(null===r)return{done:!0,value:null};var n={done:!1,value:r};return r=c.tree_getNextDescendantNode(t,r),n}}},t},t.range_getPartiallyContainedNodes=function(e){var t;return(t={})[Symbol.iterator]=function(){var t=e.commonAncestorContainer,r=c.tree_getFirstDescendantNode(t);return{next:function(){for(;r&&!b(r,e);)r=c.tree_getNextDescendantNode(t,r);if(null===r)return{done:!0,value:null};var n={done:!1,value:r};return r=c.tree_getNextDescendantNode(t,r),n}}},t}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(9);t.selectors_scopeMatchASelectorsString=function(e,t){throw new n.NotSupportedError}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(2),o=r(105);t.treeWalker_traverseChildren=function(e,t){for(var r=t?e._current._firstChild:e._current._lastChild;null!==r;){var i=o.traversal_filter(e,r);if(i===n.FilterResult.Accept)return e._current=r,r;if(i===n.FilterResult.Skip){var a=t?r._firstChild:r._lastChild;if(null!==a){r=a;continue}}for(;null!==r;){var s=t?r._nextSibling:r._previousSibling;if(null!==s){r=s;break}var l=r._parent;if(null===l||l===e._root||l===e._current)return null;r=l}}return null},t.treeWalker_traverseSiblings=function(e,t){var r=e._current;if(r===e._root)return null;for(;;){for(var i=t?r._nextSibling:r._previousSibling;null!==i;){r=i;var a=o.traversal_filter(e,r);if(a===n.FilterResult.Accept)return e._current=r,r;i=t?r._firstChild:r._lastChild,a!==n.FilterResult.Reject&&null!==i||(i=t?r._nextSibling:r._previousSibling)}if(null===(r=r._parent)||r===e._root)return null;if(o.traversal_filter(e,r)===n.FilterResult.Accept)return null}}},function(e,t,r){"use strict";r(89),r(74);var n,o=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var i=r(1),a=r(2),s=r(50),l=r(3),u=function(e){function t(t,r){var n=e.call(this,t)||this;return n._indentation={},n._lengthToLastNewline=0,n._writerOptions=i.applyDefaults(r,{wellFormed:!1,headless:!1,prettyPrint:!1,indent:" ",newline:"\n",offset:0,width:0,allowEmptyTags:!1,indentTextOnlyNodes:!1,spaceBeforeSlash:!1}),n}return o(t,e),t.prototype.serialize=function(e){return this._refs={suppressPretty:!1,emptyNode:!1,markup:""},e.nodeType!==a.NodeType.Document||this._writerOptions.headless||this.declaration(this._builderOptions.version,this._builderOptions.encoding,this._builderOptions.standalone),this.serializeNode(e,this._writerOptions.wellFormed),this._writerOptions.prettyPrint&&this._refs.markup.slice(-this._writerOptions.newline.length)===this._writerOptions.newline&&(this._refs.markup=this._refs.markup.slice(0,-this._writerOptions.newline.length)),this._refs.markup},t.prototype.declaration=function(e,t,r){this._beginLine(),this._refs.markup+='",this._endLine()},t.prototype.docType=function(e,t,r){this._beginLine(),this._refs.markup+=t&&r?"':t?"':r?"':"",this._endLine()},t.prototype.openTagBegin=function(e){this._beginLine(),this._refs.markup+="<"+e},t.prototype.openTagEnd=function(e,t,r){if(this._refs.suppressPretty=!1,this._refs.emptyNode=!1,this._writerOptions.prettyPrint&&!t&&!r){for(var n=!0,o=!0,i=this.currentNode.firstChild,a=0,s=0;i;){if(l.Guard.isExclusiveTextNode(i))s++;else{if(!l.Guard.isCDATASectionNode(i)){n=!1,o=!1;break}a++}""!==i.data&&(o=!1),i=i.nextSibling}this._refs.suppressPretty=!this._writerOptions.indentTextOnlyNodes&&n&&(a<=1&&0===s||0===a),this._refs.emptyNode=o}(r||t||this._refs.emptyNode)&&this._writerOptions.allowEmptyTags?this._refs.markup+=">":this._refs.markup+=r?" />":t||this._refs.emptyNode?this._writerOptions.spaceBeforeSlash?" />":"/>":">",this._endLine()},t.prototype.closeTag=function(e){this._refs.emptyNode||(this._beginLine(),this._refs.markup+=""),this._refs.suppressPretty=!1,this._refs.emptyNode=!1,this._endLine()},t.prototype.attribute=function(e,t){var r=e+'="'+t+'"';this._writerOptions.prettyPrint&&this._writerOptions.width>0&&this._refs.markup.length-this._lengthToLastNewline+1+r.length>this._writerOptions.width?(this._endLine(),this._beginLine(),this._refs.markup+=this._indent(1)+r):this._refs.markup+=" "+r},t.prototype.text=function(e){""!==e&&(this._beginLine(),this._refs.markup+=e,this._endLine())},t.prototype.cdata=function(e){""!==e&&(this._beginLine(),this._refs.markup+="",this._endLine())},t.prototype.comment=function(e){this._beginLine(),this._refs.markup+="\x3c!--"+e+"--\x3e",this._endLine()},t.prototype.instruction=function(e,t){this._beginLine(),this._refs.markup+="",this._endLine()},t.prototype._beginLine=function(){this._writerOptions.prettyPrint&&!this._refs.suppressPretty&&(this._refs.markup+=this._indent(this._writerOptions.offset+this.level))},t.prototype._endLine=function(){this._writerOptions.prettyPrint&&!this._refs.suppressPretty&&(this._refs.markup+=this._writerOptions.newline,this._lengthToLastNewline=this._refs.markup.length)},t.prototype._indent=function(e){if(e<=0)return"";if(void 0!==this._indentation[e])return this._indentation[e];var t=this._writerOptions.indent.repeat(e);return this._indentation[e]=t,t},t}(s.BaseWriter);t.XMLWriter=u},function(e,t,r){"use strict";var n=r(47),o=r(35);e.exports="".repeat||function(e){var t=String(o(this)),r="",i=n(e);if(i<0||i==1/0)throw RangeError("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))1&i&&(r+=t);return r}},function(e,t,r){"use strict";r(31),r(32),r(33),r(19),r(178),r(20),r(22),r(23);var n,o=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),i=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var a=r(67),s=r(1),l=function(e){function t(t,r){var n=e.call(this,t)||this;return n._writerOptions=s.applyDefaults(r,{wellFormed:!1,prettyPrint:!1,indent:" ",newline:"\n",offset:0,group:!1,verbose:!1}),n}return o(t,e),t.prototype.serialize=function(e){var t=s.applyDefaults(this._writerOptions,{format:"object",wellFormed:!1}),r=new a.ObjectWriter(this._builderOptions,t).serialize(e);return this._beginLine(this._writerOptions,0)+this._convertObject(r,this._writerOptions)},t.prototype._convertObject=function(e,t,r){var n,o,a=this;void 0===r&&(r=0);var l="",u=this._isLeafNode(e);if(s.isArray(e)){l+="[";var c=e.length,d=0;try{for(var p=i(e),f=p.next();!f.done;f=p.next()){var h=f.value;l+=this._endLine(t,r+1)+this._beginLine(t,r+1)+this._convertObject(h,t,r+1),d0?new Array(r).join(e.indent):""},t.prototype._endLine=function(e,t){return e.prettyPrint?e.newline:""},t.prototype._key=function(e){return'"'+e+'":'},t.prototype._val=function(e){return JSON.stringify(e)},t.prototype._isLeafNode=function(e){return this._descendantCount(e)<=1},t.prototype._descendantCount=function(e,t){var r=this;return void 0===t&&(t=0),s.isArray(e)?s.forEachArray(e,function(e){return t+=r._descendantCount(e,t)},this):s.isObject(e)?s.forEachObject(e,function(e,n){return t+=r._descendantCount(n,t)},this):t++,t},t}(r(50).BaseWriter);t.JSONWriter=l},function(e,t,r){"use strict";r(31),r(32),r(33),r(19),r(178),r(89),r(20),r(22),r(23);var n,o=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),i=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var a=r(67),s=r(1),l=function(e){function t(t,r){var n=e.call(this,t)||this;if(n._writerOptions=s.applyDefaults(r,{wellFormed:!1,indent:" ",newline:"\n",offset:0,group:!1,verbose:!1}),n._writerOptions.indent.length<2)throw new Error("YAML indententation string must be at least two characters long.");if(n._writerOptions.offset<0)throw new Error("YAML offset should be zero or a positive number.");return n}return o(t,e),t.prototype.serialize=function(e){var t=s.applyDefaults(this._writerOptions,{format:"object",wellFormed:!1}),r=new a.ObjectWriter(this._builderOptions,t).serialize(e),n=this._beginLine(this._writerOptions,0)+"---"+this._endLine(this._writerOptions)+this._convertObject(r,this._writerOptions,0);return n.slice(-this._writerOptions.newline.length)===this._writerOptions.newline&&(n=n.slice(0,-this._writerOptions.newline.length)),n},t.prototype._convertObject=function(e,t,r,n){var o,a,l=this;void 0===n&&(n=!1);var u="";if(s.isArray(e))try{for(var c=i(e),d=c.next();!d.done;d=c.next()){var p=d.value;u+=this._beginLine(t,r,!0),s.isObject(p)?s.isEmpty(p)?u+='""'+this._endLine(t):u+=this._convertObject(p,t,r,!0):u+=this._val(p)+this._endLine(t)}}catch(e){o={error:e}}finally{try{d&&!d.done&&(a=c.return)&&a.call(c)}finally{if(o)throw o.error}}else s.forEachObject(e,function(e,o){n?(u+=l._key(e),n=!1):u+=l._beginLine(t,r)+l._key(e),s.isObject(o)?s.isEmpty(o)?u+=' ""'+l._endLine(t):u+=l._endLine(t)+l._convertObject(o,t,r+1):u+=" "+l._val(o)+l._endLine(t)},this);return u},t.prototype._beginLine=function(e,t,r){void 0===r&&(r=!1);var n=e.offset+t+1,o=new Array(n).join(e.indent);return r?o.substr(0,o.length-2)+"-"+o.substr(-1,1):o},t.prototype._endLine=function(e){return e.newline},t.prototype._key=function(e){return'"'+e+'":'},t.prototype._val=function(e){return JSON.stringify(e)},t}(r(50).BaseWriter);t.YAMLWriter=l},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),r(110).dom.setFeatures(!0);var n=r(110);t.DOMImplementation=n.DOMImplementation;var o=r(271);t.DOMParser=o.DOMParser;var i=r(274);t.XMLSerializer=i.XMLSerializer},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(3),o=r(0),i=function(){function e(){}return e.prototype.before=function(){for(var e=[],t=0;t=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var o=r(6),i=r(3),a=r(7),s=function(){function e(e){this._nodeList=[],this._recordQueue=[],this._callback=e;var t=o.dom.window;a.set.append(t._mutationObservers,this)}return e.prototype.observe=function(e,t){var r,o;if(void 0===(t=t||{childList:!1,subtree:!1}).attributeOldValue&&void 0===t.attributeFilter||void 0!==t.attributes||(t.attributes=!0),void 0!==t.characterDataOldValue&&void 0===t.characterData&&(t.characterData=!0),!t.childList&&!t.attributes&&!t.characterData)throw new TypeError;if(t.attributeOldValue&&!t.attributes)throw new TypeError;if(void 0!==t.attributeFilter&&!t.attributes)throw new TypeError;if(t.characterDataOldValue&&!t.characterData)throw new TypeError;var s=!1,l=t,u=function(e){var t,r;if(e.observer===c){s=!0;try{for(var o=(t=void 0,n(c._nodeList)),u=o.next();!u.done;u=o.next()){var d=u.value;a.list.remove(d._registeredObserverList,function(t){return i.Guard.isTransientRegisteredObserver(t)&&t.source===e})}}catch(e){t={error:e}}finally{try{u&&!u.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}e.options=l}},c=this;try{for(var d=n(e._registeredObserverList),p=d.next();!p.done;p=d.next())u(p.value)}catch(e){r={error:e}}finally{try{p&&!p.done&&(o=d.return)&&o.call(d)}finally{if(r)throw r.error}}s||(e._registeredObserverList.push({observer:this,options:t}),this._nodeList.push(e))},e.prototype.disconnect=function(){var e,t,r=this;try{for(var o=n(this._nodeList),i=o.next();!i.done;i=o.next()){var s=i.value;a.list.remove(s._registeredObserverList,function(e){return e.observer===r})}}catch(t){e={error:t}}finally{try{i&&!i.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}this._recordQueue=[]},e.prototype.takeRecords=function(){var e=this._recordQueue;return this._recordQueue=[],e},e}();t.MutationObserverImpl=s},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(3),o=function(){function e(){}return Object.defineProperty(e.prototype,"previousElementSibling",{get:function(){for(var e=n.Cast.asNode(this)._previousSibling;e;){if(n.Guard.isElementNode(e))return e;e=e._previousSibling}return null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nextElementSibling",{get:function(){for(var e=n.Cast.asNode(this)._nextSibling;e;){if(n.Guard.isElementNode(e))return e;e=e._nextSibling}return null},enumerable:!0,configurable:!0}),e}();t.NonDocumentTypeChildNodeImpl=o},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(3),o=r(0),i=function(){function e(){}return e.prototype.getElementById=function(e){for(var t=o.tree_getFirstDescendantNode(n.Cast.asNode(this),!1,!1,function(e){return n.Guard.isElementNode(e)});null!==t;){if(t._uniqueIdentifier===e)return t;t=o.tree_getNextDescendantNode(n.Cast.asNode(this),t,!1,!1,function(e){return n.Guard.isElementNode(e)})}return null},e}();t.NonElementParentNodeImpl=i},function(e,t,r){"use strict";var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var o=r(3),i=r(0),a=function(){function e(){}return Object.defineProperty(e.prototype,"children",{get:function(){return i.create_htmlCollection(o.Cast.asNode(this))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"firstElementChild",{get:function(){for(var e=o.Cast.asNode(this)._firstChild;e;){if(o.Guard.isElementNode(e))return e;e=e._nextSibling}return null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"lastElementChild",{get:function(){for(var e=o.Cast.asNode(this)._lastChild;e;){if(o.Guard.isElementNode(e))return e;e=e._previousSibling}return null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"childElementCount",{get:function(){var e,t,r=0;try{for(var i=n(o.Cast.asNode(this)._children),a=i.next();!a.done;a=i.next()){var s=a.value;o.Guard.isElementNode(s)&&r++}}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}return r},enumerable:!0,configurable:!0}),e.prototype.prepend=function(){for(var e=[],t=0;t0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a},o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var i=r(180),a=r(111),s=r(7),l=r(0),u=r(69),c=function(){function e(){}return e.prototype.parse=function(e){for(var t,r,c,d,p=new i.XMLStringLexer(e,{skipWhitespaceOnlyText:!0}),f=l.create_document(),h=f,m=p.nextToken();m.type!==a.TokenType.EOF;){switch(m.type){case a.TokenType.Declaration:var g=m;if("1.0"!==g.version)throw new Error("Invalid xml version: "+g.version);break;case a.TokenType.DocType:var y=m;if(!l.xml_isPubidChar(y.pubId))throw new Error("DocType public identifier does not match PubidChar construct.");if(!l.xml_isLegalChar(y.sysId)||-1!==y.sysId.indexOf('"')&&-1!==y.sysId.indexOf("'"))throw new Error("DocType system identifier contains invalid characters.");h.appendChild(f.implementation.createDocumentType(y.name,y.pubId,y.sysId));break;case a.TokenType.CDATA:var v=m;if(!l.xml_isLegalChar(v.data)||-1!==v.data.indexOf("]]>"))throw new Error("CDATA contains invalid characters.");h.appendChild(f.createCDATASection(v.data));break;case a.TokenType.Comment:var b=m;if(!l.xml_isLegalChar(b.data)||-1!==b.data.indexOf("--")||b.data.endsWith("-"))throw new Error("Comment data contains invalid characters.");h.appendChild(f.createComment(b.data));break;case a.TokenType.PI:var x=m;if(-1!==x.target.indexOf(":")||/^xml$/i.test(x.target))throw new Error("Processing instruction target contains invalid characters.");if(!l.xml_isLegalChar(x.data)||-1!==x.data.indexOf("?>"))throw new Error("Processing instruction data contains invalid characters.");h.appendChild(f.createProcessingInstruction(x.target,x.data));break;case a.TokenType.Text:var _=m;if(!l.xml_isLegalChar(_.data))throw new Error("Text data contains invalid characters.");h.appendChild(f.createTextNode(this._decodeText(_.data)));break;case a.TokenType.Element:var S=m,C=n(l.namespace_extractQName(S.name),2),T=C[0],w=C[1];if(-1!==w.indexOf(":")||!l.xml_isName(w))throw new Error("Node local name contains invalid characters.");if("xmlns"===T)throw new Error("An element cannot have the 'xmlns' prefix.");var A=h.lookupNamespaceURI(T),E={};try{for(var D=(t=void 0,o(S.attributes)),P=D.next();!P.done;P=D.next()){var I=n(P.value,2),O=I[0],N=I[1];if("xmlns"===O)A=N;else{var M=n(l.namespace_extractQName(O),2),R=M[0],F=M[1];"xmlns"===R&&(F===T&&(A=N),E[F]=N)}}}catch(e){t={error:e}}finally{try{P&&!P.done&&(r=D.return)&&r.call(D)}finally{if(t)throw t.error}}var B=null!==A?f.createElementNS(A,S.name):f.createElement(S.name);h.appendChild(B);var L=new u.LocalNameSet;try{for(var k=(c=void 0,o(S.attributes)),U=k.next();!U.done;U=k.next()){var V=n(U.value,2),G=(O=V[0],N=V[1],n(l.namespace_extractQName(O),2)),z=(R=G[0],F=G[1],null);if("xmlns"===R||null===R&&"xmlns"===F?z=s.namespace.XMLNS:null!==(z=B.lookupNamespaceURI(R))&&B.isDefaultNamespace(z)?z=null:null===z&&null!==R&&(z=E[R]||null),L.has(z,F))throw new Error("Element contains duplicate attributes.");if(L.set(z,F),z===s.namespace.XMLNS&&N===s.namespace.XMLNS)throw new Error("XMLNS namespace is reserved.");if(-1!==F.indexOf(":")||!l.xml_isName(F))throw new Error("Attribute local name contains invalid characters.");if("xmlns"===R&&""===N)throw new Error("Empty XML namespace is not allowed.");null!==z?B.setAttributeNS(z,O,this._decodeAttributeValue(N)):B.setAttribute(O,this._decodeAttributeValue(N))}}catch(e){c={error:e}}finally{try{U&&!U.done&&(d=k.return)&&d.call(k)}finally{if(c)throw c.error}}S.selfClosing||(h=B);break;case a.TokenType.ClosingTag:if(m.name!==h.nodeName)throw new Error("Closing tag name does not match opening tag name.");h._parent&&(h=h._parent)}m=p.nextToken()}return f},e.prototype._decodeText=function(e){return null==e?e:e.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")},e.prototype._decodeAttributeValue=function(e){return null==e?e:e.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")},e}();t.XMLParserImpl=c},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(275);t.XMLSerializer=n.XMLSerializerImpl},function(e,t,r){"use strict";var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var o=r(2),i=r(69),a=r(95),s=r(9),l=r(7),u=r(0),c=function(){function e(){}return e.prototype.serializeToString=function(e){return this._xmlSerialization(e,!1)},e.prototype._xmlSerialization=function(e,t){if(void 0===e._nodeDocument||e._nodeDocument._hasNamespaces){var r=new a.NamespacePrefixMap;r.set("xml",l.namespace.XML);try{return this._serializeNodeNS(e,null,r,{value:1},t)}catch(e){throw new s.InvalidStateError}}else try{return this._serializeNode(e,t)}catch(e){throw new s.InvalidStateError}},e.prototype._serializeNodeNS=function(e,t,r,n,i){switch(e.nodeType){case o.NodeType.Element:return this._serializeElementNS(e,t,r,n,i);case o.NodeType.Document:return this._serializeDocumentNS(e,t,r,n,i);case o.NodeType.Comment:return this._serializeComment(e,i);case o.NodeType.Text:return this._serializeText(e,i);case o.NodeType.DocumentFragment:return this._serializeDocumentFragmentNS(e,t,r,n,i);case o.NodeType.DocumentType:return this._serializeDocumentType(e,i);case o.NodeType.ProcessingInstruction:return this._serializeProcessingInstruction(e,i);case o.NodeType.CData:return this._serializeCData(e,i);default:throw new Error("Unknown node type: "+e.nodeType)}},e.prototype._serializeNode=function(e,t){switch(e.nodeType){case o.NodeType.Element:return this._serializeElement(e,t);case o.NodeType.Document:return this._serializeDocument(e,t);case o.NodeType.Comment:return this._serializeComment(e,t);case o.NodeType.Text:return this._serializeText(e,t);case o.NodeType.DocumentFragment:return this._serializeDocumentFragment(e,t);case o.NodeType.DocumentType:return this._serializeDocumentType(e,t);case o.NodeType.ProcessingInstruction:return this._serializeProcessingInstruction(e,t);case o.NodeType.CData:return this._serializeCData(e,t);default:throw new Error("Unknown node type: "+e.nodeType)}},e.prototype._serializeElementNS=function(t,r,o,i,a){var s,c;if(a&&(-1!==t.localName.indexOf(":")||!u.xml_isName(t.localName)))throw new Error("Node local name contains invalid characters (well-formed required).");var d="<",p="",f=!1,h=!1,m=o.copy(),g={},y=this._recordNamespaceInformation(t,m,g),v=r,b=t.namespaceURI;if(v===b)null!==y&&(h=!0),d+=p=b===l.namespace.XML?"xml:"+t.localName:t.localName;else{var x=t.prefix,_=null;if(null===x&&b===y||(_=m.get(x,b)),"xmlns"===x){if(a)throw new Error("An element cannot have the 'xmlns' prefix (well-formed required).");_=x}null!==_?(p=_+":"+t.localName,null!==y&&y!==l.namespace.XML&&(v=y||null),d+=p):null!==x?(x in g&&(x=this._generatePrefix(b,m,i)),m.set(x,b),d+=p+=x+":"+t.localName,d+=" xmlns:"+x+'="'+this._serializeAttributeValue(b,a)+'"',null!==y&&(v=y||null)):null===y||null!==y&&y!==b?(h=!0,v=b,d+=p+=t.localName,d+=' xmlns="'+this._serializeAttributeValue(b,a)+'"'):(v=b,d+=p+=t.localName)}d+=this._serializeAttributesNS(t,m,i,g,h,a);var S=b===l.namespace.HTML;if(S&&0===t.childNodes.length&&e._VoidElementNames.has(t.localName)?(d+=" /",f=!0):S||0!==t.childNodes.length||(d+="/",f=!0),d+=">",f)return d;if(S&&"template"===t.localName);else try{for(var C=n(t._children||t.childNodes),T=C.next();!T.done;T=C.next()){var w=T.value;d+=this._serializeNodeNS(w,v,m,i,a)}}catch(e){s={error:e}}finally{try{T&&!T.done&&(c=C.return)&&c.call(C)}finally{if(s)throw s.error}}return d+""},e.prototype._serializeDocumentNS=function(e,t,r,o,i){var a,s;if(i&&null===e.documentElement)throw new Error("Missing document element (well-formed required).");var l="";try{for(var u=n(e._children||e.childNodes),c=u.next();!c.done;c=u.next()){var d=c.value;l+=this._serializeNodeNS(d,t,r,o,i)}}catch(e){a={error:e}}finally{try{c&&!c.done&&(s=u.return)&&s.call(u)}finally{if(a)throw a.error}}return l},e.prototype._serializeComment=function(e,t){if(t&&(!u.xml_isLegalChar(e.data)||-1!==e.data.indexOf("--")||e.data.endsWith("-")))throw new Error("Comment data contains invalid characters (well-formed required).");return"\x3c!--"+e.data+"--\x3e"},e.prototype._serializeText=function(e,t){if(t&&!u.xml_isLegalChar(e.data))throw new Error("Text data contains invalid characters (well-formed required).");for(var r="",n=0;n"===o?">":o}return r},e.prototype._serializeDocumentFragmentNS=function(e,t,r,o,i){var a,s,l="";try{for(var u=n(e._children||e.childNodes),c=u.next();!c.done;c=u.next()){var d=c.value;l+=this._serializeNodeNS(d,t,r,o,i)}}catch(e){a={error:e}}finally{try{c&&!c.done&&(s=u.return)&&s.call(u)}finally{if(a)throw a.error}}return l},e.prototype._serializeDocumentType=function(e,t){if(t&&!u.xml_isPubidChar(e.publicId))throw new Error("DocType public identifier does not match PubidChar construct (well-formed required).");if(t&&(!u.xml_isLegalChar(e.systemId)||-1!==e.systemId.indexOf('"')&&-1!==e.systemId.indexOf("'")))throw new Error("DocType system identifier contains invalid characters (well-formed required).");return e.publicId&&e.systemId?"':e.publicId?"':e.systemId?"':""},e.prototype._serializeProcessingInstruction=function(e,t){if(t&&(-1!==e.target.indexOf(":")||/^xml$/i.test(e.target)))throw new Error("Processing instruction target contains invalid characters (well-formed required).");if(t&&(!u.xml_isLegalChar(e.data)||-1!==e.data.indexOf("?>")))throw new Error("Processing instruction data contains invalid characters (well-formed required).");return""},e.prototype._serializeCData=function(e,t){if(t&&-1!==e.data.indexOf("]]>"))throw new Error("CDATA contains invalid characters (well-formed required).");return""},e.prototype._serializeAttributesNS=function(e,t,r,o,a,s){var c,d,p="",f=s?new i.LocalNameSet:void 0;try{for(var h=n(e.attributes),m=h.next();!m.done;m=h.next()){var g=m.value;if(a||s||null!==g.namespaceURI){if(s&&f&&f.has(g.namespaceURI,g.localName))throw new Error("Element contains duplicate attributes (well-formed required).");s&&f&&f.set(g.namespaceURI,g.localName);var y=g.namespaceURI,v=null;if(null!==y)if(v=t.get(g.prefix,y),y===l.namespace.XMLNS){if(g.value===l.namespace.XML||null===g.prefix&&a||null!==g.prefix&&(!(g.localName in o)||o[g.localName]!==g.value)&&t.has(g.localName,g.value))continue;if(s&&g.value===l.namespace.XMLNS)throw new Error("XMLNS namespace is reserved (well-formed required).");if(s&&""===g.value)throw new Error("Namespace prefix declarations cannot be used to undeclare a namespace (well-formed required).");"xmlns"===g.prefix&&(v="xmlns")}else null===v&&(p+=" xmlns:"+(v=null===g.prefix||t.hasPrefix(g.prefix)&&!t.has(g.prefix,y)?this._generatePrefix(y,t,r):g.prefix)+'="'+this._serializeAttributeValue(y,s)+'"');if(p+=" ",null!==v&&(p+=v+":"),s&&(-1!==g.localName.indexOf(":")||!u.xml_isName(g.localName)||"xmlns"===g.localName&&null===y))throw new Error("Attribute local name contains invalid characters (well-formed required).");p+=g.localName+'="'+this._serializeAttributeValue(g.value,s)+'"'}else p+=" "+g.localName+'="'+this._serializeAttributeValue(g.value,s)+'"'}}catch(e){c={error:e}}finally{try{m&&!m.done&&(d=h.return)&&d.call(h)}finally{if(c)throw c.error}}return p},e.prototype._recordNamespaceInformation=function(e,t,r){var o,i,a=null;try{for(var s=n(e.attributes),u=s.next();!u.done;u=s.next()){var c=u.value,d=c.namespaceURI,p=c.prefix;if(d===l.namespace.XMLNS){if(null===p){a=c.value;continue}var f=c.localName,h=c.value;if(h===l.namespace.XML)continue;if(""===h&&(h=null),t.has(f,h))continue;t.set(f,h),r[f]=h||""}}}catch(e){o={error:e}}finally{try{u&&!u.done&&(i=s.return)&&i.call(s)}finally{if(o)throw o.error}}return a},e.prototype._generatePrefix=function(e,t,r){var n="ns"+r.value;return r.value++,t.set(n,e),n},e.prototype._serializeAttributeValue=function(e,t){if(t&&null!==e&&!u.xml_isLegalChar(e))throw new Error("Invalid characters in attribute value.");if(null===e)return"";for(var r="",n=0;n"===o?">":o}return r},e.prototype._serializeElement=function(e,t){var r,o;if(t&&(-1!==e.localName.indexOf(":")||!u.xml_isName(e.localName)))throw new Error("Node local name contains invalid characters (well-formed required).");var i=!1,a=e.localName,s="<"+a;if(s+=this._serializeAttributes(e,t),0===e._children.size&&(s+="/",i=!0),s+=">",i)return s;try{for(var l=n(e._children),c=l.next();!c.done;c=l.next()){var d=c.value;s+=this._serializeNode(d,t)}}catch(e){r={error:e}}finally{try{c&&!c.done&&(o=l.return)&&o.call(l)}finally{if(r)throw r.error}}return s+""},e.prototype._serializeDocument=function(e,t){var r,o;if(t&&null===e.documentElement)throw new Error("Missing document element (well-formed required).");var i="";try{for(var a=n(e._children),s=a.next();!s.done;s=a.next()){var l=s.value;i+=this._serializeNode(l,t)}}catch(e){r={error:e}}finally{try{s&&!s.done&&(o=a.return)&&o.call(a)}finally{if(r)throw r.error}}return i},e.prototype._serializeDocumentFragment=function(e,t){var r,o,i="";try{for(var a=n(e._children),s=a.next();!s.done;s=a.next()){var l=s.value;i+=this._serializeNode(l,t)}}catch(e){r={error:e}}finally{try{s&&!s.done&&(o=a.return)&&o.call(a)}finally{if(r)throw r.error}}return i},e.prototype._serializeAttributes=function(e,t){var r,o,i="",a=t?{}:void 0;try{for(var s=n(e.attributes),l=s.next();!l.done;l=s.next()){var c=l.value;if(t&&a&&c.localName in a)throw new Error("Element contains duplicate attributes (well-formed required).");if(t&&a&&(a[c.localName]=!0),t&&(-1!==c.localName.indexOf(":")||!u.xml_isName(c.localName)))throw new Error("Attribute local name contains invalid characters (well-formed required).");i+=" "+c.localName+'="'+this._serializeAttributeValue(c.value,t)+'"'}}catch(e){r={error:e}}finally{try{l&&!l.done&&(o=s.return)&&o.call(s)}finally{if(r)throw r.error}}return i},e._VoidElementNames=new Set(["area","base","basefont","bgsound","br","col","embed","frame","hr","img","input","keygen","link","menuitem","meta","param","source","track","wbr"]),e}();t.XMLSerializerImpl=c},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(277);t.XMLReader=n.XMLReader;var o=r(112);t.ObjectReader=o.ObjectReader;var i=r(280);t.JSONReader=i.JSONReader;var a=r(281);t.YAMLReader=a.YAMLReader},function(e,t,r){"use strict";r(31),r(32),r(33),r(19),r(65),r(20),r(22),r(23);var n,o=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),i=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a},a=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0});var s=r(180),l=r(111),u=r(7),c=r(0),d=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype._parse=function(e,t){for(var r,n,o,d,p=new s.XMLStringLexer(t,{skipWhitespaceOnlyText:!0}),f=e,h=e,m=p.nextToken();m.type!==l.TokenType.EOF;){switch(m.type){case l.TokenType.Declaration:var g=m,y=this.sanitize(g.version);if("1.0"!==y)throw new Error("Invalid xml version: "+y);var v={version:y};g.encoding&&(v.encoding=this.sanitize(g.encoding)),g.standalone&&(v.standalone="yes"===this.sanitize(g.standalone)),h.set(v);break;case l.TokenType.DocType:var b=m;h=this.docType(h,this.sanitize(b.name),this.sanitize(b.pubId),this.sanitize(b.sysId))||h;break;case l.TokenType.CDATA:var x=m;h=this.cdata(h,this.sanitize(x.data))||h;break;case l.TokenType.Comment:var _=m;h=this.comment(h,this.sanitize(_.data))||h;break;case l.TokenType.PI:var S=m;h=this.instruction(h,this.sanitize(S.target),this.sanitize(S.data))||h;break;case l.TokenType.Text:var C=m;h=this.text(h,this._decodeText(this.sanitize(C.data)))||h;break;case l.TokenType.Element:var T=m,w=this.sanitize(T.name),A=i(c.namespace_extractQName(w),1)[0],E=h.node.lookupNamespaceURI(A),D={};try{for(var P=(r=void 0,a(T.attributes)),I=P.next();!I.done;I=P.next()){var O=i(I.value,2),N=O[0],M=O[1];if(N=this.sanitize(N),M=this.sanitize(M),"xmlns"===N)E=M;else{var R=i(c.namespace_extractQName(N),2),F=R[0],B=R[1];"xmlns"===F&&(B===A&&(E=M),D[B]=M)}}}catch(e){r={error:e}}finally{try{I&&!I.done&&(n=P.return)&&n.call(P)}finally{if(r)throw r.error}}var L=null!==E?this.element(h,E,w):this.element(h,void 0,w);if(void 0===L)break;h.node===e.node&&(f=L);try{for(var k=(o=void 0,a(T.attributes)),U=k.next();!U.done;U=k.next()){var V=i(U.value,2);N=V[0],M=V[1],N=this.sanitize(N),M=this.sanitize(M);var G=i(c.namespace_extractQName(N),2),z=(F=G[0],B=G[1],null);"xmlns"===F||null===F&&"xmlns"===B?z=u.namespace.XMLNS:null!==(z=L.node.lookupNamespaceURI(F))&&L.node.isDefaultNamespace(z)?z=null:null===z&&null!==F&&(z=D[F]||null),null!==z?this.attribute(L,z,N,this._decodeAttributeValue(M)):this.attribute(L,void 0,N,this._decodeAttributeValue(M))}}catch(e){o={error:e}}finally{try{U&&!U.done&&(d=k.return)&&d.call(k)}finally{if(o)throw o.error}}T.selfClosing||(h=L);break;case l.TokenType.ClosingTag:h.node.parentNode&&(h=h.up())}m=p.nextToken()}return f},t}(r(75).BaseReader);t.XMLReader=d},function(e,t,r){var n=r(4),o=r(279);n({target:"Object",stat:!0,forced:Object.assign!==o},{assign:o})},function(e,t,r){"use strict";var n=r(16),o=r(8),i=r(61),a=r(85),s=r(79),l=r(27),u=r(41),c=Object.assign,d=Object.defineProperty;e.exports=!c||o(function(){if(n&&1!==c({b:1},c(d({},"a",{enumerable:!0,get:function(){d(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},r=Symbol();return e[r]=7,"abcdefghijklmnopqrst".split("").forEach(function(e){t[e]=e}),7!=c({},e)[r]||"abcdefghijklmnopqrst"!=i(c({},t)).join("")})?function(e,t){for(var r=l(e),o=arguments.length,c=1,d=a.f,p=s.f;o>c;)for(var f,h=u(arguments[c++]),m=d?i(h).concat(d(h)):i(h),g=m.length,y=0;g>y;)f=m[y++],n&&!p.call(h,f)||(r[f]=h[f]);return r}:c},function(e,t,r){"use strict";var n,o=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var i=r(112),a=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype._parse=function(e,t){return new i.ObjectReader(this._builderOptions).parse(e,JSON.parse(t))},t}(r(75).BaseReader);t.JSONReader=a},function(e,t,r){"use strict";var n,o=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var i=r(112),a=r(75),s=r(282),l=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),t.prototype._parse=function(e,t){var r=s.safeLoad(t);if(void 0===r)throw new Error("Unable to parse YAML document.");return new i.ObjectReader(this._builderOptions).parse(e,r)},t}(a.BaseReader);t.YAMLReader=l},function(e,t,r){"use strict";var n=r(283);e.exports=n},function(e,t,r){"use strict";var n=r(284),o=r(303);function i(e){return function(){throw new Error("Function "+e+" is deprecated and cannot be used.")}}e.exports.Type=r(10),e.exports.Schema=r(39),e.exports.FAILSAFE_SCHEMA=r(113),e.exports.JSON_SCHEMA=r(182),e.exports.CORE_SCHEMA=r(181),e.exports.DEFAULT_SAFE_SCHEMA=r(54),e.exports.DEFAULT_FULL_SCHEMA=r(76),e.exports.load=n.load,e.exports.loadAll=n.loadAll,e.exports.safeLoad=n.safeLoad,e.exports.safeLoadAll=n.safeLoadAll,e.exports.dump=o.dump,e.exports.safeDump=o.safeDump,e.exports.YAMLException=r(53),e.exports.MINIMAL_SCHEMA=r(113),e.exports.SAFE_SCHEMA=r(54),e.exports.DEFAULT_SCHEMA=r(76),e.exports.scan=i("scan"),e.exports.parse=i("parse"),e.exports.compose=i("compose"),e.exports.addConstructor=i("addConstructor")},function(e,t,r){"use strict";var n=r(38),o=r(53),i=r(285),a=r(54),s=r(76),l=Object.prototype.hasOwnProperty,u=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,c=/[\x85\u2028\u2029]/,d=/[,\[\]\{\}]/,p=/^(?:!|!!|![a-z\-]+!)$/i,f=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;function h(e){return Object.prototype.toString.call(e)}function m(e){return 10===e||13===e}function g(e){return 9===e||32===e}function y(e){return 9===e||32===e||10===e||13===e}function v(e){return 44===e||91===e||93===e||123===e||125===e}function b(e){var t;return 48<=e&&e<=57?e-48:97<=(t=32|e)&&t<=102?t-97+10:-1}function x(e){return 48===e?"\0":97===e?"":98===e?"\b":116===e||9===e?"\t":110===e?"\n":118===e?"\v":102===e?"\f":114===e?"\r":101===e?"":32===e?" ":34===e?'"':47===e?"/":92===e?"\\":78===e?"…":95===e?" ":76===e?"\u2028":80===e?"\u2029":""}function _(e){return e<=65535?String.fromCharCode(e):String.fromCharCode(55296+(e-65536>>10),56320+(e-65536&1023))}for(var S=new Array(256),C=new Array(256),T=0;T<256;T++)S[T]=x(T)?1:0,C[T]=x(T);function w(e,t){this.input=e,this.filename=t.filename||null,this.schema=t.schema||s,this.onWarning=t.onWarning||null,this.legacy=t.legacy||!1,this.json=t.json||!1,this.listener=t.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=e.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.documents=[]}function A(e,t){return new o(t,new i(e.filename,e.input,e.position,e.line,e.position-e.lineStart))}function E(e,t){throw A(e,t)}function D(e,t){e.onWarning&&e.onWarning.call(null,A(e,t))}var P={YAML:function(e,t,r){var n,o,i;null!==e.version&&E(e,"duplication of %YAML directive"),1!==r.length&&E(e,"YAML directive accepts exactly one argument"),null===(n=/^([0-9]+)\.([0-9]+)$/.exec(r[0]))&&E(e,"ill-formed argument of the YAML directive"),o=parseInt(n[1],10),i=parseInt(n[2],10),1!==o&&E(e,"unacceptable YAML version of the document"),e.version=r[0],e.checkLineBreaks=i<2,1!==i&&2!==i&&D(e,"unsupported YAML version of the document")},TAG:function(e,t,r){var n,o;2!==r.length&&E(e,"TAG directive accepts exactly two arguments"),n=r[0],o=r[1],p.test(n)||E(e,"ill-formed tag handle (first argument) of the TAG directive"),l.call(e.tagMap,n)&&E(e,'there is a previously declared suffix for "'+n+'" tag handle'),f.test(o)||E(e,"ill-formed tag prefix (second argument) of the TAG directive"),e.tagMap[n]=o}};function I(e,t,r,n){var o,i,a,s;if(t1&&(e.result+=n.repeat("\n",t-1))}function L(e,t){var r,n,o=e.tag,i=e.anchor,a=[],s=!1;for(null!==e.anchor&&(e.anchorMap[e.anchor]=a),n=e.input.charCodeAt(e.position);0!==n&&45===n&&y(e.input.charCodeAt(e.position+1));)if(s=!0,e.position++,R(e,!0,-1)&&e.lineIndent<=t)a.push(null),n=e.input.charCodeAt(e.position);else if(r=e.line,V(e,t,3,!1,!0),a.push(e.result),R(e,!0,-1),n=e.input.charCodeAt(e.position),(e.line===r||e.lineIndent>t)&&0!==n)E(e,"bad indentation of a sequence entry");else if(e.lineIndentt?x=1:e.lineIndent===t?x=0:e.lineIndentt?x=1:e.lineIndent===t?x=0:e.lineIndentt)&&(V(e,t,4,!0,o)&&(m?f=e.result:h=e.result),m||(N(e,c,d,p,f,h,i,a),p=f=h=null),R(e,!0,-1),s=e.input.charCodeAt(e.position)),e.lineIndent>t&&0!==s)E(e,"bad indentation of a mapping entry");else if(e.lineIndent=0))break;0===i?E(e,"bad explicit indentation width of a block scalar; it cannot be less than one"):c?E(e,"repeat of an indentation width identifier"):(d=t+i-1,c=!0)}if(g(a)){do{a=e.input.charCodeAt(++e.position)}while(g(a));if(35===a)do{a=e.input.charCodeAt(++e.position)}while(!m(a)&&0!==a)}for(;0!==a;){for(M(e),e.lineIndent=0,a=e.input.charCodeAt(e.position);(!c||e.lineIndentd&&(d=e.lineIndent),m(a))p++;else{if(e.lineIndent0){for(o=a,i=0;o>0;o--)(a=b(s=e.input.charCodeAt(++e.position)))>=0?i=(i<<4)+a:E(e,"expected hexadecimal character");e.result+=_(i),e.position++}else E(e,"unknown escape sequence");r=n=e.position}else m(s)?(I(e,r,n,!0),B(e,R(e,!1,t)),r=n=e.position):e.position===e.lineStart&&F(e)?E(e,"unexpected end of the document within a double quoted scalar"):(e.position++,n=e.position)}E(e,"unexpected end of the stream within a double quoted scalar")}(e,f)?w=!0:function(e){var t,r,n;if(42!==(n=e.input.charCodeAt(e.position)))return!1;for(n=e.input.charCodeAt(++e.position),t=e.position;0!==n&&!y(n)&&!v(n);)n=e.input.charCodeAt(++e.position);return e.position===t&&E(e,"name of an alias node must contain at least one character"),r=e.input.slice(t,e.position),e.anchorMap.hasOwnProperty(r)||E(e,'unidentified alias "'+r+'"'),e.result=e.anchorMap[r],R(e,!0,-1),!0}(e)?(w=!0,null===e.tag&&null===e.anchor||E(e,"alias node should not have any properties")):function(e,t,r){var n,o,i,a,s,l,u,c,d=e.kind,p=e.result;if(y(c=e.input.charCodeAt(e.position))||v(c)||35===c||38===c||42===c||33===c||124===c||62===c||39===c||34===c||37===c||64===c||96===c)return!1;if((63===c||45===c)&&(y(n=e.input.charCodeAt(e.position+1))||r&&v(n)))return!1;for(e.kind="scalar",e.result="",o=i=e.position,a=!1;0!==c;){if(58===c){if(y(n=e.input.charCodeAt(e.position+1))||r&&v(n))break}else if(35===c){if(y(e.input.charCodeAt(e.position-1)))break}else{if(e.position===e.lineStart&&F(e)||r&&v(c))break;if(m(c)){if(s=e.line,l=e.lineStart,u=e.lineIndent,R(e,!1,-1),e.lineIndent>=t){a=!0,c=e.input.charCodeAt(e.position);continue}e.position=i,e.line=s,e.lineStart=l,e.lineIndent=u;break}}a&&(I(e,o,i,!1),B(e,e.line-s),o=i=e.position,a=!1),g(c)||(i=e.position+1),c=e.input.charCodeAt(++e.position)}return I(e,o,i,!1),!!e.result||(e.kind=d,e.result=p,!1)}(e,f,1===r)&&(w=!0,null===e.tag&&(e.tag="?")),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):0===x&&(w=u&&L(e,h))),null!==e.tag&&"!"!==e.tag)if("?"===e.tag){for(null!==e.result&&"scalar"!==e.kind&&E(e,'unacceptable node kind for ! tag; it should be "scalar", not "'+e.kind+'"'),c=0,d=e.implicitTypes.length;c tag; it should be "'+p.kind+'", not "'+e.kind+'"'),p.resolve(e.result)?(e.result=p.construct(e.result),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):E(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")):E(e,"unknown tag !<"+e.tag+">");return null!==e.listener&&e.listener("close",e),null!==e.tag||null!==e.anchor||w}function G(e){var t,r,n,o,i=e.position,a=!1;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap={},e.anchorMap={};0!==(o=e.input.charCodeAt(e.position))&&(R(e,!0,-1),o=e.input.charCodeAt(e.position),!(e.lineIndent>0||37!==o));){for(a=!0,o=e.input.charCodeAt(++e.position),t=e.position;0!==o&&!y(o);)o=e.input.charCodeAt(++e.position);for(n=[],(r=e.input.slice(t,e.position)).length<1&&E(e,"directive name must not be less than one character in length");0!==o;){for(;g(o);)o=e.input.charCodeAt(++e.position);if(35===o){do{o=e.input.charCodeAt(++e.position)}while(0!==o&&!m(o));break}if(m(o))break;for(t=e.position;0!==o&&!y(o);)o=e.input.charCodeAt(++e.position);n.push(e.input.slice(t,e.position))}0!==o&&M(e),l.call(P,r)?P[r](e,r,n):D(e,'unknown document directive "'+r+'"')}R(e,!0,-1),0===e.lineIndent&&45===e.input.charCodeAt(e.position)&&45===e.input.charCodeAt(e.position+1)&&45===e.input.charCodeAt(e.position+2)?(e.position+=3,R(e,!0,-1)):a&&E(e,"directives end mark is expected"),V(e,e.lineIndent-1,4,!1,!0),R(e,!0,-1),e.checkLineBreaks&&c.test(e.input.slice(i,e.position))&&D(e,"non-ASCII line breaks are interpreted as content"),e.documents.push(e.result),e.position===e.lineStart&&F(e)?46===e.input.charCodeAt(e.position)&&(e.position+=3,R(e,!0,-1)):e.position0&&-1==="\0\r\n…\u2028\u2029".indexOf(this.buffer.charAt(o-1));)if(o-=1,this.position-o>t/2-1){r=" ... ",o+=5;break}for(i="",a=this.position;at/2-1){i=" ... ",a-=5;break}return s=this.buffer.slice(o,a),n.repeat(" ",e)+r+s+i+"\n"+n.repeat(" ",e+this.position-o+r.length)+"^"},o.prototype.toString=function(e){var t,r="";return this.name&&(r+='in "'+this.name+'" '),r+="at line "+(this.line+1)+", column "+(this.column+1),e||(t=this.getSnippet())&&(r+=":\n"+t),r},e.exports=o},function(e,t,r){"use strict";var n=r(10);e.exports=new n("tag:yaml.org,2002:str",{kind:"scalar",construct:function(e){return null!==e?e:""}})},function(e,t,r){"use strict";var n=r(10);e.exports=new n("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(e){return null!==e?e:[]}})},function(e,t,r){"use strict";var n=r(10);e.exports=new n("tag:yaml.org,2002:map",{kind:"mapping",construct:function(e){return null!==e?e:{}}})},function(e,t,r){"use strict";var n=r(10);e.exports=new n("tag:yaml.org,2002:null",{kind:"scalar",resolve:function(e){if(null===e)return!0;var t=e.length;return 1===t&&"~"===e||4===t&&("null"===e||"Null"===e||"NULL"===e)},construct:function(){return null},predicate:function(e){return null===e},represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"}},defaultStyle:"lowercase"})},function(e,t,r){"use strict";var n=r(10);e.exports=new n("tag:yaml.org,2002:bool",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t=e.length;return 4===t&&("true"===e||"True"===e||"TRUE"===e)||5===t&&("false"===e||"False"===e||"FALSE"===e)},construct:function(e){return"true"===e||"True"===e||"TRUE"===e},predicate:function(e){return"[object Boolean]"===Object.prototype.toString.call(e)},represent:{lowercase:function(e){return e?"true":"false"},uppercase:function(e){return e?"TRUE":"FALSE"},camelcase:function(e){return e?"True":"False"}},defaultStyle:"lowercase"})},function(e,t,r){"use strict";var n=r(38),o=r(10);function i(e){return 48<=e&&e<=55}function a(e){return 48<=e&&e<=57}e.exports=new o("tag:yaml.org,2002:int",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t,r,n=e.length,o=0,s=!1;if(!n)return!1;if("-"!==(t=e[o])&&"+"!==t||(t=e[++o]),"0"===t){if(o+1===n)return!0;if("b"===(t=e[++o])){for(o++;o=0?"0b"+e.toString(2):"-0b"+e.toString(2).slice(1)},octal:function(e){return e>=0?"0"+e.toString(8):"-0"+e.toString(8).slice(1)},decimal:function(e){return e.toString(10)},hexadecimal:function(e){return e>=0?"0x"+e.toString(16).toUpperCase():"-0x"+e.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}})},function(e,t,r){"use strict";var n=r(38),o=r(10),i=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),a=/^[-+]?[0-9]+e/;e.exports=new o("tag:yaml.org,2002:float",{kind:"scalar",resolve:function(e){return null!==e&&!(!i.test(e)||"_"===e[e.length-1])},construct:function(e){var t,r,n,o;return r="-"===(t=e.replace(/_/g,"").toLowerCase())[0]?-1:1,o=[],"+-".indexOf(t[0])>=0&&(t=t.slice(1)),".inf"===t?1===r?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:".nan"===t?NaN:t.indexOf(":")>=0?(t.split(":").forEach(function(e){o.unshift(parseFloat(e,10))}),t=0,n=1,o.forEach(function(e){t+=e*n,n*=60}),r*t):r*parseFloat(t,10)},predicate:function(e){return"[object Number]"===Object.prototype.toString.call(e)&&(e%1!=0||n.isNegativeZero(e))},represent:function(e,t){var r;if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(n.isNegativeZero(e))return"-0.0";return r=e.toString(10),a.test(r)?r.replace("e",".e"):r},defaultStyle:"lowercase"})},function(e,t,r){"use strict";var n=r(10),o=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),i=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");e.exports=new n("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:function(e){return null!==e&&(null!==o.exec(e)||null!==i.exec(e))},construct:function(e){var t,r,n,a,s,l,u,c,d=0,p=null;if(null===(t=o.exec(e))&&(t=i.exec(e)),null===t)throw new Error("Date resolve error");if(r=+t[1],n=+t[2]-1,a=+t[3],!t[4])return new Date(Date.UTC(r,n,a));if(s=+t[4],l=+t[5],u=+t[6],t[7]){for(d=t[7].slice(0,3);d.length<3;)d+="0";d=+d}return t[9]&&(p=6e4*(60*+t[10]+ +(t[11]||0)),"-"===t[9]&&(p=-p)),c=new Date(Date.UTC(r,n,a,s,l,u,d)),p&&c.setTime(c.getTime()-p),c},instanceOf:Date,represent:function(e){return e.toISOString()}})},function(e,t,r){"use strict";var n=r(10);e.exports=new n("tag:yaml.org,2002:merge",{kind:"scalar",resolve:function(e){return"<<"===e||null===e}})},function(e,t,r){"use strict";var n;try{n=r(145).Buffer}catch(e){}var o=r(10),i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";e.exports=new o("tag:yaml.org,2002:binary",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t,r,n=0,o=e.length,a=i;for(r=0;r64)){if(t<0)return!1;n+=6}return n%8==0},construct:function(e){var t,r,o=e.replace(/[\r\n=]/g,""),a=o.length,s=i,l=0,u=[];for(t=0;t>16&255),u.push(l>>8&255),u.push(255&l)),l=l<<6|s.indexOf(o.charAt(t));return 0==(r=a%4*6)?(u.push(l>>16&255),u.push(l>>8&255),u.push(255&l)):18===r?(u.push(l>>10&255),u.push(l>>2&255)):12===r&&u.push(l>>4&255),n?n.from?n.from(u):new n(u):u},predicate:function(e){return n&&n.isBuffer(e)},represent:function(e){var t,r,n="",o=0,a=e.length,s=i;for(t=0;t>18&63],n+=s[o>>12&63],n+=s[o>>6&63],n+=s[63&o]),o=(o<<8)+e[t];return 0==(r=a%3)?(n+=s[o>>18&63],n+=s[o>>12&63],n+=s[o>>6&63],n+=s[63&o]):2===r?(n+=s[o>>10&63],n+=s[o>>4&63],n+=s[o<<2&63],n+=s[64]):1===r&&(n+=s[o>>2&63],n+=s[o<<4&63],n+=s[64],n+=s[64]),n}})},function(e,t,r){"use strict";var n=r(10),o=Object.prototype.hasOwnProperty,i=Object.prototype.toString;e.exports=new n("tag:yaml.org,2002:omap",{kind:"sequence",resolve:function(e){if(null===e)return!0;var t,r,n,a,s,l=[],u=e;for(t=0,r=u.length;t3)return!1;if("/"!==t[t.length-n.length-1])return!1}return!0},construct:function(e){var t=e,r=/\/([gim]*)$/.exec(e),n="";return"/"===t[0]&&(r&&(n=r[1]),t=t.slice(1,t.length-n.length-1)),new RegExp(t,n)},predicate:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},represent:function(e){var t="/"+e.source+"/";return e.global&&(t+="g"),e.multiline&&(t+="m"),e.ignoreCase&&(t+="i"),t}})},function(e,t,r){"use strict";var n;try{n=r(302)}catch(e){"undefined"!=typeof window&&(n=window.esprima)}var o=r(10);e.exports=new o("tag:yaml.org,2002:js/function",{kind:"scalar",resolve:function(e){if(null===e)return!1;try{var t="("+e+")",r=n.parse(t,{range:!0});return"Program"===r.type&&1===r.body.length&&"ExpressionStatement"===r.body[0].type&&("ArrowFunctionExpression"===r.body[0].expression.type||"FunctionExpression"===r.body[0].expression.type)}catch(e){return!1}},construct:function(e){var t,r="("+e+")",o=n.parse(r,{range:!0}),i=[];if("Program"!==o.type||1!==o.body.length||"ExpressionStatement"!==o.body[0].type||"ArrowFunctionExpression"!==o.body[0].expression.type&&"FunctionExpression"!==o.body[0].expression.type)throw new Error("Failed to resolve function");return o.body[0].expression.params.forEach(function(e){i.push(e.name)}),t=o.body[0].expression.body.range,"BlockStatement"===o.body[0].expression.body.type?new Function(i,r.slice(t[0]+1,t[1]-1)):new Function(i,"return "+r.slice(t[0],t[1]))},predicate:function(e){return"[object Function]"===Object.prototype.toString.call(e)},represent:function(e){return e.toString()}})},function(e,t,r){var n;n=function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,r),o.loaded=!0,o.exports}return r.m=e,r.c=t,r.p="",r(0)}([function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(1),o=r(3),i=r(8),a=r(15);function s(e,t,r){var a=null,s=function(e,t){r&&r(e,t),a&&a.visit(e,t)},l="function"==typeof r?s:null,u=!1;if(t){u="boolean"==typeof t.comment&&t.comment;var c="boolean"==typeof t.attachComment&&t.attachComment;(u||c)&&((a=new n.CommentHandler).attach=c,t.comment=!0,l=s)}var d,p=!1;t&&"string"==typeof t.sourceType&&(p="module"===t.sourceType),d=t&&"boolean"==typeof t.jsx&&t.jsx?new o.JSXParser(e,t,l):new i.Parser(e,t,l);var f=p?d.parseModule():d.parseScript();return u&&a&&(f.comments=a.comments),d.config.tokens&&(f.tokens=d.tokens),d.config.tolerant&&(f.errors=d.errorHandler.errors),f}t.parse=s,t.parseModule=function(e,t,r){var n=t||{};return n.sourceType="module",s(e,n,r)},t.parseScript=function(e,t,r){var n=t||{};return n.sourceType="script",s(e,n,r)},t.tokenize=function(e,t,r){var n,o=new a.Tokenizer(e,t);n=[];try{for(;;){var i=o.getNextToken();if(!i)break;r&&(i=r(i)),n.push(i)}}catch(e){o.errorHandler.tolerate(e)}return o.errorHandler.tolerant&&(n.errors=o.errors()),n};var l=r(2);t.Syntax=l.Syntax,t.version="4.0.1"},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(2),o=function(){function e(){this.attach=!1,this.comments=[],this.stack=[],this.leading=[],this.trailing=[]}return e.prototype.insertInnerComments=function(e,t){if(e.type===n.Syntax.BlockStatement&&0===e.body.length){for(var r=[],o=this.leading.length-1;o>=0;--o){var i=this.leading[o];t.end.offset>=i.start&&(r.unshift(i.comment),this.leading.splice(o,1),this.trailing.splice(o,1))}r.length&&(e.innerComments=r)}},e.prototype.findTrailingComments=function(e){var t=[];if(this.trailing.length>0){for(var r=this.trailing.length-1;r>=0;--r){var n=this.trailing[r];n.start>=e.end.offset&&t.unshift(n.comment)}return this.trailing.length=0,t}var o=this.stack[this.stack.length-1];if(o&&o.node.trailingComments){var i=o.node.trailingComments[0];i&&i.range[0]>=e.end.offset&&(t=o.node.trailingComments,delete o.node.trailingComments)}return t},e.prototype.findLeadingComments=function(e){for(var t,r=[];this.stack.length>0&&(i=this.stack[this.stack.length-1])&&i.start>=e.start.offset;)t=i.node,this.stack.pop();if(t){for(var n=(t.leadingComments?t.leadingComments.length:0)-1;n>=0;--n){var o=t.leadingComments[n];o.range[1]<=e.start.offset&&(r.unshift(o),t.leadingComments.splice(n,1))}return t.leadingComments&&0===t.leadingComments.length&&delete t.leadingComments,r}for(n=this.leading.length-1;n>=0;--n){var i;(i=this.leading[n]).start<=e.start.offset&&(r.unshift(i.comment),this.leading.splice(n,1))}return r},e.prototype.visitNode=function(e,t){if(!(e.type===n.Syntax.Program&&e.body.length>0)){this.insertInnerComments(e,t);var r=this.findTrailingComments(t),o=this.findLeadingComments(t);o.length>0&&(e.leadingComments=o),r.length>0&&(e.trailingComments=r),this.stack.push({node:e,start:t.start.offset})}},e.prototype.visitComment=function(e,t){var r="L"===e.type[0]?"Line":"Block",n={type:r,value:e.value};if(e.range&&(n.range=e.range),e.loc&&(n.loc=e.loc),this.comments.push(n),this.attach){var o={comment:{type:r,value:e.value,range:[t.start.offset,t.end.offset]},start:t.start.offset};e.loc&&(o.comment.loc=e.loc),e.type=r,this.leading.push(o),this.trailing.push(o)}},e.prototype.visit=function(e,t){"LineComment"===e.type||"BlockComment"===e.type?this.visitComment(e,t):this.attach&&this.visitNode(e,t)},e}();t.CommentHandler=o},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Syntax={AssignmentExpression:"AssignmentExpression",AssignmentPattern:"AssignmentPattern",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DoWhileStatement:"DoWhileStatement",DebuggerStatement:"DebuggerStatement",EmptyStatement:"EmptyStatement",ExportAllDeclaration:"ExportAllDeclaration",ExportDefaultDeclaration:"ExportDefaultDeclaration",ExportNamedDeclaration:"ExportNamedDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForOfStatement:"ForOfStatement",ForInStatement:"ForInStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MetaProperty:"MetaProperty",MethodDefinition:"MethodDefinition",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",RestElement:"RestElement",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",Super:"Super",SwitchCase:"SwitchCase",SwitchStatement:"SwitchStatement",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"}},function(e,t,r){"use strict";var n,o=this&&this.__extends||(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var i=r(4),a=r(5),s=r(6),l=r(7),u=r(8),c=r(13),d=r(14);function p(e){var t;switch(e.type){case s.JSXSyntax.JSXIdentifier:t=e.name;break;case s.JSXSyntax.JSXNamespacedName:var r=e;t=p(r.namespace)+":"+p(r.name);break;case s.JSXSyntax.JSXMemberExpression:var n=e;t=p(n.object)+"."+p(n.property)}return t}c.TokenName[100]="JSXIdentifier",c.TokenName[101]="JSXText";var f=function(e){function t(t,r,n){return e.call(this,t,r,n)||this}return o(t,e),t.prototype.parsePrimaryExpression=function(){return this.match("<")?this.parseJSXRoot():e.prototype.parsePrimaryExpression.call(this)},t.prototype.startJSX=function(){this.scanner.index=this.startMarker.index,this.scanner.lineNumber=this.startMarker.line,this.scanner.lineStart=this.startMarker.index-this.startMarker.column},t.prototype.finishJSX=function(){this.nextToken()},t.prototype.reenterJSX=function(){this.startJSX(),this.expectJSX("}"),this.config.tokens&&this.tokens.pop()},t.prototype.createJSXNode=function(){return this.collectComments(),{index:this.scanner.index,line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart}},t.prototype.createJSXChildNode=function(){return{index:this.scanner.index,line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart}},t.prototype.scanXHTMLEntity=function(e){for(var t="&",r=!0,n=!1,o=!1,a=!1;!this.scanner.eof()&&r&&!n;){var s=this.scanner.source[this.scanner.index];if(s===e)break;if(n=";"===s,t+=s,++this.scanner.index,!n)switch(t.length){case 2:o="#"===s;break;case 3:o&&(r=(a="x"===s)||i.Character.isDecimalDigit(s.charCodeAt(0)),o=o&&!a);break;default:r=(r=r&&!(o&&!i.Character.isDecimalDigit(s.charCodeAt(0))))&&!(a&&!i.Character.isHexDigit(s.charCodeAt(0)))}}if(r&&n&&t.length>2){var l=t.substr(1,t.length-2);o&&l.length>1?t=String.fromCharCode(parseInt(l.substr(1),10)):a&&l.length>2?t=String.fromCharCode(parseInt("0"+l.substr(1),16)):o||a||!d.XHTMLEntities[l]||(t=d.XHTMLEntities[l])}return t},t.prototype.lexJSX=function(){var e=this.scanner.source.charCodeAt(this.scanner.index);if(60===e||62===e||47===e||58===e||61===e||123===e||125===e)return{type:7,value:s=this.scanner.source[this.scanner.index++],lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:this.scanner.index-1,end:this.scanner.index};if(34===e||39===e){for(var t=this.scanner.index,r=this.scanner.source[this.scanner.index++],n="";!this.scanner.eof()&&(l=this.scanner.source[this.scanner.index++])!==r;)n+="&"===l?this.scanXHTMLEntity(r):l;return{type:8,value:n,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:t,end:this.scanner.index}}if(46===e){var o=this.scanner.source.charCodeAt(this.scanner.index+1),a=this.scanner.source.charCodeAt(this.scanner.index+2),s=46===o&&46===a?"...":".";return t=this.scanner.index,this.scanner.index+=s.length,{type:7,value:s,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:t,end:this.scanner.index}}if(96===e)return{type:10,value:"",lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:this.scanner.index,end:this.scanner.index};if(i.Character.isIdentifierStart(e)&&92!==e){for(t=this.scanner.index,++this.scanner.index;!this.scanner.eof();){var l=this.scanner.source.charCodeAt(this.scanner.index);if(i.Character.isIdentifierPart(l)&&92!==l)++this.scanner.index;else{if(45!==l)break;++this.scanner.index}}return{type:100,value:this.scanner.source.slice(t,this.scanner.index),lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:t,end:this.scanner.index}}return this.scanner.lex()},t.prototype.nextJSXToken=function(){this.collectComments(),this.startMarker.index=this.scanner.index,this.startMarker.line=this.scanner.lineNumber,this.startMarker.column=this.scanner.index-this.scanner.lineStart;var e=this.lexJSX();return this.lastMarker.index=this.scanner.index,this.lastMarker.line=this.scanner.lineNumber,this.lastMarker.column=this.scanner.index-this.scanner.lineStart,this.config.tokens&&this.tokens.push(this.convertToken(e)),e},t.prototype.nextJSXText=function(){this.startMarker.index=this.scanner.index,this.startMarker.line=this.scanner.lineNumber,this.startMarker.column=this.scanner.index-this.scanner.lineStart;for(var e=this.scanner.index,t="";!this.scanner.eof();){var r=this.scanner.source[this.scanner.index];if("{"===r||"<"===r)break;++this.scanner.index,t+=r,i.Character.isLineTerminator(r.charCodeAt(0))&&(++this.scanner.lineNumber,"\r"===r&&"\n"===this.scanner.source[this.scanner.index]&&++this.scanner.index,this.scanner.lineStart=this.scanner.index)}this.lastMarker.index=this.scanner.index,this.lastMarker.line=this.scanner.lineNumber,this.lastMarker.column=this.scanner.index-this.scanner.lineStart;var n={type:101,value:t,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:e,end:this.scanner.index};return t.length>0&&this.config.tokens&&this.tokens.push(this.convertToken(n)),n},t.prototype.peekJSXToken=function(){var e=this.scanner.saveState();this.scanner.scanComments();var t=this.lexJSX();return this.scanner.restoreState(e),t},t.prototype.expectJSX=function(e){var t=this.nextJSXToken();7===t.type&&t.value===e||this.throwUnexpectedToken(t)},t.prototype.matchJSX=function(e){var t=this.peekJSXToken();return 7===t.type&&t.value===e},t.prototype.parseJSXIdentifier=function(){var e=this.createJSXNode(),t=this.nextJSXToken();return 100!==t.type&&this.throwUnexpectedToken(t),this.finalize(e,new a.JSXIdentifier(t.value))},t.prototype.parseJSXElementName=function(){var e=this.createJSXNode(),t=this.parseJSXIdentifier();if(this.matchJSX(":")){var r=t;this.expectJSX(":");var n=this.parseJSXIdentifier();t=this.finalize(e,new a.JSXNamespacedName(r,n))}else if(this.matchJSX("."))for(;this.matchJSX(".");){var o=t;this.expectJSX(".");var i=this.parseJSXIdentifier();t=this.finalize(e,new a.JSXMemberExpression(o,i))}return t},t.prototype.parseJSXAttributeName=function(){var e,t=this.createJSXNode(),r=this.parseJSXIdentifier();if(this.matchJSX(":")){var n=r;this.expectJSX(":");var o=this.parseJSXIdentifier();e=this.finalize(t,new a.JSXNamespacedName(n,o))}else e=r;return e},t.prototype.parseJSXStringLiteralAttribute=function(){var e=this.createJSXNode(),t=this.nextJSXToken();8!==t.type&&this.throwUnexpectedToken(t);var r=this.getTokenRaw(t);return this.finalize(e,new l.Literal(t.value,r))},t.prototype.parseJSXExpressionAttribute=function(){var e=this.createJSXNode();this.expectJSX("{"),this.finishJSX(),this.match("}")&&this.tolerateError("JSX attributes must only be assigned a non-empty expression");var t=this.parseAssignmentExpression();return this.reenterJSX(),this.finalize(e,new a.JSXExpressionContainer(t))},t.prototype.parseJSXAttributeValue=function(){return this.matchJSX("{")?this.parseJSXExpressionAttribute():this.matchJSX("<")?this.parseJSXElement():this.parseJSXStringLiteralAttribute()},t.prototype.parseJSXNameValueAttribute=function(){var e=this.createJSXNode(),t=this.parseJSXAttributeName(),r=null;return this.matchJSX("=")&&(this.expectJSX("="),r=this.parseJSXAttributeValue()),this.finalize(e,new a.JSXAttribute(t,r))},t.prototype.parseJSXSpreadAttribute=function(){var e=this.createJSXNode();this.expectJSX("{"),this.expectJSX("..."),this.finishJSX();var t=this.parseAssignmentExpression();return this.reenterJSX(),this.finalize(e,new a.JSXSpreadAttribute(t))},t.prototype.parseJSXAttributes=function(){for(var e=[];!this.matchJSX("/")&&!this.matchJSX(">");){var t=this.matchJSX("{")?this.parseJSXSpreadAttribute():this.parseJSXNameValueAttribute();e.push(t)}return e},t.prototype.parseJSXOpeningElement=function(){var e=this.createJSXNode();this.expectJSX("<");var t=this.parseJSXElementName(),r=this.parseJSXAttributes(),n=this.matchJSX("/");return n&&this.expectJSX("/"),this.expectJSX(">"),this.finalize(e,new a.JSXOpeningElement(t,n,r))},t.prototype.parseJSXBoundaryElement=function(){var e=this.createJSXNode();if(this.expectJSX("<"),this.matchJSX("/")){this.expectJSX("/");var t=this.parseJSXElementName();return this.expectJSX(">"),this.finalize(e,new a.JSXClosingElement(t))}var r=this.parseJSXElementName(),n=this.parseJSXAttributes(),o=this.matchJSX("/");return o&&this.expectJSX("/"),this.expectJSX(">"),this.finalize(e,new a.JSXOpeningElement(r,o,n))},t.prototype.parseJSXEmptyExpression=function(){var e=this.createJSXChildNode();return this.collectComments(),this.lastMarker.index=this.scanner.index,this.lastMarker.line=this.scanner.lineNumber,this.lastMarker.column=this.scanner.index-this.scanner.lineStart,this.finalize(e,new a.JSXEmptyExpression)},t.prototype.parseJSXExpressionContainer=function(){var e,t=this.createJSXNode();return this.expectJSX("{"),this.matchJSX("}")?(e=this.parseJSXEmptyExpression(),this.expectJSX("}")):(this.finishJSX(),e=this.parseAssignmentExpression(),this.reenterJSX()),this.finalize(t,new a.JSXExpressionContainer(e))},t.prototype.parseJSXChildren=function(){for(var e=[];!this.scanner.eof();){var t=this.createJSXChildNode(),r=this.nextJSXText();if(r.start0))break;i=this.finalize(e.node,new a.JSXElement(e.opening,e.children,e.closing)),(e=t[t.length-1]).children.push(i),t.pop()}}return e},t.prototype.parseJSXElement=function(){var e=this.createJSXNode(),t=this.parseJSXOpeningElement(),r=[],n=null;if(!t.selfClosing){var o=this.parseComplexJSXElement({node:e,opening:t,closing:n,children:r});r=o.children,n=o.closing}return this.finalize(e,new a.JSXElement(t,r,n))},t.prototype.parseJSXRoot=function(){this.config.tokens&&this.tokens.pop(),this.startJSX();var e=this.parseJSXElement();return this.finishJSX(),e},t.prototype.isStartOfExpression=function(){return e.prototype.isStartOfExpression.call(this)||this.match("<")},t}(u.Parser);t.JSXParser=f},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r={NonAsciiIdentifierStart:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,NonAsciiIdentifierPart:/[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/};t.Character={fromCodePoint:function(e){return e<65536?String.fromCharCode(e):String.fromCharCode(55296+(e-65536>>10))+String.fromCharCode(56320+(e-65536&1023))},isWhiteSpace:function(e){return 32===e||9===e||11===e||12===e||160===e||e>=5760&&[5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279].indexOf(e)>=0},isLineTerminator:function(e){return 10===e||13===e||8232===e||8233===e},isIdentifierStart:function(e){return 36===e||95===e||e>=65&&e<=90||e>=97&&e<=122||92===e||e>=128&&r.NonAsciiIdentifierStart.test(t.Character.fromCodePoint(e))},isIdentifierPart:function(e){return 36===e||95===e||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||92===e||e>=128&&r.NonAsciiIdentifierPart.test(t.Character.fromCodePoint(e))},isDecimalDigit:function(e){return e>=48&&e<=57},isHexDigit:function(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102},isOctalDigit:function(e){return e>=48&&e<=55}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(6);t.JSXClosingElement=function(e){this.type=n.JSXSyntax.JSXClosingElement,this.name=e};t.JSXElement=function(e,t,r){this.type=n.JSXSyntax.JSXElement,this.openingElement=e,this.children=t,this.closingElement=r};t.JSXEmptyExpression=function(){this.type=n.JSXSyntax.JSXEmptyExpression};t.JSXExpressionContainer=function(e){this.type=n.JSXSyntax.JSXExpressionContainer,this.expression=e};t.JSXIdentifier=function(e){this.type=n.JSXSyntax.JSXIdentifier,this.name=e};t.JSXMemberExpression=function(e,t){this.type=n.JSXSyntax.JSXMemberExpression,this.object=e,this.property=t};t.JSXAttribute=function(e,t){this.type=n.JSXSyntax.JSXAttribute,this.name=e,this.value=t};t.JSXNamespacedName=function(e,t){this.type=n.JSXSyntax.JSXNamespacedName,this.namespace=e,this.name=t};t.JSXOpeningElement=function(e,t,r){this.type=n.JSXSyntax.JSXOpeningElement,this.name=e,this.selfClosing=t,this.attributes=r};t.JSXSpreadAttribute=function(e){this.type=n.JSXSyntax.JSXSpreadAttribute,this.argument=e};t.JSXText=function(e,t){this.type=n.JSXSyntax.JSXText,this.value=e,this.raw=t}},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.JSXSyntax={JSXAttribute:"JSXAttribute",JSXClosingElement:"JSXClosingElement",JSXElement:"JSXElement",JSXEmptyExpression:"JSXEmptyExpression",JSXExpressionContainer:"JSXExpressionContainer",JSXIdentifier:"JSXIdentifier",JSXMemberExpression:"JSXMemberExpression",JSXNamespacedName:"JSXNamespacedName",JSXOpeningElement:"JSXOpeningElement",JSXSpreadAttribute:"JSXSpreadAttribute",JSXText:"JSXText"}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(2);t.ArrayExpression=function(e){this.type=n.Syntax.ArrayExpression,this.elements=e};t.ArrayPattern=function(e){this.type=n.Syntax.ArrayPattern,this.elements=e};t.ArrowFunctionExpression=function(e,t,r){this.type=n.Syntax.ArrowFunctionExpression,this.id=null,this.params=e,this.body=t,this.generator=!1,this.expression=r,this.async=!1};t.AssignmentExpression=function(e,t,r){this.type=n.Syntax.AssignmentExpression,this.operator=e,this.left=t,this.right=r};t.AssignmentPattern=function(e,t){this.type=n.Syntax.AssignmentPattern,this.left=e,this.right=t};t.AsyncArrowFunctionExpression=function(e,t,r){this.type=n.Syntax.ArrowFunctionExpression,this.id=null,this.params=e,this.body=t,this.generator=!1,this.expression=r,this.async=!0};t.AsyncFunctionDeclaration=function(e,t,r){this.type=n.Syntax.FunctionDeclaration,this.id=e,this.params=t,this.body=r,this.generator=!1,this.expression=!1,this.async=!0};t.AsyncFunctionExpression=function(e,t,r){this.type=n.Syntax.FunctionExpression,this.id=e,this.params=t,this.body=r,this.generator=!1,this.expression=!1,this.async=!0};t.AwaitExpression=function(e){this.type=n.Syntax.AwaitExpression,this.argument=e};t.BinaryExpression=function(e,t,r){var o="||"===e||"&&"===e;this.type=o?n.Syntax.LogicalExpression:n.Syntax.BinaryExpression,this.operator=e,this.left=t,this.right=r};t.BlockStatement=function(e){this.type=n.Syntax.BlockStatement,this.body=e};t.BreakStatement=function(e){this.type=n.Syntax.BreakStatement,this.label=e};t.CallExpression=function(e,t){this.type=n.Syntax.CallExpression,this.callee=e,this.arguments=t};t.CatchClause=function(e,t){this.type=n.Syntax.CatchClause,this.param=e,this.body=t};t.ClassBody=function(e){this.type=n.Syntax.ClassBody,this.body=e};t.ClassDeclaration=function(e,t,r){this.type=n.Syntax.ClassDeclaration,this.id=e,this.superClass=t,this.body=r};t.ClassExpression=function(e,t,r){this.type=n.Syntax.ClassExpression,this.id=e,this.superClass=t,this.body=r};t.ComputedMemberExpression=function(e,t){this.type=n.Syntax.MemberExpression,this.computed=!0,this.object=e,this.property=t};t.ConditionalExpression=function(e,t,r){this.type=n.Syntax.ConditionalExpression,this.test=e,this.consequent=t,this.alternate=r};t.ContinueStatement=function(e){this.type=n.Syntax.ContinueStatement,this.label=e};t.DebuggerStatement=function(){this.type=n.Syntax.DebuggerStatement};t.Directive=function(e,t){this.type=n.Syntax.ExpressionStatement,this.expression=e,this.directive=t};t.DoWhileStatement=function(e,t){this.type=n.Syntax.DoWhileStatement,this.body=e,this.test=t};t.EmptyStatement=function(){this.type=n.Syntax.EmptyStatement};t.ExportAllDeclaration=function(e){this.type=n.Syntax.ExportAllDeclaration,this.source=e};t.ExportDefaultDeclaration=function(e){this.type=n.Syntax.ExportDefaultDeclaration,this.declaration=e};t.ExportNamedDeclaration=function(e,t,r){this.type=n.Syntax.ExportNamedDeclaration,this.declaration=e,this.specifiers=t,this.source=r};t.ExportSpecifier=function(e,t){this.type=n.Syntax.ExportSpecifier,this.exported=t,this.local=e};t.ExpressionStatement=function(e){this.type=n.Syntax.ExpressionStatement,this.expression=e};t.ForInStatement=function(e,t,r){this.type=n.Syntax.ForInStatement,this.left=e,this.right=t,this.body=r,this.each=!1};t.ForOfStatement=function(e,t,r){this.type=n.Syntax.ForOfStatement,this.left=e,this.right=t,this.body=r};t.ForStatement=function(e,t,r,o){this.type=n.Syntax.ForStatement,this.init=e,this.test=t,this.update=r,this.body=o};t.FunctionDeclaration=function(e,t,r,o){this.type=n.Syntax.FunctionDeclaration,this.id=e,this.params=t,this.body=r,this.generator=o,this.expression=!1,this.async=!1};t.FunctionExpression=function(e,t,r,o){this.type=n.Syntax.FunctionExpression,this.id=e,this.params=t,this.body=r,this.generator=o,this.expression=!1,this.async=!1};t.Identifier=function(e){this.type=n.Syntax.Identifier,this.name=e};t.IfStatement=function(e,t,r){this.type=n.Syntax.IfStatement,this.test=e,this.consequent=t,this.alternate=r};t.ImportDeclaration=function(e,t){this.type=n.Syntax.ImportDeclaration,this.specifiers=e,this.source=t};t.ImportDefaultSpecifier=function(e){this.type=n.Syntax.ImportDefaultSpecifier,this.local=e};t.ImportNamespaceSpecifier=function(e){this.type=n.Syntax.ImportNamespaceSpecifier,this.local=e};t.ImportSpecifier=function(e,t){this.type=n.Syntax.ImportSpecifier,this.local=e,this.imported=t};t.LabeledStatement=function(e,t){this.type=n.Syntax.LabeledStatement,this.label=e,this.body=t};t.Literal=function(e,t){this.type=n.Syntax.Literal,this.value=e,this.raw=t};t.MetaProperty=function(e,t){this.type=n.Syntax.MetaProperty,this.meta=e,this.property=t};t.MethodDefinition=function(e,t,r,o,i){this.type=n.Syntax.MethodDefinition,this.key=e,this.computed=t,this.value=r,this.kind=o,this.static=i};t.Module=function(e){this.type=n.Syntax.Program,this.body=e,this.sourceType="module"};t.NewExpression=function(e,t){this.type=n.Syntax.NewExpression,this.callee=e,this.arguments=t};t.ObjectExpression=function(e){this.type=n.Syntax.ObjectExpression,this.properties=e};t.ObjectPattern=function(e){this.type=n.Syntax.ObjectPattern,this.properties=e};t.Property=function(e,t,r,o,i,a){this.type=n.Syntax.Property,this.key=t,this.computed=r,this.value=o,this.kind=e,this.method=i,this.shorthand=a};t.RegexLiteral=function(e,t,r,o){this.type=n.Syntax.Literal,this.value=e,this.raw=t,this.regex={pattern:r,flags:o}};t.RestElement=function(e){this.type=n.Syntax.RestElement,this.argument=e};t.ReturnStatement=function(e){this.type=n.Syntax.ReturnStatement,this.argument=e};t.Script=function(e){this.type=n.Syntax.Program,this.body=e,this.sourceType="script"};t.SequenceExpression=function(e){this.type=n.Syntax.SequenceExpression,this.expressions=e};t.SpreadElement=function(e){this.type=n.Syntax.SpreadElement,this.argument=e};t.StaticMemberExpression=function(e,t){this.type=n.Syntax.MemberExpression,this.computed=!1,this.object=e,this.property=t};t.Super=function(){this.type=n.Syntax.Super};t.SwitchCase=function(e,t){this.type=n.Syntax.SwitchCase,this.test=e,this.consequent=t};t.SwitchStatement=function(e,t){this.type=n.Syntax.SwitchStatement,this.discriminant=e,this.cases=t};t.TaggedTemplateExpression=function(e,t){this.type=n.Syntax.TaggedTemplateExpression,this.tag=e,this.quasi=t};t.TemplateElement=function(e,t){this.type=n.Syntax.TemplateElement,this.value=e,this.tail=t};t.TemplateLiteral=function(e,t){this.type=n.Syntax.TemplateLiteral,this.quasis=e,this.expressions=t};t.ThisExpression=function(){this.type=n.Syntax.ThisExpression};t.ThrowStatement=function(e){this.type=n.Syntax.ThrowStatement,this.argument=e};t.TryStatement=function(e,t,r){this.type=n.Syntax.TryStatement,this.block=e,this.handler=t,this.finalizer=r};t.UnaryExpression=function(e,t){this.type=n.Syntax.UnaryExpression,this.operator=e,this.argument=t,this.prefix=!0};t.UpdateExpression=function(e,t,r){this.type=n.Syntax.UpdateExpression,this.operator=e,this.argument=t,this.prefix=r};t.VariableDeclaration=function(e,t){this.type=n.Syntax.VariableDeclaration,this.declarations=e,this.kind=t};t.VariableDeclarator=function(e,t){this.type=n.Syntax.VariableDeclarator,this.id=e,this.init=t};t.WhileStatement=function(e,t){this.type=n.Syntax.WhileStatement,this.test=e,this.body=t};t.WithStatement=function(e,t){this.type=n.Syntax.WithStatement,this.object=e,this.body=t};t.YieldExpression=function(e,t){this.type=n.Syntax.YieldExpression,this.argument=e,this.delegate=t}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(9),o=r(10),i=r(11),a=r(7),s=r(12),l=r(2),u=r(13),c=function(){function e(e,t,r){void 0===t&&(t={}),this.config={range:"boolean"==typeof t.range&&t.range,loc:"boolean"==typeof t.loc&&t.loc,source:null,tokens:"boolean"==typeof t.tokens&&t.tokens,comment:"boolean"==typeof t.comment&&t.comment,tolerant:"boolean"==typeof t.tolerant&&t.tolerant},this.config.loc&&t.source&&null!==t.source&&(this.config.source=String(t.source)),this.delegate=r,this.errorHandler=new o.ErrorHandler,this.errorHandler.tolerant=this.config.tolerant,this.scanner=new s.Scanner(e,this.errorHandler),this.scanner.trackComment=this.config.comment,this.operatorPrecedence={")":0,";":0,",":0,"=":0,"]":0,"||":1,"&&":2,"|":3,"^":4,"&":5,"==":6,"!=":6,"===":6,"!==":6,"<":7,">":7,"<=":7,">=":7,"<<":8,">>":8,">>>":8,"+":9,"-":9,"*":11,"/":11,"%":11},this.lookahead={type:2,value:"",lineNumber:this.scanner.lineNumber,lineStart:0,start:0,end:0},this.hasLineTerminator=!1,this.context={isModule:!1,await:!1,allowIn:!0,allowStrictDirective:!0,allowYield:!0,firstCoverInitializedNameError:null,isAssignmentTarget:!1,isBindingElement:!1,inFunctionBody:!1,inIteration:!1,inSwitch:!1,labelSet:{},strict:!1},this.tokens=[],this.startMarker={index:0,line:this.scanner.lineNumber,column:0},this.lastMarker={index:0,line:this.scanner.lineNumber,column:0},this.nextToken(),this.lastMarker={index:this.scanner.index,line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart}}return e.prototype.throwError=function(e){for(var t=[],r=1;r0&&this.delegate)for(var t=0;t>="===e||">>>="===e||"&="===e||"^="===e||"|="===e},e.prototype.isolateCoverGrammar=function(e){var t=this.context.isBindingElement,r=this.context.isAssignmentTarget,n=this.context.firstCoverInitializedNameError;this.context.isBindingElement=!0,this.context.isAssignmentTarget=!0,this.context.firstCoverInitializedNameError=null;var o=e.call(this);return null!==this.context.firstCoverInitializedNameError&&this.throwUnexpectedToken(this.context.firstCoverInitializedNameError),this.context.isBindingElement=t,this.context.isAssignmentTarget=r,this.context.firstCoverInitializedNameError=n,o},e.prototype.inheritCoverGrammar=function(e){var t=this.context.isBindingElement,r=this.context.isAssignmentTarget,n=this.context.firstCoverInitializedNameError;this.context.isBindingElement=!0,this.context.isAssignmentTarget=!0,this.context.firstCoverInitializedNameError=null;var o=e.call(this);return this.context.isBindingElement=this.context.isBindingElement&&t,this.context.isAssignmentTarget=this.context.isAssignmentTarget&&r,this.context.firstCoverInitializedNameError=n||this.context.firstCoverInitializedNameError,o},e.prototype.consumeSemicolon=function(){this.match(";")?this.nextToken():this.hasLineTerminator||(2===this.lookahead.type||this.match("}")||this.throwUnexpectedToken(this.lookahead),this.lastMarker.index=this.startMarker.index,this.lastMarker.line=this.startMarker.line,this.lastMarker.column=this.startMarker.column)},e.prototype.parsePrimaryExpression=function(){var e,t,r,n=this.createNode();switch(this.lookahead.type){case 3:(this.context.isModule||this.context.await)&&"await"===this.lookahead.value&&this.tolerateUnexpectedToken(this.lookahead),e=this.matchAsyncFunction()?this.parseFunctionExpression():this.finalize(n,new a.Identifier(this.nextToken().value));break;case 6:case 8:this.context.strict&&this.lookahead.octal&&this.tolerateUnexpectedToken(this.lookahead,i.Messages.StrictOctalLiteral),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,t=this.nextToken(),r=this.getTokenRaw(t),e=this.finalize(n,new a.Literal(t.value,r));break;case 1:this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,t=this.nextToken(),r=this.getTokenRaw(t),e=this.finalize(n,new a.Literal("true"===t.value,r));break;case 5:this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,t=this.nextToken(),r=this.getTokenRaw(t),e=this.finalize(n,new a.Literal(null,r));break;case 10:e=this.parseTemplateLiteral();break;case 7:switch(this.lookahead.value){case"(":this.context.isBindingElement=!1,e=this.inheritCoverGrammar(this.parseGroupExpression);break;case"[":e=this.inheritCoverGrammar(this.parseArrayInitializer);break;case"{":e=this.inheritCoverGrammar(this.parseObjectInitializer);break;case"/":case"/=":this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,this.scanner.index=this.startMarker.index,t=this.nextRegexToken(),r=this.getTokenRaw(t),e=this.finalize(n,new a.RegexLiteral(t.regex,r,t.pattern,t.flags));break;default:e=this.throwUnexpectedToken(this.nextToken())}break;case 4:!this.context.strict&&this.context.allowYield&&this.matchKeyword("yield")?e=this.parseIdentifierName():!this.context.strict&&this.matchKeyword("let")?e=this.finalize(n,new a.Identifier(this.nextToken().value)):(this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,this.matchKeyword("function")?e=this.parseFunctionExpression():this.matchKeyword("this")?(this.nextToken(),e=this.finalize(n,new a.ThisExpression)):e=this.matchKeyword("class")?this.parseClassExpression():this.throwUnexpectedToken(this.nextToken()));break;default:e=this.throwUnexpectedToken(this.nextToken())}return e},e.prototype.parseSpreadElement=function(){var e=this.createNode();this.expect("...");var t=this.inheritCoverGrammar(this.parseAssignmentExpression);return this.finalize(e,new a.SpreadElement(t))},e.prototype.parseArrayInitializer=function(){var e=this.createNode(),t=[];for(this.expect("[");!this.match("]");)if(this.match(","))this.nextToken(),t.push(null);else if(this.match("...")){var r=this.parseSpreadElement();this.match("]")||(this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,this.expect(",")),t.push(r)}else t.push(this.inheritCoverGrammar(this.parseAssignmentExpression)),this.match("]")||this.expect(",");return this.expect("]"),this.finalize(e,new a.ArrayExpression(t))},e.prototype.parsePropertyMethod=function(e){this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;var t=this.context.strict,r=this.context.allowStrictDirective;this.context.allowStrictDirective=e.simple;var n=this.isolateCoverGrammar(this.parseFunctionSourceElements);return this.context.strict&&e.firstRestricted&&this.tolerateUnexpectedToken(e.firstRestricted,e.message),this.context.strict&&e.stricted&&this.tolerateUnexpectedToken(e.stricted,e.message),this.context.strict=t,this.context.allowStrictDirective=r,n},e.prototype.parsePropertyMethodFunction=function(){var e=this.createNode(),t=this.context.allowYield;this.context.allowYield=!0;var r=this.parseFormalParameters(),n=this.parsePropertyMethod(r);return this.context.allowYield=t,this.finalize(e,new a.FunctionExpression(null,r.params,n,!1))},e.prototype.parsePropertyMethodAsyncFunction=function(){var e=this.createNode(),t=this.context.allowYield,r=this.context.await;this.context.allowYield=!1,this.context.await=!0;var n=this.parseFormalParameters(),o=this.parsePropertyMethod(n);return this.context.allowYield=t,this.context.await=r,this.finalize(e,new a.AsyncFunctionExpression(null,n.params,o))},e.prototype.parseObjectPropertyKey=function(){var e,t=this.createNode(),r=this.nextToken();switch(r.type){case 8:case 6:this.context.strict&&r.octal&&this.tolerateUnexpectedToken(r,i.Messages.StrictOctalLiteral);var n=this.getTokenRaw(r);e=this.finalize(t,new a.Literal(r.value,n));break;case 3:case 1:case 5:case 4:e=this.finalize(t,new a.Identifier(r.value));break;case 7:"["===r.value?(e=this.isolateCoverGrammar(this.parseAssignmentExpression),this.expect("]")):e=this.throwUnexpectedToken(r);break;default:e=this.throwUnexpectedToken(r)}return e},e.prototype.isPropertyKey=function(e,t){return e.type===l.Syntax.Identifier&&e.name===t||e.type===l.Syntax.Literal&&e.value===t},e.prototype.parseObjectProperty=function(e){var t,r=this.createNode(),n=this.lookahead,o=null,s=null,l=!1,u=!1,c=!1,d=!1;if(3===n.type){var p=n.value;this.nextToken(),l=this.match("["),o=(d=!(this.hasLineTerminator||"async"!==p||this.match(":")||this.match("(")||this.match("*")||this.match(",")))?this.parseObjectPropertyKey():this.finalize(r,new a.Identifier(p))}else this.match("*")?this.nextToken():(l=this.match("["),o=this.parseObjectPropertyKey());var f=this.qualifiedPropertyName(this.lookahead);if(3===n.type&&!d&&"get"===n.value&&f)t="get",l=this.match("["),o=this.parseObjectPropertyKey(),this.context.allowYield=!1,s=this.parseGetterMethod();else if(3===n.type&&!d&&"set"===n.value&&f)t="set",l=this.match("["),o=this.parseObjectPropertyKey(),s=this.parseSetterMethod();else if(7===n.type&&"*"===n.value&&f)t="init",l=this.match("["),o=this.parseObjectPropertyKey(),s=this.parseGeneratorMethod(),u=!0;else if(o||this.throwUnexpectedToken(this.lookahead),t="init",this.match(":")&&!d)!l&&this.isPropertyKey(o,"__proto__")&&(e.value&&this.tolerateError(i.Messages.DuplicateProtoProperty),e.value=!0),this.nextToken(),s=this.inheritCoverGrammar(this.parseAssignmentExpression);else if(this.match("("))s=d?this.parsePropertyMethodAsyncFunction():this.parsePropertyMethodFunction(),u=!0;else if(3===n.type)if(p=this.finalize(r,new a.Identifier(n.value)),this.match("=")){this.context.firstCoverInitializedNameError=this.lookahead,this.nextToken(),c=!0;var h=this.isolateCoverGrammar(this.parseAssignmentExpression);s=this.finalize(r,new a.AssignmentPattern(p,h))}else c=!0,s=p;else this.throwUnexpectedToken(this.nextToken());return this.finalize(r,new a.Property(t,o,l,s,u,c))},e.prototype.parseObjectInitializer=function(){var e=this.createNode();this.expect("{");for(var t=[],r={value:!1};!this.match("}");)t.push(this.parseObjectProperty(r)),this.match("}")||this.expectCommaSeparator();return this.expect("}"),this.finalize(e,new a.ObjectExpression(t))},e.prototype.parseTemplateHead=function(){n.assert(this.lookahead.head,"Template literal must start with a template head");var e=this.createNode(),t=this.nextToken(),r=t.value,o=t.cooked;return this.finalize(e,new a.TemplateElement({raw:r,cooked:o},t.tail))},e.prototype.parseTemplateElement=function(){10!==this.lookahead.type&&this.throwUnexpectedToken();var e=this.createNode(),t=this.nextToken(),r=t.value,n=t.cooked;return this.finalize(e,new a.TemplateElement({raw:r,cooked:n},t.tail))},e.prototype.parseTemplateLiteral=function(){var e=this.createNode(),t=[],r=[],n=this.parseTemplateHead();for(r.push(n);!n.tail;)t.push(this.parseExpression()),n=this.parseTemplateElement(),r.push(n);return this.finalize(e,new a.TemplateLiteral(r,t))},e.prototype.reinterpretExpressionAsPattern=function(e){switch(e.type){case l.Syntax.Identifier:case l.Syntax.MemberExpression:case l.Syntax.RestElement:case l.Syntax.AssignmentPattern:break;case l.Syntax.SpreadElement:e.type=l.Syntax.RestElement,this.reinterpretExpressionAsPattern(e.argument);break;case l.Syntax.ArrayExpression:e.type=l.Syntax.ArrayPattern;for(var t=0;t")||this.expect("=>"),e={type:"ArrowParameterPlaceHolder",params:[],async:!1};else{var t=this.lookahead,r=[];if(this.match("..."))e=this.parseRestElement(r),this.expect(")"),this.match("=>")||this.expect("=>"),e={type:"ArrowParameterPlaceHolder",params:[e],async:!1};else{var n=!1;if(this.context.isBindingElement=!0,e=this.inheritCoverGrammar(this.parseAssignmentExpression),this.match(",")){var o=[];for(this.context.isAssignmentTarget=!1,o.push(e);2!==this.lookahead.type&&this.match(",");){if(this.nextToken(),this.match(")")){this.nextToken();for(var i=0;i")||this.expect("=>"),this.context.isBindingElement=!1,i=0;i")&&(e.type===l.Syntax.Identifier&&"yield"===e.name&&(n=!0,e={type:"ArrowParameterPlaceHolder",params:[e],async:!1}),!n)){if(this.context.isBindingElement||this.throwUnexpectedToken(this.lookahead),e.type===l.Syntax.SequenceExpression)for(i=0;i")){for(var l=0;l0){this.nextToken(),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;for(var o=[e,this.lookahead],i=t,s=this.isolateCoverGrammar(this.parseExponentiationExpression),l=[i,r.value,s],u=[n];!((n=this.binaryPrecedence(this.lookahead))<=0);){for(;l.length>2&&n<=u[u.length-1];){s=l.pop();var c=l.pop();u.pop(),i=l.pop(),o.pop();var d=this.startNode(o[o.length-1]);l.push(this.finalize(d,new a.BinaryExpression(c,i,s)))}l.push(this.nextToken().value),u.push(n),o.push(this.lookahead),l.push(this.isolateCoverGrammar(this.parseExponentiationExpression))}var p=l.length-1;t=l[p];for(var f=o.pop();p>1;){var h=o.pop(),m=f&&f.lineStart;d=this.startNode(h,m),c=l[p-1],t=this.finalize(d,new a.BinaryExpression(c,l[p-2],t)),p-=2,f=h}}return t},e.prototype.parseConditionalExpression=function(){var e=this.lookahead,t=this.inheritCoverGrammar(this.parseBinaryExpression);if(this.match("?")){this.nextToken();var r=this.context.allowIn;this.context.allowIn=!0;var n=this.isolateCoverGrammar(this.parseAssignmentExpression);this.context.allowIn=r,this.expect(":");var o=this.isolateCoverGrammar(this.parseAssignmentExpression);t=this.finalize(this.startNode(e),new a.ConditionalExpression(t,n,o)),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1}return t},e.prototype.checkPatternParam=function(e,t){switch(t.type){case l.Syntax.Identifier:this.validateParam(e,t,t.name);break;case l.Syntax.RestElement:this.checkPatternParam(e,t.argument);break;case l.Syntax.AssignmentPattern:this.checkPatternParam(e,t.left);break;case l.Syntax.ArrayPattern:for(var r=0;r")){this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;var o=e.async,s=this.reinterpretAsCoverFormalsList(e);if(s){this.hasLineTerminator&&this.tolerateUnexpectedToken(this.lookahead),this.context.firstCoverInitializedNameError=null;var u=this.context.strict,c=this.context.allowStrictDirective;this.context.allowStrictDirective=s.simple;var d=this.context.allowYield,p=this.context.await;this.context.allowYield=!0,this.context.await=o;var f=this.startNode(t);this.expect("=>");var h=void 0;if(this.match("{")){var m=this.context.allowIn;this.context.allowIn=!0,h=this.parseFunctionSourceElements(),this.context.allowIn=m}else h=this.isolateCoverGrammar(this.parseAssignmentExpression);var g=h.type!==l.Syntax.BlockStatement;this.context.strict&&s.firstRestricted&&this.throwUnexpectedToken(s.firstRestricted,s.message),this.context.strict&&s.stricted&&this.tolerateUnexpectedToken(s.stricted,s.message),e=o?this.finalize(f,new a.AsyncArrowFunctionExpression(s.params,h,g)):this.finalize(f,new a.ArrowFunctionExpression(s.params,h,g)),this.context.strict=u,this.context.allowStrictDirective=c,this.context.allowYield=d,this.context.await=p}}else if(this.matchAssign()){if(this.context.isAssignmentTarget||this.tolerateError(i.Messages.InvalidLHSInAssignment),this.context.strict&&e.type===l.Syntax.Identifier){var y=e;this.scanner.isRestrictedWord(y.name)&&this.tolerateUnexpectedToken(r,i.Messages.StrictLHSAssignment),this.scanner.isStrictModeReservedWord(y.name)&&this.tolerateUnexpectedToken(r,i.Messages.StrictReservedWord)}this.match("=")?this.reinterpretExpressionAsPattern(e):(this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1);var v=(r=this.nextToken()).value,b=this.isolateCoverGrammar(this.parseAssignmentExpression);e=this.finalize(this.startNode(t),new a.AssignmentExpression(v,e,b)),this.context.firstCoverInitializedNameError=null}}return e},e.prototype.parseExpression=function(){var e=this.lookahead,t=this.isolateCoverGrammar(this.parseAssignmentExpression);if(this.match(",")){var r=[];for(r.push(t);2!==this.lookahead.type&&this.match(",");)this.nextToken(),r.push(this.isolateCoverGrammar(this.parseAssignmentExpression));t=this.finalize(this.startNode(e),new a.SequenceExpression(r))}return t},e.prototype.parseStatementListItem=function(){var e;if(this.context.isAssignmentTarget=!0,this.context.isBindingElement=!0,4===this.lookahead.type)switch(this.lookahead.value){case"export":this.context.isModule||this.tolerateUnexpectedToken(this.lookahead,i.Messages.IllegalExportDeclaration),e=this.parseExportDeclaration();break;case"import":this.context.isModule||this.tolerateUnexpectedToken(this.lookahead,i.Messages.IllegalImportDeclaration),e=this.parseImportDeclaration();break;case"const":e=this.parseLexicalDeclaration({inFor:!1});break;case"function":e=this.parseFunctionDeclaration();break;case"class":e=this.parseClassDeclaration();break;case"let":e=this.isLexicalDeclaration()?this.parseLexicalDeclaration({inFor:!1}):this.parseStatement();break;default:e=this.parseStatement()}else e=this.parseStatement();return e},e.prototype.parseBlock=function(){var e=this.createNode();this.expect("{");for(var t=[];!this.match("}");)t.push(this.parseStatementListItem());return this.expect("}"),this.finalize(e,new a.BlockStatement(t))},e.prototype.parseLexicalBinding=function(e,t){var r=this.createNode(),n=this.parsePattern([],e);this.context.strict&&n.type===l.Syntax.Identifier&&this.scanner.isRestrictedWord(n.name)&&this.tolerateError(i.Messages.StrictVarName);var o=null;return"const"===e?this.matchKeyword("in")||this.matchContextualKeyword("of")||(this.match("=")?(this.nextToken(),o=this.isolateCoverGrammar(this.parseAssignmentExpression)):this.throwError(i.Messages.DeclarationMissingInitializer,"const")):(!t.inFor&&n.type!==l.Syntax.Identifier||this.match("="))&&(this.expect("="),o=this.isolateCoverGrammar(this.parseAssignmentExpression)),this.finalize(r,new a.VariableDeclarator(n,o))},e.prototype.parseBindingList=function(e,t){for(var r=[this.parseLexicalBinding(e,t)];this.match(",");)this.nextToken(),r.push(this.parseLexicalBinding(e,t));return r},e.prototype.isLexicalDeclaration=function(){var e=this.scanner.saveState();this.scanner.scanComments();var t=this.scanner.lex();return this.scanner.restoreState(e),3===t.type||7===t.type&&"["===t.value||7===t.type&&"{"===t.value||4===t.type&&"let"===t.value||4===t.type&&"yield"===t.value},e.prototype.parseLexicalDeclaration=function(e){var t=this.createNode(),r=this.nextToken().value;n.assert("let"===r||"const"===r,"Lexical declaration must be either let or const");var o=this.parseBindingList(r,e);return this.consumeSemicolon(),this.finalize(t,new a.VariableDeclaration(o,r))},e.prototype.parseBindingRestElement=function(e,t){var r=this.createNode();this.expect("...");var n=this.parsePattern(e,t);return this.finalize(r,new a.RestElement(n))},e.prototype.parseArrayPattern=function(e,t){var r=this.createNode();this.expect("[");for(var n=[];!this.match("]");)if(this.match(","))this.nextToken(),n.push(null);else{if(this.match("...")){n.push(this.parseBindingRestElement(e,t));break}n.push(this.parsePatternWithDefault(e,t)),this.match("]")||this.expect(",")}return this.expect("]"),this.finalize(r,new a.ArrayPattern(n))},e.prototype.parsePropertyPattern=function(e,t){var r,n,o=this.createNode(),i=!1,s=!1;if(3===this.lookahead.type){var l=this.lookahead;r=this.parseVariableIdentifier();var u=this.finalize(o,new a.Identifier(l.value));if(this.match("=")){e.push(l),s=!0,this.nextToken();var c=this.parseAssignmentExpression();n=this.finalize(this.startNode(l),new a.AssignmentPattern(u,c))}else this.match(":")?(this.expect(":"),n=this.parsePatternWithDefault(e,t)):(e.push(l),s=!0,n=u)}else i=this.match("["),r=this.parseObjectPropertyKey(),this.expect(":"),n=this.parsePatternWithDefault(e,t);return this.finalize(o,new a.Property("init",r,i,n,!1,s))},e.prototype.parseObjectPattern=function(e,t){var r=this.createNode(),n=[];for(this.expect("{");!this.match("}");)n.push(this.parsePropertyPattern(e,t)),this.match("}")||this.expect(",");return this.expect("}"),this.finalize(r,new a.ObjectPattern(n))},e.prototype.parsePattern=function(e,t){var r;return this.match("[")?r=this.parseArrayPattern(e,t):this.match("{")?r=this.parseObjectPattern(e,t):(!this.matchKeyword("let")||"const"!==t&&"let"!==t||this.tolerateUnexpectedToken(this.lookahead,i.Messages.LetInLexicalBinding),e.push(this.lookahead),r=this.parseVariableIdentifier(t)),r},e.prototype.parsePatternWithDefault=function(e,t){var r=this.lookahead,n=this.parsePattern(e,t);if(this.match("=")){this.nextToken();var o=this.context.allowYield;this.context.allowYield=!0;var i=this.isolateCoverGrammar(this.parseAssignmentExpression);this.context.allowYield=o,n=this.finalize(this.startNode(r),new a.AssignmentPattern(n,i))}return n},e.prototype.parseVariableIdentifier=function(e){var t=this.createNode(),r=this.nextToken();return 4===r.type&&"yield"===r.value?this.context.strict?this.tolerateUnexpectedToken(r,i.Messages.StrictReservedWord):this.context.allowYield||this.throwUnexpectedToken(r):3!==r.type?this.context.strict&&4===r.type&&this.scanner.isStrictModeReservedWord(r.value)?this.tolerateUnexpectedToken(r,i.Messages.StrictReservedWord):(this.context.strict||"let"!==r.value||"var"!==e)&&this.throwUnexpectedToken(r):(this.context.isModule||this.context.await)&&3===r.type&&"await"===r.value&&this.tolerateUnexpectedToken(r),this.finalize(t,new a.Identifier(r.value))},e.prototype.parseVariableDeclaration=function(e){var t=this.createNode(),r=this.parsePattern([],"var");this.context.strict&&r.type===l.Syntax.Identifier&&this.scanner.isRestrictedWord(r.name)&&this.tolerateError(i.Messages.StrictVarName);var n=null;return this.match("=")?(this.nextToken(),n=this.isolateCoverGrammar(this.parseAssignmentExpression)):r.type===l.Syntax.Identifier||e.inFor||this.expect("="),this.finalize(t,new a.VariableDeclarator(r,n))},e.prototype.parseVariableDeclarationList=function(e){var t={inFor:e.inFor},r=[];for(r.push(this.parseVariableDeclaration(t));this.match(",");)this.nextToken(),r.push(this.parseVariableDeclaration(t));return r},e.prototype.parseVariableStatement=function(){var e=this.createNode();this.expectKeyword("var");var t=this.parseVariableDeclarationList({inFor:!1});return this.consumeSemicolon(),this.finalize(e,new a.VariableDeclaration(t,"var"))},e.prototype.parseEmptyStatement=function(){var e=this.createNode();return this.expect(";"),this.finalize(e,new a.EmptyStatement)},e.prototype.parseExpressionStatement=function(){var e=this.createNode(),t=this.parseExpression();return this.consumeSemicolon(),this.finalize(e,new a.ExpressionStatement(t))},e.prototype.parseIfClause=function(){return this.context.strict&&this.matchKeyword("function")&&this.tolerateError(i.Messages.StrictFunction),this.parseStatement()},e.prototype.parseIfStatement=function(){var e,t=this.createNode(),r=null;this.expectKeyword("if"),this.expect("(");var n=this.parseExpression();return!this.match(")")&&this.config.tolerant?(this.tolerateUnexpectedToken(this.nextToken()),e=this.finalize(this.createNode(),new a.EmptyStatement)):(this.expect(")"),e=this.parseIfClause(),this.matchKeyword("else")&&(this.nextToken(),r=this.parseIfClause())),this.finalize(t,new a.IfStatement(n,e,r))},e.prototype.parseDoWhileStatement=function(){var e=this.createNode();this.expectKeyword("do");var t=this.context.inIteration;this.context.inIteration=!0;var r=this.parseStatement();this.context.inIteration=t,this.expectKeyword("while"),this.expect("(");var n=this.parseExpression();return!this.match(")")&&this.config.tolerant?this.tolerateUnexpectedToken(this.nextToken()):(this.expect(")"),this.match(";")&&this.nextToken()),this.finalize(e,new a.DoWhileStatement(r,n))},e.prototype.parseWhileStatement=function(){var e,t=this.createNode();this.expectKeyword("while"),this.expect("(");var r=this.parseExpression();if(!this.match(")")&&this.config.tolerant)this.tolerateUnexpectedToken(this.nextToken()),e=this.finalize(this.createNode(),new a.EmptyStatement);else{this.expect(")");var n=this.context.inIteration;this.context.inIteration=!0,e=this.parseStatement(),this.context.inIteration=n}return this.finalize(t,new a.WhileStatement(r,e))},e.prototype.parseForStatement=function(){var e,t,r,n=null,o=null,s=null,u=!0,c=this.createNode();if(this.expectKeyword("for"),this.expect("("),this.match(";"))this.nextToken();else if(this.matchKeyword("var")){n=this.createNode(),this.nextToken();var d=this.context.allowIn;this.context.allowIn=!1;var p=this.parseVariableDeclarationList({inFor:!0});if(this.context.allowIn=d,1===p.length&&this.matchKeyword("in")){var f=p[0];f.init&&(f.id.type===l.Syntax.ArrayPattern||f.id.type===l.Syntax.ObjectPattern||this.context.strict)&&this.tolerateError(i.Messages.ForInOfLoopInitializer,"for-in"),n=this.finalize(n,new a.VariableDeclaration(p,"var")),this.nextToken(),e=n,t=this.parseExpression(),n=null}else 1===p.length&&null===p[0].init&&this.matchContextualKeyword("of")?(n=this.finalize(n,new a.VariableDeclaration(p,"var")),this.nextToken(),e=n,t=this.parseAssignmentExpression(),n=null,u=!1):(n=this.finalize(n,new a.VariableDeclaration(p,"var")),this.expect(";"))}else if(this.matchKeyword("const")||this.matchKeyword("let")){n=this.createNode();var h=this.nextToken().value;this.context.strict||"in"!==this.lookahead.value?(d=this.context.allowIn,this.context.allowIn=!1,p=this.parseBindingList(h,{inFor:!0}),this.context.allowIn=d,1===p.length&&null===p[0].init&&this.matchKeyword("in")?(n=this.finalize(n,new a.VariableDeclaration(p,h)),this.nextToken(),e=n,t=this.parseExpression(),n=null):1===p.length&&null===p[0].init&&this.matchContextualKeyword("of")?(n=this.finalize(n,new a.VariableDeclaration(p,h)),this.nextToken(),e=n,t=this.parseAssignmentExpression(),n=null,u=!1):(this.consumeSemicolon(),n=this.finalize(n,new a.VariableDeclaration(p,h)))):(n=this.finalize(n,new a.Identifier(h)),this.nextToken(),e=n,t=this.parseExpression(),n=null)}else{var m=this.lookahead;if(d=this.context.allowIn,this.context.allowIn=!1,n=this.inheritCoverGrammar(this.parseAssignmentExpression),this.context.allowIn=d,this.matchKeyword("in"))this.context.isAssignmentTarget&&n.type!==l.Syntax.AssignmentExpression||this.tolerateError(i.Messages.InvalidLHSInForIn),this.nextToken(),this.reinterpretExpressionAsPattern(n),e=n,t=this.parseExpression(),n=null;else if(this.matchContextualKeyword("of"))this.context.isAssignmentTarget&&n.type!==l.Syntax.AssignmentExpression||this.tolerateError(i.Messages.InvalidLHSInForLoop),this.nextToken(),this.reinterpretExpressionAsPattern(n),e=n,t=this.parseAssignmentExpression(),n=null,u=!1;else{if(this.match(",")){for(var g=[n];this.match(",");)this.nextToken(),g.push(this.isolateCoverGrammar(this.parseAssignmentExpression));n=this.finalize(this.startNode(m),new a.SequenceExpression(g))}this.expect(";")}}if(void 0===e&&(this.match(";")||(o=this.parseExpression()),this.expect(";"),this.match(")")||(s=this.parseExpression())),!this.match(")")&&this.config.tolerant)this.tolerateUnexpectedToken(this.nextToken()),r=this.finalize(this.createNode(),new a.EmptyStatement);else{this.expect(")");var y=this.context.inIteration;this.context.inIteration=!0,r=this.isolateCoverGrammar(this.parseStatement),this.context.inIteration=y}return void 0===e?this.finalize(c,new a.ForStatement(n,o,s,r)):u?this.finalize(c,new a.ForInStatement(e,t,r)):this.finalize(c,new a.ForOfStatement(e,t,r))},e.prototype.parseContinueStatement=function(){var e=this.createNode();this.expectKeyword("continue");var t=null;if(3===this.lookahead.type&&!this.hasLineTerminator){var r=this.parseVariableIdentifier();t=r;var n="$"+r.name;Object.prototype.hasOwnProperty.call(this.context.labelSet,n)||this.throwError(i.Messages.UnknownLabel,r.name)}return this.consumeSemicolon(),null!==t||this.context.inIteration||this.throwError(i.Messages.IllegalContinue),this.finalize(e,new a.ContinueStatement(t))},e.prototype.parseBreakStatement=function(){var e=this.createNode();this.expectKeyword("break");var t=null;if(3===this.lookahead.type&&!this.hasLineTerminator){var r=this.parseVariableIdentifier(),n="$"+r.name;Object.prototype.hasOwnProperty.call(this.context.labelSet,n)||this.throwError(i.Messages.UnknownLabel,r.name),t=r}return this.consumeSemicolon(),null!==t||this.context.inIteration||this.context.inSwitch||this.throwError(i.Messages.IllegalBreak),this.finalize(e,new a.BreakStatement(t))},e.prototype.parseReturnStatement=function(){this.context.inFunctionBody||this.tolerateError(i.Messages.IllegalReturn);var e=this.createNode();this.expectKeyword("return");var t=(this.match(";")||this.match("}")||this.hasLineTerminator||2===this.lookahead.type)&&8!==this.lookahead.type&&10!==this.lookahead.type?null:this.parseExpression();return this.consumeSemicolon(),this.finalize(e,new a.ReturnStatement(t))},e.prototype.parseWithStatement=function(){this.context.strict&&this.tolerateError(i.Messages.StrictModeWith);var e,t=this.createNode();this.expectKeyword("with"),this.expect("(");var r=this.parseExpression();return!this.match(")")&&this.config.tolerant?(this.tolerateUnexpectedToken(this.nextToken()),e=this.finalize(this.createNode(),new a.EmptyStatement)):(this.expect(")"),e=this.parseStatement()),this.finalize(t,new a.WithStatement(r,e))},e.prototype.parseSwitchCase=function(){var e,t=this.createNode();this.matchKeyword("default")?(this.nextToken(),e=null):(this.expectKeyword("case"),e=this.parseExpression()),this.expect(":");for(var r=[];!(this.match("}")||this.matchKeyword("default")||this.matchKeyword("case"));)r.push(this.parseStatementListItem());return this.finalize(t,new a.SwitchCase(e,r))},e.prototype.parseSwitchStatement=function(){var e=this.createNode();this.expectKeyword("switch"),this.expect("(");var t=this.parseExpression();this.expect(")");var r=this.context.inSwitch;this.context.inSwitch=!0;var n=[],o=!1;for(this.expect("{");!this.match("}");){var s=this.parseSwitchCase();null===s.test&&(o&&this.throwError(i.Messages.MultipleDefaultsInSwitch),o=!0),n.push(s)}return this.expect("}"),this.context.inSwitch=r,this.finalize(e,new a.SwitchStatement(t,n))},e.prototype.parseLabelledStatement=function(){var e,t=this.createNode(),r=this.parseExpression();if(r.type===l.Syntax.Identifier&&this.match(":")){this.nextToken();var n=r,o="$"+n.name;Object.prototype.hasOwnProperty.call(this.context.labelSet,o)&&this.throwError(i.Messages.Redeclaration,"Label",n.name),this.context.labelSet[o]=!0;var s=void 0;if(this.matchKeyword("class"))this.tolerateUnexpectedToken(this.lookahead),s=this.parseClassDeclaration();else if(this.matchKeyword("function")){var u=this.lookahead,c=this.parseFunctionDeclaration();this.context.strict?this.tolerateUnexpectedToken(u,i.Messages.StrictFunction):c.generator&&this.tolerateUnexpectedToken(u,i.Messages.GeneratorInLegacyContext),s=c}else s=this.parseStatement();delete this.context.labelSet[o],e=new a.LabeledStatement(n,s)}else this.consumeSemicolon(),e=new a.ExpressionStatement(r);return this.finalize(t,e)},e.prototype.parseThrowStatement=function(){var e=this.createNode();this.expectKeyword("throw"),this.hasLineTerminator&&this.throwError(i.Messages.NewlineAfterThrow);var t=this.parseExpression();return this.consumeSemicolon(),this.finalize(e,new a.ThrowStatement(t))},e.prototype.parseCatchClause=function(){var e=this.createNode();this.expectKeyword("catch"),this.expect("("),this.match(")")&&this.throwUnexpectedToken(this.lookahead);for(var t=[],r=this.parsePattern(t),n={},o=0;o0&&this.tolerateError(i.Messages.BadGetterArity);var n=this.parsePropertyMethod(r);return this.context.allowYield=t,this.finalize(e,new a.FunctionExpression(null,r.params,n,!1))},e.prototype.parseSetterMethod=function(){var e=this.createNode(),t=this.context.allowYield;this.context.allowYield=!0;var r=this.parseFormalParameters();1!==r.params.length?this.tolerateError(i.Messages.BadSetterArity):r.params[0]instanceof a.RestElement&&this.tolerateError(i.Messages.BadSetterRestParameter);var n=this.parsePropertyMethod(r);return this.context.allowYield=t,this.finalize(e,new a.FunctionExpression(null,r.params,n,!1))},e.prototype.parseGeneratorMethod=function(){var e=this.createNode(),t=this.context.allowYield;this.context.allowYield=!0;var r=this.parseFormalParameters();this.context.allowYield=!1;var n=this.parsePropertyMethod(r);return this.context.allowYield=t,this.finalize(e,new a.FunctionExpression(null,r.params,n,!0))},e.prototype.isStartOfExpression=function(){var e=!0,t=this.lookahead.value;switch(this.lookahead.type){case 7:e="["===t||"("===t||"{"===t||"+"===t||"-"===t||"!"===t||"~"===t||"++"===t||"--"===t||"/"===t||"/="===t;break;case 4:e="class"===t||"delete"===t||"function"===t||"let"===t||"new"===t||"super"===t||"this"===t||"typeof"===t||"void"===t||"yield"===t}return e},e.prototype.parseYieldExpression=function(){var e=this.createNode();this.expectKeyword("yield");var t=null,r=!1;if(!this.hasLineTerminator){var n=this.context.allowYield;this.context.allowYield=!1,(r=this.match("*"))?(this.nextToken(),t=this.parseAssignmentExpression()):this.isStartOfExpression()&&(t=this.parseAssignmentExpression()),this.context.allowYield=n}return this.finalize(e,new a.YieldExpression(t,r))},e.prototype.parseClassElement=function(e){var t=this.lookahead,r=this.createNode(),n="",o=null,s=null,l=!1,u=!1,c=!1,d=!1;if(this.match("*"))this.nextToken();else if(l=this.match("["),"static"===(o=this.parseObjectPropertyKey()).name&&(this.qualifiedPropertyName(this.lookahead)||this.match("*"))&&(t=this.lookahead,c=!0,l=this.match("["),this.match("*")?this.nextToken():o=this.parseObjectPropertyKey()),3===t.type&&!this.hasLineTerminator&&"async"===t.value){var p=this.lookahead.value;":"!==p&&"("!==p&&"*"!==p&&(d=!0,t=this.lookahead,o=this.parseObjectPropertyKey(),3===t.type&&"constructor"===t.value&&this.tolerateUnexpectedToken(t,i.Messages.ConstructorIsAsync))}var f=this.qualifiedPropertyName(this.lookahead);return 3===t.type?"get"===t.value&&f?(n="get",l=this.match("["),o=this.parseObjectPropertyKey(),this.context.allowYield=!1,s=this.parseGetterMethod()):"set"===t.value&&f&&(n="set",l=this.match("["),o=this.parseObjectPropertyKey(),s=this.parseSetterMethod()):7===t.type&&"*"===t.value&&f&&(n="init",l=this.match("["),o=this.parseObjectPropertyKey(),s=this.parseGeneratorMethod(),u=!0),!n&&o&&this.match("(")&&(n="init",s=d?this.parsePropertyMethodAsyncFunction():this.parsePropertyMethodFunction(),u=!0),n||this.throwUnexpectedToken(this.lookahead),"init"===n&&(n="method"),l||(c&&this.isPropertyKey(o,"prototype")&&this.throwUnexpectedToken(t,i.Messages.StaticPrototype),!c&&this.isPropertyKey(o,"constructor")&&(("method"!==n||!u||s&&s.generator)&&this.throwUnexpectedToken(t,i.Messages.ConstructorSpecialMethod),e.value?this.throwUnexpectedToken(t,i.Messages.DuplicateConstructor):e.value=!0,n="constructor")),this.finalize(r,new a.MethodDefinition(o,l,s,n,c))},e.prototype.parseClassElementList=function(){var e=[],t={value:!1};for(this.expect("{");!this.match("}");)this.match(";")?this.nextToken():e.push(this.parseClassElement(t));return this.expect("}"),e},e.prototype.parseClassBody=function(){var e=this.createNode(),t=this.parseClassElementList();return this.finalize(e,new a.ClassBody(t))},e.prototype.parseClassDeclaration=function(e){var t=this.createNode(),r=this.context.strict;this.context.strict=!0,this.expectKeyword("class");var n=e&&3!==this.lookahead.type?null:this.parseVariableIdentifier(),o=null;this.matchKeyword("extends")&&(this.nextToken(),o=this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall));var i=this.parseClassBody();return this.context.strict=r,this.finalize(t,new a.ClassDeclaration(n,o,i))},e.prototype.parseClassExpression=function(){var e=this.createNode(),t=this.context.strict;this.context.strict=!0,this.expectKeyword("class");var r=3===this.lookahead.type?this.parseVariableIdentifier():null,n=null;this.matchKeyword("extends")&&(this.nextToken(),n=this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall));var o=this.parseClassBody();return this.context.strict=t,this.finalize(e,new a.ClassExpression(r,n,o))},e.prototype.parseModule=function(){this.context.strict=!0,this.context.isModule=!0,this.scanner.isModule=!0;for(var e=this.createNode(),t=this.parseDirectivePrologues();2!==this.lookahead.type;)t.push(this.parseStatementListItem());return this.finalize(e,new a.Module(t))},e.prototype.parseScript=function(){for(var e=this.createNode(),t=this.parseDirectivePrologues();2!==this.lookahead.type;)t.push(this.parseStatementListItem());return this.finalize(e,new a.Script(t))},e.prototype.parseModuleSpecifier=function(){var e=this.createNode();8!==this.lookahead.type&&this.throwError(i.Messages.InvalidModuleSpecifier);var t=this.nextToken(),r=this.getTokenRaw(t);return this.finalize(e,new a.Literal(t.value,r))},e.prototype.parseImportSpecifier=function(){var e,t,r=this.createNode();return 3===this.lookahead.type?(t=e=this.parseVariableIdentifier(),this.matchContextualKeyword("as")&&(this.nextToken(),t=this.parseVariableIdentifier())):(t=e=this.parseIdentifierName(),this.matchContextualKeyword("as")?(this.nextToken(),t=this.parseVariableIdentifier()):this.throwUnexpectedToken(this.nextToken())),this.finalize(r,new a.ImportSpecifier(t,e))},e.prototype.parseNamedImports=function(){this.expect("{");for(var e=[];!this.match("}");)e.push(this.parseImportSpecifier()),this.match("}")||this.expect(",");return this.expect("}"),e},e.prototype.parseImportDefaultSpecifier=function(){var e=this.createNode(),t=this.parseIdentifierName();return this.finalize(e,new a.ImportDefaultSpecifier(t))},e.prototype.parseImportNamespaceSpecifier=function(){var e=this.createNode();this.expect("*"),this.matchContextualKeyword("as")||this.throwError(i.Messages.NoAsAfterImportNamespace),this.nextToken();var t=this.parseIdentifierName();return this.finalize(e,new a.ImportNamespaceSpecifier(t))},e.prototype.parseImportDeclaration=function(){this.context.inFunctionBody&&this.throwError(i.Messages.IllegalImportDeclaration);var e,t=this.createNode();this.expectKeyword("import");var r=[];if(8===this.lookahead.type)e=this.parseModuleSpecifier();else{if(this.match("{")?r=r.concat(this.parseNamedImports()):this.match("*")?r.push(this.parseImportNamespaceSpecifier()):this.isIdentifierName(this.lookahead)&&!this.matchKeyword("default")?(r.push(this.parseImportDefaultSpecifier()),this.match(",")&&(this.nextToken(),this.match("*")?r.push(this.parseImportNamespaceSpecifier()):this.match("{")?r=r.concat(this.parseNamedImports()):this.throwUnexpectedToken(this.lookahead))):this.throwUnexpectedToken(this.nextToken()),!this.matchContextualKeyword("from")){var n=this.lookahead.value?i.Messages.UnexpectedToken:i.Messages.MissingFromClause;this.throwError(n,this.lookahead.value)}this.nextToken(),e=this.parseModuleSpecifier()}return this.consumeSemicolon(),this.finalize(t,new a.ImportDeclaration(r,e))},e.prototype.parseExportSpecifier=function(){var e=this.createNode(),t=this.parseIdentifierName(),r=t;return this.matchContextualKeyword("as")&&(this.nextToken(),r=this.parseIdentifierName()),this.finalize(e,new a.ExportSpecifier(t,r))},e.prototype.parseExportDeclaration=function(){this.context.inFunctionBody&&this.throwError(i.Messages.IllegalExportDeclaration);var e,t=this.createNode();if(this.expectKeyword("export"),this.matchKeyword("default"))if(this.nextToken(),this.matchKeyword("function")){var r=this.parseFunctionDeclaration(!0);e=this.finalize(t,new a.ExportDefaultDeclaration(r))}else this.matchKeyword("class")?(r=this.parseClassDeclaration(!0),e=this.finalize(t,new a.ExportDefaultDeclaration(r))):this.matchContextualKeyword("async")?(r=this.matchAsyncFunction()?this.parseFunctionDeclaration(!0):this.parseAssignmentExpression(),e=this.finalize(t,new a.ExportDefaultDeclaration(r))):(this.matchContextualKeyword("from")&&this.throwError(i.Messages.UnexpectedToken,this.lookahead.value),r=this.match("{")?this.parseObjectInitializer():this.match("[")?this.parseArrayInitializer():this.parseAssignmentExpression(),this.consumeSemicolon(),e=this.finalize(t,new a.ExportDefaultDeclaration(r)));else if(this.match("*")){if(this.nextToken(),!this.matchContextualKeyword("from")){var n=this.lookahead.value?i.Messages.UnexpectedToken:i.Messages.MissingFromClause;this.throwError(n,this.lookahead.value)}this.nextToken();var o=this.parseModuleSpecifier();this.consumeSemicolon(),e=this.finalize(t,new a.ExportAllDeclaration(o))}else if(4===this.lookahead.type){switch(r=void 0,this.lookahead.value){case"let":case"const":r=this.parseLexicalDeclaration({inFor:!1});break;case"var":case"class":case"function":r=this.parseStatementListItem();break;default:this.throwUnexpectedToken(this.lookahead)}e=this.finalize(t,new a.ExportNamedDeclaration(r,[],null))}else if(this.matchAsyncFunction())r=this.parseFunctionDeclaration(),e=this.finalize(t,new a.ExportNamedDeclaration(r,[],null));else{var s=[],l=null,u=!1;for(this.expect("{");!this.match("}");)u=u||this.matchKeyword("default"),s.push(this.parseExportSpecifier()),this.match("}")||this.expect(",");this.expect("}"),this.matchContextualKeyword("from")?(this.nextToken(),l=this.parseModuleSpecifier(),this.consumeSemicolon()):u?(n=this.lookahead.value?i.Messages.UnexpectedToken:i.Messages.MissingFromClause,this.throwError(n,this.lookahead.value)):this.consumeSemicolon(),e=this.finalize(t,new a.ExportNamedDeclaration(null,s,l))}return e},e}();t.Parser=c},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assert=function(e,t){if(!e)throw new Error("ASSERT: "+t)}},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(){this.errors=[],this.tolerant=!1}return e.prototype.recordError=function(e){this.errors.push(e)},e.prototype.tolerate=function(e){if(!this.tolerant)throw e;this.recordError(e)},e.prototype.constructError=function(e,t){var r=new Error(e);try{throw r}catch(e){Object.create&&Object.defineProperty&&(r=Object.create(e),Object.defineProperty(r,"column",{value:t}))}return r},e.prototype.createError=function(e,t,r,n){var o="Line "+t+": "+n,i=this.constructError(o,r);return i.index=e,i.lineNumber=t,i.description=n,i},e.prototype.throwError=function(e,t,r,n){throw this.createError(e,t,r,n)},e.prototype.tolerateError=function(e,t,r,n){var o=this.createError(e,t,r,n);if(!this.tolerant)throw o;this.recordError(o)},e}();t.ErrorHandler=r},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Messages={BadGetterArity:"Getter must not have any formal parameters",BadSetterArity:"Setter must have exactly one formal parameter",BadSetterRestParameter:"Setter function argument must not be a rest parameter",ConstructorIsAsync:"Class constructor may not be an async method",ConstructorSpecialMethod:"Class constructor may not be an accessor",DeclarationMissingInitializer:"Missing initializer in %0 declaration",DefaultRestParameter:"Unexpected token =",DuplicateBinding:"Duplicate binding %0",DuplicateConstructor:"A class may only have one constructor",DuplicateProtoProperty:"Duplicate __proto__ fields are not allowed in object literals",ForInOfLoopInitializer:"%0 loop variable declaration may not have an initializer",GeneratorInLegacyContext:"Generator declarations are not allowed in legacy contexts",IllegalBreak:"Illegal break statement",IllegalContinue:"Illegal continue statement",IllegalExportDeclaration:"Unexpected token",IllegalImportDeclaration:"Unexpected token",IllegalLanguageModeDirective:"Illegal 'use strict' directive in function with non-simple parameter list",IllegalReturn:"Illegal return statement",InvalidEscapedReservedWord:"Keyword must not contain escaped characters",InvalidHexEscapeSequence:"Invalid hexadecimal escape sequence",InvalidLHSInAssignment:"Invalid left-hand side in assignment",InvalidLHSInForIn:"Invalid left-hand side in for-in",InvalidLHSInForLoop:"Invalid left-hand side in for-loop",InvalidModuleSpecifier:"Unexpected token",InvalidRegExp:"Invalid regular expression",LetInLexicalBinding:"let is disallowed as a lexically bound name",MissingFromClause:"Unexpected token",MultipleDefaultsInSwitch:"More than one default clause in switch statement",NewlineAfterThrow:"Illegal newline after throw",NoAsAfterImportNamespace:"Unexpected token",NoCatchOrFinally:"Missing catch or finally after try",ParameterAfterRestParameter:"Rest parameter must be last formal parameter",Redeclaration:"%0 '%1' has already been declared",StaticPrototype:"Classes may not have static property named prototype",StrictCatchVariable:"Catch variable may not be eval or arguments in strict mode",StrictDelete:"Delete of an unqualified identifier in strict mode.",StrictFunction:"In strict mode code, functions can only be declared at top level or inside a block",StrictFunctionName:"Function name may not be eval or arguments in strict mode",StrictLHSAssignment:"Assignment to eval or arguments is not allowed in strict mode",StrictLHSPostfix:"Postfix increment/decrement may not have eval or arguments operand in strict mode",StrictLHSPrefix:"Prefix increment/decrement may not have eval or arguments operand in strict mode",StrictModeWith:"Strict mode code may not include a with statement",StrictOctalLiteral:"Octal literals are not allowed in strict mode.",StrictParamDupe:"Strict mode function may not have duplicate parameter names",StrictParamName:"Parameter name eval or arguments is not allowed in strict mode",StrictReservedWord:"Use of future reserved word in strict mode",StrictVarName:"Variable name may not be eval or arguments in strict mode",TemplateOctalLiteral:"Octal literals are not allowed in template strings.",UnexpectedEOS:"Unexpected end of input",UnexpectedIdentifier:"Unexpected identifier",UnexpectedNumber:"Unexpected number",UnexpectedReserved:"Unexpected reserved word",UnexpectedString:"Unexpected string",UnexpectedTemplate:"Unexpected quasi %0",UnexpectedToken:"Unexpected token %0",UnexpectedTokenIllegal:"Unexpected token ILLEGAL",UnknownLabel:"Undefined label '%0'",UnterminatedRegExp:"Invalid regular expression: missing /"}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(9),o=r(4),i=r(11);function a(e){return"0123456789abcdef".indexOf(e.toLowerCase())}function s(e){return"01234567".indexOf(e)}var l=function(){function e(e,t){this.source=e,this.errorHandler=t,this.trackComment=!1,this.isModule=!1,this.length=e.length,this.index=0,this.lineNumber=e.length>0?1:0,this.lineStart=0,this.curlyStack=[]}return e.prototype.saveState=function(){return{index:this.index,lineNumber:this.lineNumber,lineStart:this.lineStart}},e.prototype.restoreState=function(e){this.index=e.index,this.lineNumber=e.lineNumber,this.lineStart=e.lineStart},e.prototype.eof=function(){return this.index>=this.length},e.prototype.throwUnexpectedToken=function(e){return void 0===e&&(e=i.Messages.UnexpectedTokenIllegal),this.errorHandler.throwError(this.index,this.lineNumber,this.index-this.lineStart+1,e)},e.prototype.tolerateUnexpectedToken=function(e){void 0===e&&(e=i.Messages.UnexpectedTokenIllegal),this.errorHandler.tolerateError(this.index,this.lineNumber,this.index-this.lineStart+1,e)},e.prototype.skipSingleLineComment=function(e){var t,r,n=[];for(this.trackComment&&(n=[],t=this.index-e,r={start:{line:this.lineNumber,column:this.index-this.lineStart-e},end:{}});!this.eof();){var i=this.source.charCodeAt(this.index);if(++this.index,o.Character.isLineTerminator(i)){if(this.trackComment){r.end={line:this.lineNumber,column:this.index-this.lineStart-1};var a={multiLine:!1,slice:[t+e,this.index-1],range:[t,this.index-1],loc:r};n.push(a)}return 13===i&&10===this.source.charCodeAt(this.index)&&++this.index,++this.lineNumber,this.lineStart=this.index,n}}return this.trackComment&&(r.end={line:this.lineNumber,column:this.index-this.lineStart},a={multiLine:!1,slice:[t+e,this.index],range:[t,this.index],loc:r},n.push(a)),n},e.prototype.skipMultiLineComment=function(){var e,t,r=[];for(this.trackComment&&(r=[],e=this.index-2,t={start:{line:this.lineNumber,column:this.index-this.lineStart-2},end:{}});!this.eof();){var n=this.source.charCodeAt(this.index);if(o.Character.isLineTerminator(n))13===n&&10===this.source.charCodeAt(this.index+1)&&++this.index,++this.lineNumber,++this.index,this.lineStart=this.index;else if(42===n){if(47===this.source.charCodeAt(this.index+1)){if(this.index+=2,this.trackComment){t.end={line:this.lineNumber,column:this.index-this.lineStart};var i={multiLine:!0,slice:[e+2,this.index-2],range:[e,this.index],loc:t};r.push(i)}return r}++this.index}else++this.index}return this.trackComment&&(t.end={line:this.lineNumber,column:this.index-this.lineStart},i={multiLine:!0,slice:[e+2,this.index],range:[e,this.index],loc:t},r.push(i)),this.tolerateUnexpectedToken(),r},e.prototype.scanComments=function(){var e;this.trackComment&&(e=[]);for(var t=0===this.index;!this.eof();){var r=this.source.charCodeAt(this.index);if(o.Character.isWhiteSpace(r))++this.index;else if(o.Character.isLineTerminator(r))++this.index,13===r&&10===this.source.charCodeAt(this.index)&&++this.index,++this.lineNumber,this.lineStart=this.index,t=!0;else if(47===r)if(47===(r=this.source.charCodeAt(this.index+1))){this.index+=2;var n=this.skipSingleLineComment(2);this.trackComment&&(e=e.concat(n)),t=!0}else{if(42!==r)break;this.index+=2,n=this.skipMultiLineComment(),this.trackComment&&(e=e.concat(n))}else if(t&&45===r){if(45!==this.source.charCodeAt(this.index+1)||62!==this.source.charCodeAt(this.index+2))break;this.index+=3,n=this.skipSingleLineComment(3),this.trackComment&&(e=e.concat(n))}else{if(60!==r||this.isModule)break;if("!--"!==this.source.slice(this.index+1,this.index+4))break;this.index+=4,n=this.skipSingleLineComment(4),this.trackComment&&(e=e.concat(n))}}return e},e.prototype.isFutureReservedWord=function(e){switch(e){case"enum":case"export":case"import":case"super":return!0;default:return!1}},e.prototype.isStrictModeReservedWord=function(e){switch(e){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"yield":case"let":return!0;default:return!1}},e.prototype.isRestrictedWord=function(e){return"eval"===e||"arguments"===e},e.prototype.isKeyword=function(e){switch(e.length){case 2:return"if"===e||"in"===e||"do"===e;case 3:return"var"===e||"for"===e||"new"===e||"try"===e||"let"===e;case 4:return"this"===e||"else"===e||"case"===e||"void"===e||"with"===e||"enum"===e;case 5:return"while"===e||"break"===e||"catch"===e||"throw"===e||"const"===e||"yield"===e||"class"===e||"super"===e;case 6:return"return"===e||"typeof"===e||"delete"===e||"switch"===e||"export"===e||"import"===e;case 7:return"default"===e||"finally"===e||"extends"===e;case 8:return"function"===e||"continue"===e||"debugger"===e;case 10:return"instanceof"===e;default:return!1}},e.prototype.codePointAt=function(e){var t=this.source.charCodeAt(e);if(t>=55296&&t<=56319){var r=this.source.charCodeAt(e+1);r>=56320&&r<=57343&&(t=1024*(t-55296)+r-56320+65536)}return t},e.prototype.scanHexEscape=function(e){for(var t="u"===e?4:2,r=0,n=0;n1114111||"}"!==e)&&this.throwUnexpectedToken(),o.Character.fromCodePoint(t)},e.prototype.getIdentifier=function(){for(var e=this.index++;!this.eof();){var t=this.source.charCodeAt(this.index);if(92===t)return this.index=e,this.getComplexIdentifier();if(t>=55296&&t<57343)return this.index=e,this.getComplexIdentifier();if(!o.Character.isIdentifierPart(t))break;++this.index}return this.source.slice(e,this.index)},e.prototype.getComplexIdentifier=function(){var e,t=this.codePointAt(this.index),r=o.Character.fromCodePoint(t);for(this.index+=r.length,92===t&&(117!==this.source.charCodeAt(this.index)&&this.throwUnexpectedToken(),++this.index,"{"===this.source[this.index]?(++this.index,e=this.scanUnicodeCodePointEscape()):null!==(e=this.scanHexEscape("u"))&&"\\"!==e&&o.Character.isIdentifierStart(e.charCodeAt(0))||this.throwUnexpectedToken(),r=e);!this.eof()&&(t=this.codePointAt(this.index),o.Character.isIdentifierPart(t));)r+=e=o.Character.fromCodePoint(t),this.index+=e.length,92===t&&(r=r.substr(0,r.length-1),117!==this.source.charCodeAt(this.index)&&this.throwUnexpectedToken(),++this.index,"{"===this.source[this.index]?(++this.index,e=this.scanUnicodeCodePointEscape()):null!==(e=this.scanHexEscape("u"))&&"\\"!==e&&o.Character.isIdentifierPart(e.charCodeAt(0))||this.throwUnexpectedToken(),r+=e);return r},e.prototype.octalToDecimal=function(e){var t="0"!==e,r=s(e);return!this.eof()&&o.Character.isOctalDigit(this.source.charCodeAt(this.index))&&(t=!0,r=8*r+s(this.source[this.index++]),"0123".indexOf(e)>=0&&!this.eof()&&o.Character.isOctalDigit(this.source.charCodeAt(this.index))&&(r=8*r+s(this.source[this.index++]))),{code:r,octal:t}},e.prototype.scanIdentifier=function(){var e,t=this.index,r=92===this.source.charCodeAt(t)?this.getComplexIdentifier():this.getIdentifier();if(3!=(e=1===r.length?3:this.isKeyword(r)?4:"null"===r?5:"true"===r||"false"===r?1:3)&&t+r.length!==this.index){var n=this.index;this.index=t,this.tolerateUnexpectedToken(i.Messages.InvalidEscapedReservedWord),this.index=n}return{type:e,value:r,lineNumber:this.lineNumber,lineStart:this.lineStart,start:t,end:this.index}},e.prototype.scanPunctuator=function(){var e=this.index,t=this.source[this.index];switch(t){case"(":case"{":"{"===t&&this.curlyStack.push("{"),++this.index;break;case".":++this.index,"."===this.source[this.index]&&"."===this.source[this.index+1]&&(this.index+=2,t="...");break;case"}":++this.index,this.curlyStack.pop();break;case")":case";":case",":case"[":case"]":case":":case"?":case"~":++this.index;break;default:">>>="===(t=this.source.substr(this.index,4))?this.index+=4:"==="===(t=t.substr(0,3))||"!=="===t||">>>"===t||"<<="===t||">>="===t||"**="===t?this.index+=3:"&&"===(t=t.substr(0,2))||"||"===t||"=="===t||"!="===t||"+="===t||"-="===t||"*="===t||"/="===t||"++"===t||"--"===t||"<<"===t||">>"===t||"&="===t||"|="===t||"^="===t||"%="===t||"<="===t||">="===t||"=>"===t||"**"===t?this.index+=2:(t=this.source[this.index],"<>=!+-*%&|^/".indexOf(t)>=0&&++this.index)}return this.index===e&&this.throwUnexpectedToken(),{type:7,value:t,lineNumber:this.lineNumber,lineStart:this.lineStart,start:e,end:this.index}},e.prototype.scanHexLiteral=function(e){for(var t="";!this.eof()&&o.Character.isHexDigit(this.source.charCodeAt(this.index));)t+=this.source[this.index++];return 0===t.length&&this.throwUnexpectedToken(),o.Character.isIdentifierStart(this.source.charCodeAt(this.index))&&this.throwUnexpectedToken(),{type:6,value:parseInt("0x"+t,16),lineNumber:this.lineNumber,lineStart:this.lineStart,start:e,end:this.index}},e.prototype.scanBinaryLiteral=function(e){for(var t,r="";!this.eof()&&("0"===(t=this.source[this.index])||"1"===t);)r+=this.source[this.index++];return 0===r.length&&this.throwUnexpectedToken(),this.eof()||(t=this.source.charCodeAt(this.index),(o.Character.isIdentifierStart(t)||o.Character.isDecimalDigit(t))&&this.throwUnexpectedToken()),{type:6,value:parseInt(r,2),lineNumber:this.lineNumber,lineStart:this.lineStart,start:e,end:this.index}},e.prototype.scanOctalLiteral=function(e,t){var r="",n=!1;for(o.Character.isOctalDigit(e.charCodeAt(0))?(n=!0,r="0"+this.source[this.index++]):++this.index;!this.eof()&&o.Character.isOctalDigit(this.source.charCodeAt(this.index));)r+=this.source[this.index++];return n||0!==r.length||this.throwUnexpectedToken(),(o.Character.isIdentifierStart(this.source.charCodeAt(this.index))||o.Character.isDecimalDigit(this.source.charCodeAt(this.index)))&&this.throwUnexpectedToken(),{type:6,value:parseInt(r,8),octal:n,lineNumber:this.lineNumber,lineStart:this.lineStart,start:t,end:this.index}},e.prototype.isImplicitOctalLiteral=function(){for(var e=this.index+1;e=0&&(r=r.replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g,function(e,t,r){var o=parseInt(t||r,16);return o>1114111&&n.throwUnexpectedToken(i.Messages.InvalidRegExp),o<=65535?String.fromCharCode(o):"￿"}).replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"￿"));try{RegExp(r)}catch(e){this.throwUnexpectedToken(i.Messages.InvalidRegExp)}try{return new RegExp(e,t)}catch(e){return null}},e.prototype.scanRegExpBody=function(){var e=this.source[this.index];n.assert("/"===e,"Regular expression literal must start with a slash");for(var t=this.source[this.index++],r=!1,a=!1;!this.eof();)if(t+=e=this.source[this.index++],"\\"===e)e=this.source[this.index++],o.Character.isLineTerminator(e.charCodeAt(0))&&this.throwUnexpectedToken(i.Messages.UnterminatedRegExp),t+=e;else if(o.Character.isLineTerminator(e.charCodeAt(0)))this.throwUnexpectedToken(i.Messages.UnterminatedRegExp);else if(r)"]"===e&&(r=!1);else{if("/"===e){a=!0;break}"["===e&&(r=!0)}return a||this.throwUnexpectedToken(i.Messages.UnterminatedRegExp),t.substr(1,t.length-2)},e.prototype.scanRegExpFlags=function(){for(var e="";!this.eof();){var t=this.source[this.index];if(!o.Character.isIdentifierPart(t.charCodeAt(0)))break;if(++this.index,"\\"!==t||this.eof())e+=t;else if("u"===(t=this.source[this.index])){++this.index;var r=this.index,n=this.scanHexEscape("u");if(null!==n)for(e+=n;r=55296&&e<57343&&o.Character.isIdentifierStart(this.codePointAt(this.index))?this.scanIdentifier():this.scanPunctuator()},e}();t.Scanner=l},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TokenName={},t.TokenName[1]="Boolean",t.TokenName[2]="",t.TokenName[3]="Identifier",t.TokenName[4]="Keyword",t.TokenName[5]="Null",t.TokenName[6]="Numeric",t.TokenName[7]="Punctuator",t.TokenName[8]="String",t.TokenName[9]="RegularExpression",t.TokenName[10]="Template"},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.XHTMLEntities={quot:'"',amp:"&",apos:"'",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪",int:"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦",lang:"⟨",rang:"⟩"}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(10),o=r(12),i=r(13),a=function(){function e(){this.values=[],this.curly=this.paren=-1}return e.prototype.beforeFunctionExpression=function(e){return["(","{","[","in","typeof","instanceof","new","return","case","delete","throw","void","=","+=","-=","*=","**=","/=","%=","<<=",">>=",">>>=","&=","|=","^=",",","+","-","*","**","/","%","++","--","<<",">>",">>>","&","|","^","!","~","&&","||","?",":","===","==",">=","<=","<",">","!=","!=="].indexOf(e)>=0},e.prototype.isRegexStart=function(){var e=this.values[this.values.length-1],t=null!==e;switch(e){case"this":case"]":t=!1;break;case")":var r=this.values[this.paren-1];t="if"===r||"while"===r||"for"===r||"with"===r;break;case"}":if(t=!1,"function"===this.values[this.curly-3])t=!!(n=this.values[this.curly-4])&&!this.beforeFunctionExpression(n);else if("function"===this.values[this.curly-4]){var n;t=!(n=this.values[this.curly-5])||!this.beforeFunctionExpression(n)}}return t},e.prototype.push=function(e){7===e.type||4===e.type?("{"===e.value?this.curly=this.values.length:"("===e.value&&(this.paren=this.values.length),this.values.push(e.value)):this.values.push(null)},e}(),s=function(){function e(e,t){this.errorHandler=new n.ErrorHandler,this.errorHandler.tolerant=!!t&&"boolean"==typeof t.tolerant&&t.tolerant,this.scanner=new o.Scanner(e,this.errorHandler),this.scanner.trackComment=!!t&&"boolean"==typeof t.comment&&t.comment,this.trackRange=!!t&&"boolean"==typeof t.range&&t.range,this.trackLoc=!!t&&"boolean"==typeof t.loc&&t.loc,this.buffer=[],this.reader=new a}return e.prototype.errors=function(){return this.errorHandler.errors},e.prototype.getNextToken=function(){if(0===this.buffer.length){var e=this.scanner.scanComments();if(this.scanner.trackComment)for(var t=0;t-1&&r>=e.flowLevel;switch(function(e,t,r,n,o){var i,a,s,l,u=!1,c=!1,d=-1!==n,p=-1,f=g(l=e.charCodeAt(0))&&65279!==l&&!m(l)&&45!==l&&63!==l&&58!==l&&44!==l&&91!==l&&93!==l&&123!==l&&125!==l&&35!==l&&38!==l&&42!==l&&33!==l&&124!==l&&61!==l&&62!==l&&39!==l&&34!==l&&37!==l&&64!==l&&96!==l&&!m(e.charCodeAt(e.length-1));if(t)for(i=0;i0?e.charCodeAt(i-1):null,f=f&&y(a,s)}else{for(i=0;in&&" "!==e[p+1],p=i);else if(!g(a))return 5;s=i>0?e.charCodeAt(i-1):null,f=f&&y(a,s)}c=c||d&&i-p-1>n&&" "!==e[p+1]}return u||c?r>9&&v(e)?5:c?4:3:f&&!o(e)?1:2}(t,s,e.indent,a,function(t){return function(e,t){var r,n;for(r=0,n=e.implicitTypes.length;r"+x(t,e.indent)+_(f(function(e,t){for(var r,n,o,i=/(\n+)([^\n]*)/g,a=(o=-1!==(o=e.indexOf("\n"))?o:e.length,i.lastIndex=o,S(e.slice(0,o),t)),s="\n"===e[0]||" "===e[0];n=i.exec(e);){var l=n[1],u=n[2];r=" "===u[0],a+=l+(s||r||""===u?"":"\n")+S(u,t),s=r}return a}(t,a),i));case 5:return'"'+function(e){for(var t,r,n,o="",i=0;i=55296&&t<=56319&&(r=e.charCodeAt(i+1))>=56320&&r<=57343?(o+=d(1024*(t-55296)+r-56320+65536),i++):o+=!(n=u[t])&&g(t)?e[i]:n||d(t);return o}(t)+'"';default:throw new o("impossible error: invalid scalar style")}}()}function x(e,t){var r=v(e)?String(t):"",n="\n"===e[e.length-1];return r+(!n||"\n"!==e[e.length-2]&&"\n"!==e?n?"":"-":"+")+"\n"}function _(e){return"\n"===e[e.length-1]?e.slice(0,-1):e}function S(e,t){if(""===e||" "===e[0])return e;for(var r,n,o=/ [^ ]/g,i=0,a=0,s=0,l="";r=o.exec(e);)(s=r.index)-i>t&&(n=a>i?a:s,l+="\n"+e.slice(i,n),i=n+1),a=s;return l+="\n",e.length-i>t&&a>i?l+=e.slice(i,a)+"\n"+e.slice(a+1):l+=e.slice(i),l.slice(1)}function C(e,t,r){var n,i,a,u,c,d;for(a=0,u=(i=r?e.explicitTypes:e.implicitTypes).length;a tag resolver accepts not "'+d+'" style');n=c.represent[d](t,d)}e.dump=n}return!0}return!1}function T(e,t,r,n,i,a){e.tag=null,e.dump=r,C(e,r,!1)||C(e,r,!0);var l=s.call(e.dump);n&&(n=e.flowLevel<0||e.flowLevel>t);var u,c,d="[object Object]"===l||"[object Array]"===l;if(d&&(c=-1!==(u=e.duplicates.indexOf(r))),(null!==e.tag&&"?"!==e.tag||c||2!==e.indent&&t>0)&&(i=!1),c&&e.usedDuplicates[u])e.dump="*ref_"+u;else{if(d&&c&&!e.usedDuplicates[u]&&(e.usedDuplicates[u]=!0),"[object Object]"===l)n&&0!==Object.keys(e.dump).length?(function(e,t,r,n){var i,a,s,l,u,c,d="",p=e.tag,f=Object.keys(r);if(!0===e.sortKeys)f.sort();else if("function"==typeof e.sortKeys)f.sort(e.sortKeys);else if(e.sortKeys)throw new o("sortKeys must be a boolean or a function");for(i=0,a=f.length;i1024)&&(e.dump&&10===e.dump.charCodeAt(0)?c+="?":c+="? "),c+=e.dump,u&&(c+=h(e,t)),T(e,t+1,l,!0,u)&&(e.dump&&10===e.dump.charCodeAt(0)?c+=":":c+=": ",d+=c+=e.dump));e.tag=p,e.dump=d||"{}"}(e,t,e.dump,i),c&&(e.dump="&ref_"+u+e.dump)):(function(e,t,r){var n,o,i,a,s,l="",u=e.tag,c=Object.keys(r);for(n=0,o=c.length;n1024&&(s+="? "),s+=e.dump+(e.condenseFlow?'"':"")+":"+(e.condenseFlow?"":" "),T(e,t,a,!1,!1)&&(l+=s+=e.dump));e.tag=u,e.dump="{"+l+"}"}(e,t,e.dump),c&&(e.dump="&ref_"+u+" "+e.dump));else if("[object Array]"===l){var p=e.noArrayIndent&&t>0?t-1:t;n&&0!==e.dump.length?(function(e,t,r,n){var o,i,a="",s=e.tag;for(o=0,i=r.length;o "+e.dump)}return!0}function w(e,t){var r=new p(t=t||{});return r.noRefs||function(e,t){var r,n,o=[],i=[];for(function e(t,r,n){var o,i,a;if(null!==t&&"object"==typeof t)if(-1!==(i=r.indexOf(t)))-1===n.indexOf(i)&&n.push(i);else if(r.push(t),Array.isArray(t))for(i=0,a=t.length;i=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a};Object.defineProperty(t,"__esModule",{value:!0});var s=r(91),l=r(1),u=r(183),c=r(0),d=r(7),p=r(95),f=r(69),h=r(3),m=r(305),g=r(306),y=r(307),v=function(e){function t(t,r){void 0===r&&(r=!1);var n=e.call(this)||this;return n._hasDeclaration=!1,n._docTypeName="",n._hasDocumentElement=!1,n._currentElementSerialized=!1,n._openTags=[],n._ended=!1,n._fragment=r,n._options=l.applyDefaults(t||{},s.DefaultXMLBuilderCBOptions),n._builderOptions={defaultNamespace:n._options.defaultNamespace,namespaceAlias:n._options.namespaceAlias},"json"===n._options.format?n._writer=new g.JSONCBWriter(n._options):"yaml"===n._options.format?n._writer=new y.YAMLCBWriter(n._options):n._writer=new m.XMLCBWriter(n._options),void 0!==n._options.data&&n.on("data",n._options.data),void 0!==n._options.end&&n.on("end",n._options.end),void 0!==n._options.error&&n.on("error",n._options.error),n._prefixMap=new p.NamespacePrefixMap,n._prefixMap.set("xml",d.namespace.XML),n._prefixIndex={value:1},n._push(n._writer.frontMatter()),n}return o(t,e),t.prototype.ele=function(e,t,r){var n,o;if(l.isObject(e)||l.isString(e)&&(/^\s*/g,">");return this._push(this._writer.text(r)),this},t.prototype.ins=function(e,t){var r;void 0===t&&(t=""),this._serializeOpenTag(!0);try{r=u.fragment(this._builderOptions).ins(e,t).first().node}catch(e){return this.emit("error",e),this}return this._options.wellFormed&&(-1!==r.target.indexOf(":")||/^xml$/i.test(r.target))?(this.emit("error",new Error("Processing instruction target contains invalid characters (well-formed required).")),this):this._options.wellFormed&&!c.xml_isLegalChar(r.data)?(this.emit("error",Error("Processing instruction data contains invalid characters (well-formed required).")),this):(this._push(this._writer.instruction(r.target,r.data)),this)},t.prototype.dat=function(e){var t;this._serializeOpenTag(!0);try{t=u.fragment(this._builderOptions).dat(e).first().node}catch(e){return this.emit("error",e),this}return this._push(this._writer.cdata(t.data)),this},t.prototype.dec=function(e){return void 0===e&&(e={version:"1.0"}),this._fragment?(this.emit("error",Error("Cannot insert an XML declaration into a document fragment.")),this):this._hasDeclaration?(this.emit("error",Error("XML declaration is already inserted.")),this):(this._push(this._writer.declaration(e.version||"1.0",e.encoding,e.standalone)),this._hasDeclaration=!0,this)},t.prototype.dtd=function(e){if(this._fragment)return this.emit("error",Error("Cannot insert a DocType declaration into a document fragment.")),this;if(""!==this._docTypeName)return this.emit("error",new Error("DocType declaration is already inserted.")),this;if(this._hasDocumentElement)return this.emit("error",new Error("Cannot insert DocType declaration after document element.")),this;var t;try{t=u.create().dtd(e).first().node}catch(e){return this.emit("error",e),this}return this._options.wellFormed&&!c.xml_isPubidChar(t.publicId)?(this.emit("error",new Error("DocType public identifier does not match PubidChar construct (well-formed required).")),this):this._options.wellFormed&&(!c.xml_isLegalChar(t.systemId)||-1!==t.systemId.indexOf('"')&&-1!==t.systemId.indexOf("'"))?(this.emit("error",new Error("DocType system identifier contains invalid characters (well-formed required).")),this):(this._docTypeName=e.name,this._push(this._writer.docType(e.name,t.publicId,t.systemId)),this)},t.prototype.import=function(e){var t,r,n=u.fragment().set(this._options);try{n.import(e)}catch(e){return this.emit("error",e),this}try{for(var o=i(n.node.childNodes),a=o.next();!a.done;a=o.next()){var s=a.value;this._fromNode(s)}}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}return this},t.prototype.up=function(){return this._serializeOpenTag(!1),this._serializeCloseTag(),this},t.prototype.end=function(){for(this._serializeOpenTag(!1);this._openTags.length>0;)this._serializeCloseTag();return this._push(null),this},t.prototype._serializeOpenTag=function(e){if(!this._currentElementSerialized&&void 0!==this._currentElement){var r=this._currentElement.node;if(!this._options.wellFormed||-1===r.localName.indexOf(":")&&c.xml_isName(r.localName)){var n="",o=!1,i=this._prefixMap.copy(),a={},s=this._recordNamespaceInformation(r,i,a),l=0===this._openTags.length?null:this._openTags[this._openTags.length-1][1],u=r.namespaceURI;if(null===u&&(u=l),l===u)null!==s&&(o=!0),n=u===d.namespace.XML?"xml:"+r.localName:r.localName,this._writer.beginElement(n),this._push(this._writer.openTagBegin(n));else{var p=r.prefix,f=null;if(null===p&&u===s||(f=i.get(p,u)),"xmlns"===p){if(this._options.wellFormed)return void this.emit("error",new Error("An element cannot have the 'xmlns' prefix (well-formed required)."));f=p}null!==f?(n=f+":"+r.localName,null!==s&&s!==d.namespace.XML&&(l=s||null),this._writer.beginElement(n),this._push(this._writer.openTagBegin(n))):null!==p?(p in a&&(p=this._generatePrefix(u,i,this._prefixIndex)),i.set(p,u),n+=p+":"+r.localName,this._writer.beginElement(n),this._push(this._writer.openTagBegin(n)),this._push(this._writer.attribute("xmlns:"+p,this._serializeAttributeValue(u,this._options.wellFormed))),null!==s&&(l=s||null)):null===s||null!==s&&s!==u?(o=!0,n+=r.localName,l=u,this._writer.beginElement(n),this._push(this._writer.openTagBegin(n)),this._push(this._writer.attribute("xmlns",this._serializeAttributeValue(u,this._options.wellFormed)))):(n+=r.localName,l=u,this._writer.beginElement(n),this._push(this._writer.openTagBegin(n)))}this._serializeAttributes(r,i,this._prefixIndex,a,o,this._options.wellFormed);var h=u===d.namespace.HTML;h&&!e&&t._VoidElementNames.has(r.localName)?(this._push(this._writer.openTagEnd(n,!0,!0)),this._writer.endElement(n)):h||e?this._push(this._writer.openTagEnd(n,!1,!1)):(this._push(this._writer.openTagEnd(n,!0,!1)),this._writer.endElement(n)),this._currentElementSerialized=!0,this._openTags.push([n,l,this._prefixMap,e]),this._isPrefixMapModified(this._prefixMap,i)&&(this._prefixMap=i),this._writer.level++}else this.emit("error",new Error("Node local name contains invalid characters (well-formed required)."))}},t.prototype._serializeCloseTag=function(){this._writer.level--;var e=this._openTags.pop();if(void 0!==e){var t=a(e,4),r=t[0],n=(t[1],t[2]),o=t[3];this._prefixMap=n,o&&(this._push(this._writer.closeTag(r)),this._writer.endElement(r))}else this.emit("error",new Error("Last element is undefined."))},t.prototype._push=function(e){null===e?(this._ended=!0,this.emit("end")):this._ended?this.emit("error",new Error("Cannot push to ended stream.")):0!==e.length&&(this._writer.hasData=!0,this.emit("data",e,this._writer.level))},t.prototype._fromNode=function(e){var t,r,n,o;if(h.Guard.isElementNode(e)){var a=e.prefix?e.prefix+":"+e.localName:e.localName;null!==e.namespaceURI?this.ele(e.namespaceURI,a):this.ele(a);try{for(var s=i(e.attributes),l=s.next();!l.done;l=s.next()){var u=l.value,c=u.prefix?u.prefix+":"+u.localName:u.localName;null!==u.namespaceURI?this.att(u.namespaceURI,c,u.value):this.att(c,u.value)}}catch(e){t={error:e}}finally{try{l&&!l.done&&(r=s.return)&&r.call(s)}finally{if(t)throw t.error}}try{for(var d=i(e.childNodes),p=d.next();!p.done;p=d.next()){var f=p.value;this._fromNode(f)}}catch(e){n={error:e}}finally{try{p&&!p.done&&(o=d.return)&&o.call(d)}finally{if(n)throw n.error}}this.up()}else h.Guard.isExclusiveTextNode(e)&&e.data?this.txt(e.data):h.Guard.isCommentNode(e)?this.com(e.data):h.Guard.isCDATASectionNode(e)?this.dat(e.data):h.Guard.isProcessingInstructionNode(e)&&this.ins(e.target,e.data)},t.prototype._serializeAttributes=function(e,t,r,n,o,a){var s,l,u=a?new f.LocalNameSet:void 0;try{for(var p=i(e.attributes),h=p.next();!h.done;h=p.next()){var m=h.value;if(a||o||null!==m.namespaceURI){if(a&&u&&u.has(m.namespaceURI,m.localName))return void this.emit("error",new Error("Element contains duplicate attributes (well-formed required)."));a&&u&&u.set(m.namespaceURI,m.localName);var g=m.namespaceURI,y=null;if(null!==g)if(y=t.get(m.prefix,g),g===d.namespace.XMLNS){if(m.value===d.namespace.XML||null===m.prefix&&o||null!==m.prefix&&(!(m.localName in n)||n[m.localName]!==m.value)&&t.has(m.localName,m.value))continue;if(a&&m.value===d.namespace.XMLNS)return void this.emit("error",new Error("XMLNS namespace is reserved (well-formed required)."));if(a&&""===m.value)return void this.emit("error",new Error("Namespace prefix declarations cannot be used to undeclare a namespace (well-formed required)."));"xmlns"===m.prefix&&(y="xmlns")}else null===y&&(y=null===m.prefix||t.hasPrefix(m.prefix)&&!t.has(m.prefix,g)?this._generatePrefix(g,t,r):m.prefix,this._push(this._writer.attribute("xmlns:"+y,this._serializeAttributeValue(g,this._options.wellFormed))));if(a&&(-1!==m.localName.indexOf(":")||!c.xml_isName(m.localName)||"xmlns"===m.localName&&null===g))return void this.emit("error",new Error("Attribute local name contains invalid characters (well-formed required)."));this._push(this._writer.attribute((null!==y?y+":":"")+m.localName,this._serializeAttributeValue(m.value,this._options.wellFormed)))}else this._push(this._writer.attribute(m.localName,this._serializeAttributeValue(m.value,this._options.wellFormed)))}}catch(e){s={error:e}}finally{try{h&&!h.done&&(l=p.return)&&l.call(p)}finally{if(s)throw s.error}}},t.prototype._serializeAttributeValue=function(e,t){return t&&null!==e&&!c.xml_isLegalChar(e)?(this.emit("error",new Error("Invalid characters in attribute value.")),""):null===e?"":e.replace(/(?!&(lt|gt|amp|apos|quot);)&/g,"&").replace(//g,">").replace(/"/g,""")},t.prototype._recordNamespaceInformation=function(e,t,r){var n,o,a=null;try{for(var s=i(e.attributes),l=s.next();!l.done;l=s.next()){var u=l.value,c=u.namespaceURI,p=u.prefix;if(c===d.namespace.XMLNS){if(null===p){a=u.value;continue}var f=u.localName,h=u.value;if(h===d.namespace.XML)continue;if(""===h&&(h=null),t.has(f,h))continue;t.set(f,h),r[f]=h||""}}}catch(e){n={error:e}}finally{try{l&&!l.done&&(o=s.return)&&o.call(s)}finally{if(n)throw n.error}}return a},t.prototype._generatePrefix=function(e,t,r){var n="ns"+r.value;return r.value++,t.set(n,e),n},t.prototype._isPrefixMapModified=function(e,t){var r=e._items,n=t._items,o=e._nullItems,i=t._nullItems;for(var a in n){var s=r[a];if(void 0===s)return!0;var l=n[a];if(s.length!==l.length)return!0;for(var u=0;u"},t.prototype.docType=function(e,t,r){return this._beginLine()+(t&&r?"':t?"':r?"':"")},t.prototype.comment=function(e){return this._beginLine()+"\x3c!--"+e+"--\x3e"},t.prototype.text=function(e){return this._beginLine()+e},t.prototype.instruction=function(e,t){return t?this._beginLine()+"":this._beginLine()+""},t.prototype.cdata=function(e){return this._beginLine()+""},t.prototype.openTagBegin=function(e){return this._lineLength+=1+e.length,this._beginLine()+"<"+e},t.prototype.openTagEnd=function(e,t,r){return r?" />":t?this._writerOptions.allowEmptyTags?">":this._writerOptions.spaceBeforeSlash?" />":"/>":">"},t.prototype.closeTag=function(e){return this._beginLine()+""},t.prototype.attribute=function(e,t){var r=e+'="'+t+'"';return this._writerOptions.prettyPrint&&this._writerOptions.width>0&&this._lineLength+1+r.length>this._writerOptions.width?(r=this._beginLine()+this._indent(1)+r,this._lineLength=r.length,r):(this._lineLength+=1+r.length," "+r)},t.prototype.beginElement=function(e){},t.prototype.endElement=function(e){},t.prototype._beginLine=function(){if(this._writerOptions.prettyPrint){var e=(this.hasData?this._writerOptions.newline:"")+this._indent(this._writerOptions.offset+this.level);return this._lineLength=e.length,e}return""},t.prototype._indent=function(e){return e<=0?"":this._writerOptions.indent.repeat(e)},t}(r(114).BaseCBWriter);t.XMLCBWriter=i},function(e,t,r){"use strict";r(74);var n,o=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var i=function(e){function t(t){var r=e.call(this,t)||this;return r._hasChildren=[],r._additionalLevel=0,r}return o(t,e),t.prototype.frontMatter=function(){return""},t.prototype.declaration=function(e,t,r){return""},t.prototype.docType=function(e,t,r){return""},t.prototype.comment=function(e){return this._comma()+this._beginLine()+"{"+this._sep()+this._key(this._builderOptions.convert.comment)+this._sep()+this._val(e)+this._sep()+"}"},t.prototype.text=function(e){return this._comma()+this._beginLine()+"{"+this._sep()+this._key(this._builderOptions.convert.text)+this._sep()+this._val(e)+this._sep()+"}"},t.prototype.instruction=function(e,t){return this._comma()+this._beginLine()+"{"+this._sep()+this._key(this._builderOptions.convert.ins)+this._sep()+this._val(t?e+" "+t:e)+this._sep()+"}"},t.prototype.cdata=function(e){return this._comma()+this._beginLine()+"{"+this._sep()+this._key(this._builderOptions.convert.cdata)+this._sep()+this._val(e)+this._sep()+"}"},t.prototype.attribute=function(e,t){return this._comma()+this._beginLine(1)+"{"+this._sep()+this._key(this._builderOptions.convert.att+e)+this._sep()+this._val(t)+this._sep()+"}"},t.prototype.openTagBegin=function(e){var t=this._comma()+this._beginLine()+"{"+this._sep()+this._key(e)+this._sep()+"{";return this._additionalLevel++,this.hasData=!0,t+=this._beginLine()+this._key(this._builderOptions.convert.text)+this._sep()+"[",this._hasChildren.push(!1),t},t.prototype.openTagEnd=function(e,t,r){if(t){var n=this._sep()+"]";return this._additionalLevel--,n+(this._beginLine()+"}")+this._sep()+"}"}return""},t.prototype.closeTag=function(e){var t=this._beginLine()+"]";return this._additionalLevel--,t+(this._beginLine()+"}")+this._sep()+"}"},t.prototype.beginElement=function(e){},t.prototype.endElement=function(e){this._hasChildren.pop()},t.prototype._beginLine=function(e){return void 0===e&&(e=0),this._writerOptions.prettyPrint?(this.hasData?this._writerOptions.newline:"")+this._indent(this._writerOptions.offset+this.level+e):""},t.prototype._indent=function(e){return e+this._additionalLevel<=0?"":this._writerOptions.indent.repeat(e+this._additionalLevel)},t.prototype._comma=function(){var e=this._hasChildren[this._hasChildren.length-1]?",":"";return this._hasChildren.length>0&&(this._hasChildren[this._hasChildren.length-1]=!0),e},t.prototype._sep=function(){return this._writerOptions.prettyPrint?" ":""},t.prototype._key=function(e){return'"'+e+'":'},t.prototype._val=function(e){return JSON.stringify(e)},t}(r(114).BaseCBWriter);t.JSONCBWriter=i},function(e,t,r){"use strict";r(74);var n,o=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0});var i=function(e){function t(t){var r=e.call(this,t)||this;if(r._rootWritten=!1,r._additionalLevel=0,t.indent.length<2)throw new Error("YAML indententation string must be at least two characters long.");if(t.offset<0)throw new Error("YAML offset should be zero or a positive number.");return r}return o(t,e),t.prototype.frontMatter=function(){return this._beginLine()+"---"},t.prototype.declaration=function(e,t,r){return""},t.prototype.docType=function(e,t,r){return""},t.prototype.comment=function(e){return this._beginLine()+this._key(this._builderOptions.convert.comment)+" "+this._val(e)},t.prototype.text=function(e){return this._beginLine()+this._key(this._builderOptions.convert.text)+" "+this._val(e)},t.prototype.instruction=function(e,t){return this._beginLine()+this._key(this._builderOptions.convert.ins)+" "+this._val(t?e+" "+t:e)},t.prototype.cdata=function(e){return this._beginLine()+this._key(this._builderOptions.convert.cdata)+" "+this._val(e)},t.prototype.attribute=function(e,t){this._additionalLevel++;var r=this._beginLine()+this._key(this._builderOptions.convert.att+e)+" "+this._val(t);return this._additionalLevel--,r},t.prototype.openTagBegin=function(e){var t=this._beginLine()+this._key(e);return this._rootWritten||(this._rootWritten=!0),this.hasData=!0,this._additionalLevel++,t+(this._beginLine(!0)+this._key(this._builderOptions.convert.text))},t.prototype.openTagEnd=function(e,t,r){return t?" "+this._val(""):""},t.prototype.closeTag=function(e){return this._additionalLevel--,""},t.prototype.beginElement=function(e){},t.prototype.endElement=function(e){},t.prototype._beginLine=function(e){return void 0===e&&(e=!1),(this.hasData?this._writerOptions.newline:"")+this._indent(this._writerOptions.offset+this.level,e)},t.prototype._indent=function(e,t){if(e+this._additionalLevel<=0)return"";var r=this._writerOptions.indent.repeat(e+this._additionalLevel);return!t&&this._rootWritten?r.substr(0,r.length-2)+"-"+r.substr(-1,1):r},t.prototype._key=function(e){return'"'+e+'":'},t.prototype._val=function(e){return JSON.stringify(e)},t}(r(114).BaseCBWriter);t.YAMLCBWriter=i},function(e,t,r){"use strict";var n,o="object"==typeof Reflect?Reflect:null,i=o&&"function"==typeof o.apply?o.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};n=o&&"function"==typeof o.ownKeys?o.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var a=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}e.exports=s,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var l=10;function u(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function c(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function d(e,t,r,n){var o,i,a,s;if(u(r),void 0===(i=e._events)?(i=e._events=Object.create(null),e._eventsCount=0):(void 0!==i.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),i=e._events),a=i[t]),void 0===a)a=i[t]=r,++e._eventsCount;else if("function"==typeof a?a=i[t]=n?[r,a]:[a,r]:n?a.unshift(r):a.push(r),(o=c(e))>0&&a.length>o&&!a.warned){a.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=a.length,s=l,console&&console.warn&&console.warn(s)}return e}function p(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function f(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},o=p.bind(n);return o.listener=r,n.wrapFn=o,o}function h(e,t,r){var n=e._events;if(void 0===n)return[];var o=n[t];return void 0===o?[]:"function"==typeof o?r?[o.listener||o]:[o]:r?function(e){for(var t=new Array(e.length),r=0;r0&&(a=t[0]),a instanceof Error)throw a;var s=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw s.context=a,s}var l=o[e];if(void 0===l)return!1;if("function"==typeof l)i(l,this,t);else{var u=l.length,c=g(l,u);for(r=0;r=0;i--)if(r[i]===t||r[i].listener===t){a=r[i].listener,o=i;break}if(o<0)return this;0===o?r.shift():function(e,t){for(;t+1=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return h(this,e,!0)},s.prototype.rawListeners=function(e){return h(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):m.call(e,t)},s.prototype.listenerCount=m,s.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(77);t.createCB=function(e){return new n.XMLBuilderCBImpl(e)},t.fragmentCB=function(e){return new n.XMLBuilderCBImpl(e,!0)}}])},234(){}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={id:n,loaded:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.loaded=!0,i.exports}r.amdD=function(){throw new Error("define cannot be used indirect")},r.amdO={},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.hmd=e=>((e=Object.create(e)).children||(e.children=[]),Object.defineProperty(e,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+e.id)}}),e),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);var n=r(581);return n.default})()); \ No newline at end of file diff --git a/javascript/js/warp_mesh_field_select.js b/javascript/js/warp_mesh_field_select.js new file mode 100644 index 00000000..3b9cc3d7 --- /dev/null +++ b/javascript/js/warp_mesh_field_select.js @@ -0,0 +1,94 @@ +/** + * ComfyUI GeomPack - Warp Mesh field selector. + * + * The Warp Mesh node (GeomPackWarpMesh) is an output node: running it reports the + * candidate 3-component vertex fields. This extension renders them as clickable + * chips in a box under the node; clicking one writes it into the `field_name` + * widget. Re-run to apply the warp. + */ + +import { app } from "../../../scripts/app.js"; + +app.registerExtension({ + name: "geompack.warp_mesh_field_select", + + async beforeRegisterNodeDef(nodeType, nodeData) { + if (nodeData.name !== "GeomPackWarpMesh") return; + + const onNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function () { + const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined; + const node = this; + + const container = document.createElement("div"); + container.style.cssText = + "width:100%;box-sizing:border-box;padding:6px;background:#1c1c1c;" + + "border:1px solid #444;border-radius:4px;font:11px monospace;color:#bbb;" + + "display:flex;flex-direction:column;gap:6px;overflow:auto;"; + + const status = document.createElement("div"); + status.style.cssText = "color:#888;flex:0 0 auto;"; + status.textContent = "Run to list 3-D vertex fields."; + + const chips = document.createElement("div"); + chips.style.cssText = "display:flex;flex-wrap:wrap;gap:4px;align-content:flex-start;"; + + container.appendChild(status); + container.appendChild(chips); + + const widget = node.addDOMWidget("warp_fields", "WARP_FIELDS", container, { + getValue() { return ""; }, setValue() {}, + }); + widget.computeSize = () => [Math.max(node.size?.[0] || 240, 240), 150]; + + const fieldWidget = () => node.widgets?.find((w) => w.name === "field_name"); + + const render = (fields, selected) => { + chips.innerHTML = ""; + if (!fields || fields.length === 0) { + status.textContent = "No 3-D (n_vertices, 3) vertex fields on this mesh."; + return; + } + status.textContent = "Click a field to warp by it:"; + fields.forEach((name) => { + const chip = document.createElement("button"); + chip.textContent = name; + const isSel = name === selected; + chip.style.cssText = + "font:11px monospace;padding:2px 8px;border-radius:10px;cursor:pointer;" + + "border:1px solid " + (isSel ? "#6c6" : "#555") + ";" + + "background:" + (isSel ? "#264" : "#2b2b2b") + ";" + + "color:" + (isSel ? "#cfc" : "#ddd") + ";"; + chip.addEventListener("mouseenter", () => { + if (name !== selected) chip.style.background = "#383838"; + }); + chip.addEventListener("mouseleave", () => { + if (name !== selected) chip.style.background = "#2b2b2b"; + }); + chip.addEventListener("click", () => { + const w = fieldWidget(); + if (w) { + w.value = name; + w.callback?.(name); + } + render(fields, name); + node.setDirtyCanvas(true, true); + }); + chips.appendChild(chip); + }); + }; + + const onExecuted = node.onExecuted; + node.onExecuted = function (message) { + onExecuted?.apply(this, arguments); + const fields = message?.fields?.[0] || []; + const selected = message?.selected?.[0] || (fieldWidget()?.value ?? ""); + const warped = message?.warped?.[0]; + render(fields, selected); + if (warped) status.textContent = "Warped by '" + selected + "'. Pick another to change."; + }; + + return r; + }; + }, +}); diff --git a/javascript/viewer.html b/javascript/viewer.html new file mode 100644 index 00000000..ffdc3c83 --- /dev/null +++ b/javascript/viewer.html @@ -0,0 +1,218 @@ + + + + + GeomPack 3D Viewer + + + + +
Ready to load mesh
+ + + + + + diff --git a/javascript/viewer_bvh.html b/javascript/viewer_bvh.html new file mode 100644 index 00000000..121c140b --- /dev/null +++ b/javascript/viewer_bvh.html @@ -0,0 +1,277 @@ + + + + + + + +
Loading BVH animation...
+ +
+ + + + + + diff --git a/javascript/viewer_compare_smpl_bvh.html b/javascript/viewer_compare_smpl_bvh.html new file mode 100644 index 00000000..ad055edd --- /dev/null +++ b/javascript/viewer_compare_smpl_bvh.html @@ -0,0 +1,354 @@ + + + + + + + +
+
+
Waiting for data...
+
SMPL (Mesh)
+
BVH (Skeleton)
+
+
+ + +
0 / 0
+
+
+ + + + + + diff --git a/javascript/viewer_dual.html b/javascript/viewer_dual.html new file mode 100644 index 00000000..4ad71c32 --- /dev/null +++ b/javascript/viewer_dual.html @@ -0,0 +1,1679 @@ + + + + + GeomPack VTK.js Dual Mesh Viewer + + + +
+ +
+
+
Mesh 1
+
+
+
+
Mesh 2
+
+
+
+ + +
+
+
+ +
Ready to load meshes
+ + +
+
+

Appearance Settings

+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+ +
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+ + +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
+ + + + + + +
+
+ + + + + + diff --git a/javascript/viewer_dual_slider.html b/javascript/viewer_dual_slider.html new file mode 100644 index 00000000..d92fb1f3 --- /dev/null +++ b/javascript/viewer_dual_slider.html @@ -0,0 +1,1244 @@ + + + + + GeomPack VTK.js Dual Mesh Slider Viewer + + + +
+ +
+ +
+ + +
+
+
+
Mesh 1
+
Mesh 2
+
+ +
Ready to load meshes
+ + +
+
+

Appearance Settings

+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+ +
+
+ + +
+
+ + +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + diff --git a/javascript/viewer_dual_textured.html b/javascript/viewer_dual_textured.html new file mode 100644 index 00000000..0d3bfaa7 --- /dev/null +++ b/javascript/viewer_dual_textured.html @@ -0,0 +1,1464 @@ + + + + + GeomPack VTK.js Dual Textured Mesh Viewer + + + +
+ +
+
+
Mesh 1
+
+
+
+
Mesh 2
+
+
+
+ + +
+
+
+ +
Ready to load meshes
+ + +
+
+

Appearance Settings

+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+ +
+
+ + +
+
+ + +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
+ + + + + +
+
+ + + + + + diff --git a/javascript/viewer_fbx.html b/javascript/viewer_fbx.html new file mode 100644 index 00000000..5a69dac9 --- /dev/null +++ b/javascript/viewer_fbx.html @@ -0,0 +1,1123 @@ + + + + + FBX Viewer + + + +
+ +
Ready to load rigged mesh
+
+ +
+
FBX Viewer
+ +
+ + + +
+ +
+ + +
+ +
+ + + +
+ +
+ + + +
+ +
No mesh loaded
+
+ + + + + diff --git a/javascript/viewer_fbx_animation.html b/javascript/viewer_fbx_animation.html new file mode 100644 index 00000000..6acfc5c0 --- /dev/null +++ b/javascript/viewer_fbx_animation.html @@ -0,0 +1,316 @@ + + + + + + + +
Loading animated FBX...
+
+ + + + + + diff --git a/javascript/viewer_fbx_compare.html b/javascript/viewer_fbx_compare.html new file mode 100644 index 00000000..a6466dde --- /dev/null +++ b/javascript/viewer_fbx_compare.html @@ -0,0 +1,1007 @@ + + + + + FBX Compare Viewer - Side-by-Side Skeleton Comparison + + + +
+
+
Left Skeleton
+ +
Ready to load skeletons
+
+
+
Right Skeleton
+ +
+
+ + +
+

Bone Comparison

+
+
Bone
+
-
+
+
+
Source
+
-
+
+
+
Left Position
+
-
+
+
+
Right Position
+
-
+
+
+
Left Rotation
+
-
+
+
+
Right Rotation
+
-
+
+
-
+
+ +
+
FBX Compare Viewer - Side-by-Side Skeleton Comparison
+ +
+ + + + + + +
+ +
+
+ + + 1.0x +
+
+ + + 1.0x +
+ +
+ +
No skeletons loaded
+
+ + + + diff --git a/javascript/viewer_fbx_debug.html b/javascript/viewer_fbx_debug.html new file mode 100644 index 00000000..9a6a994d --- /dev/null +++ b/javascript/viewer_fbx_debug.html @@ -0,0 +1,1936 @@ + + + + + FBX Debug Viewer - Bone Roll & Animation + + + +
+ +
Ready to load rigged mesh
+
+ + +
+

Bone Info

+
+
Name
+
-
+
Parent
+
-
+
Index
+
-
+
+
+
Roll Angle (Z-rotation)
+
-
+
+
+
Local Position
+
+ X: - + Y: - + Z: - +
+
Local Rotation (Euler XYZ)
+
+ X: - + Y: - + Z: - +
+
Local Quaternion
+
-
+
Local Scale
+
-
+
+
+
World Position
+
+ X: - + Y: - + Z: - +
+
World Rotation (Euler XYZ)
+
+ X: - + Y: - + Z: - +
+
+
+
Bone Length
+
-
+
Children
+
-
+
+
+ +
+
FBX Debug Viewer - Bone Roll & Animation Debugging
+ + +
+
Animation Playback
+
+ +
+
+
+ + + + + +
+ + 0.00s / 0.00s +
+
+
+ + + 1.0x +
+ +
+
+ + +
+
Visualization
+
+ + + + + +
+
+ + +
+
Size Controls
+
+
+ + + 1.0x +
+
+ + + 1.0x +
+
+ + + 1.0x +
+
+
+ + +
+
Bone Filter
+
+ + 0/0 bones +
+
+ + +
+
Scene
+
+ + + +
+
+ + +
+ + + + + +
+ +
No mesh loaded
+
+ + + + diff --git a/javascript/viewer_gaussian.html b/javascript/viewer_gaussian.html new file mode 100644 index 00000000..2c2b7460 --- /dev/null +++ b/javascript/viewer_gaussian.html @@ -0,0 +1,958 @@ + + + + + + GeomPack Gaussian Splat Viewer + + + +
+ + + + + +
+ +
+
+ Scale: + +
+ + + +
+ + + + + + + diff --git a/javascript/viewer_multi.html b/javascript/viewer_multi.html new file mode 100644 index 00000000..e7089db0 --- /dev/null +++ b/javascript/viewer_multi.html @@ -0,0 +1,1221 @@ + + + + + GeomPack VTK.js Multi Mesh Viewer + + + +
+ + + +
+
+

Appearance Settings

+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+ +
+
+ + +
+
+ + +
+
+
+ +
Ready to load meshes
+ +
+ + + + + + + + + + + + + + + + + + + + + +
+ + + +
+
+ + + + + + diff --git a/javascript/viewer_multi_slider.html b/javascript/viewer_multi_slider.html new file mode 100644 index 00000000..32f610ff --- /dev/null +++ b/javascript/viewer_multi_slider.html @@ -0,0 +1,476 @@ + + + + + GeomPack VTK.js Multi Mesh Slider Viewer + + + +
+ +
+
Ready to load meshes
+ +
+
+

Appearance Settings

+
+
+
+
+
+
+
+
+ +
+ + + + + + + + + + +
+ + + + + + + diff --git a/javascript/viewer_pbr.html b/javascript/viewer_pbr.html new file mode 100644 index 00000000..45966619 --- /dev/null +++ b/javascript/viewer_pbr.html @@ -0,0 +1,409 @@ + + + + + GeomPack PBR Viewer + + + + +
Ready to load mesh
+
PBR Viewer
+ + + + + + diff --git a/javascript/viewer_slicer.html b/javascript/viewer_slicer.html new file mode 100644 index 00000000..09905d41 --- /dev/null +++ b/javascript/viewer_slicer.html @@ -0,0 +1,386 @@ + + + + + GeomPack Mesh Slicer + + + + +
+
+
+
+ 3d view: + + + + + + + load a mesh, then click 2 points in the bottom view to set the cut +
+
+ cut view: + + + + + + + + +
+
+
+
+
+ + + diff --git a/javascript/viewer_uv.html b/javascript/viewer_uv.html new file mode 100644 index 00000000..44bcab1f --- /dev/null +++ b/javascript/viewer_uv.html @@ -0,0 +1,733 @@ + + + + + GeomPack UV Viewer + + + +
+
+
3D Mesh
+ +
+
+
UV Layout
+ +
+
+
Ready to load mesh
+
+ + + + + + diff --git a/javascript/viewer_vtk.html b/javascript/viewer_vtk.html new file mode 100644 index 00000000..d649d72b --- /dev/null +++ b/javascript/viewer_vtk.html @@ -0,0 +1,1223 @@ + + + + + GeomPack VTK.js Viewer (Unified) + + + + +
+
+
▾
+
+
+
Ready to load mesh
+
+ + +
+
+

Appearance Settings

+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+ +
+
+ +
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+ + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + diff --git a/javascript/viewer_vtk_textured.html b/javascript/viewer_vtk_textured.html new file mode 100644 index 00000000..5973156f --- /dev/null +++ b/javascript/viewer_vtk_textured.html @@ -0,0 +1,461 @@ + + + + + GeomPack VTK.js Textured Viewer (Unified) + + + + +
+
+
+
+
Ready to load textured mesh
+
+ + + +
+ +
+ + + + + + + + + + + + + + + + + + + + + +
+ + +
+
+

Appearance Settings

+
+ + +
+
+ + +
+
+ +
+
+ + +
+
+ + + + + + + + + diff --git a/nodes/visualization/preview_mesh_slicer.py b/nodes/visualization/preview_mesh_slicer.py index 38dbe422..e7a1acf7 100644 --- a/nodes/visualization/preview_mesh_slicer.py +++ b/nodes/visualization/preview_mesh_slicer.py @@ -12,7 +12,7 @@ the mesh center directly, without needing to pick 2 points. The Python node exports the mesh to a .vtp for the interactive viewer; the actual clip plane (origin + normal) is picked entirely in the browser, then mirrored back -here via a hidden `plane_json` widget (see web_src/preview_mesh_slicer.js) so this +here via a hidden `plane_json` widget (see javascript/js/preview_mesh_slicer.js) so this node can reproduce the same cut on the real mesh data and return it as `sliced_mesh` -- matching whatever is currently shown in the top 3D view. Since the plane only exists once the browser has posted it back, the very first run (or right after diff --git a/prestartup_script.py b/prestartup_script.py index 75a55c84..83b32028 100644 --- a/prestartup_script.py +++ b/prestartup_script.py @@ -1,42 +1,18 @@ """ComfyUI-GeometryPack Prestartup Script.""" import logging -import os -import sys +from pathlib import Path + +from comfy_env import setup_env, copy_files log = logging.getLogger("geometrypack") -from pathlib import Path -from comfy_env import setup_env, copy_files -from comfy_3d_viewers import copy_viewer - setup_env() SCRIPT_DIR = Path(__file__).resolve().parent COMFYUI_DIR = SCRIPT_DIR.parent.parent -# Copy viewers (GeometryPack uses many viewer types) -viewers = [ - "viewer", "vtk", "vtk_batch", "vtk_textured", "pointcloud_vtk", - "multi", "multi_slider", "dual", "dual_slider", "dual_textured", - "uv", "pbr", "gaussian", - "fbx", "fbx_debug", "fbx_compare", - "bvh", "fbx_animation", "compare_smpl_bvh", - "text_report", - "ultimate_inspection", - "slicer", - "warp_mesh", -] -for viewer in viewers: - try: - copy_viewer(viewer, SCRIPT_DIR / "web") - except Exception as e: - log.warning("Failed to copy viewer %s: %s", viewer, e) - -# Copy GeometryPack-local frontend JS (tracked source -> served web/js, since web/ is generated) -copy_files(SCRIPT_DIR / "web_src", SCRIPT_DIR / "web" / "js", "*.js") - -# Copy assets into the CONFIGURED input directory, not the code-tree one: +# Copy input assets into the CONFIGURED input directory, not the code-tree one: # ComfyUI Desktop separates user data from the code tree (--base-directory), # so COMFYUI_DIR/input is never scanned by the load nodes there. main.py # calls apply_custom_paths() before prestartup scripts, so folder_paths is @@ -47,5 +23,4 @@ try: except Exception: INPUT_DIR = COMFYUI_DIR / "input" copy_files(SCRIPT_DIR / "assets", INPUT_DIR / "3d", "**/*") - -copy_files(SCRIPT_DIR / "assets", INPUT_DIR, "*.exr") \ No newline at end of file +copy_files(SCRIPT_DIR / "assets", INPUT_DIR, "*.exr") diff --git a/pyproject.toml b/pyproject.toml index ded40196..6c3c4ae1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,3 +11,4 @@ Repository = "https://github.com/PozzettiAndrea/ComfyUI-GeometryPack" PublisherId = "pznodes" DisplayName = "GeometryPack" Icon = "https://raw.githubusercontent.com/PozzettiAndrea/ComfyUI-GeometryPack/main/assets/icon.png" +web = "javascript" diff --git a/requirements.txt b/requirements.txt index 1efac36f..fe18a16b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1 @@ comfy-env==0.4.14 -comfy-3d-viewers==0.2.55 \ No newline at end of file