@thatopen/components 3.3.2 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,19 @@
1
- "use strict";var t=Object.defineProperty,e=(e,i,s)=>(((e,i,s)=>{i in e?t(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s})(e,"symbol"!=typeof i?i+"":i,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@thatopen/fragments"),s=require("three"),n=require("web-ifc");function r(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t)for(const i in t)if("default"!==i){const s=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,s.get?s:{enumerable:!0,get:()=>t[i]})}return e.default=t,Object.freeze(e)}const o=r(i),a=r(s),l=r(n);class h{constructor(){e(this,"enabled",!0),e(this,"trigger",t=>{if(!this.enabled)return;const e=this.handlers.slice(0);for(const i of e)i(t)}),e(this,"handlers",[])}add(t){this.handlers.push(t)}remove(t){this.handlers=this.handlers.filter(e=>e!==t)}reset(){this.handlers.length=0}}class c{constructor(t){e(this,"isDisposeable",()=>"dispose"in this&&"onDisposed"in this),e(this,"isResizeable",()=>"resize"in this&&"getSize"in this),e(this,"isUpdateable",()=>"onAfterUpdate"in this&&"onBeforeUpdate"in this&&"update"in this),e(this,"isHideable",()=>"visible"in this),e(this,"isConfigurable",()=>"setup"in this&&"config"in this&&"onSetup"in this),e(this,"isSerializable",()=>"import"in this&&"export"in this),this.components=t}}class d extends c{}class u extends c{constructor(t){super(t),e(this,"worlds",new i.DataMap),e(this,"onWorldChanged",new h),e(this,"_currentWorld",null),this.onWorldChanged.add(({world:t,action:e})=>{"removed"===e&&this.worlds.delete(t.uuid)})}set currentWorld(t){this._currentWorld=t}get currentWorld(){return this._currentWorld}}class p extends u{constructor(){super(...arguments),e(this,"hasCameraControls",()=>"controls"in this)}}class f extends u{constructor(){super(...arguments),e(this,"onAfterUpdate",new h),e(this,"onBeforeUpdate",new h),e(this,"onDisposed",new h),e(this,"onResize",new h),e(this,"onClippingPlanesUpdated",new h),e(this,"clippingPlanes",[])}updateClippingPlanes(){this.onClippingPlanesUpdated.trigger()}setPlane(t,e,i){e.isLocal=i;const s=this.clippingPlanes.indexOf(e);t&&-1===s?this.clippingPlanes.push(e):!t&&s>-1&&this.clippingPlanes.splice(s,1),this.three.clippingPlanes=this.clippingPlanes.filter(t=>!t.isLocal)}}const m=class t extends d{constructor(i){super(i),e(this,"_disposedComponents",new Set),e(this,"enabled",!0),i.add(t.uuid,this)}get(){return this._disposedComponents}destroy(t,e=!0,i=!0){t.removeFromParent();const s=t;s.dispose&&s.dispose(),this.disposeGeometryAndMaterials(t,e),i&&s.children&&s.children.length&&this.disposeChildren(s),t.children.length=0}disposeGeometry(t){t.boundsTree&&t.disposeBoundsTree&&t.disposeBoundsTree(),t.dispose()}disposeGeometryAndMaterials(e,i){const s=e;s.geometry&&this.disposeGeometry(s.geometry),i&&s.material&&t.disposeMaterial(s),s.material=[],s.geometry=null}disposeChildren(t){for(const e of t.children)this.destroy(e)}static disposeMaterial(t){if(t.material)if(Array.isArray(t.material))for(const e of t.material)e.dispose();else t.material.dispose()}};e(m,"uuid","76e9cd8e-ad8f-4753-9ef6-cbc60f7247fe");let g=m;class _ extends u{constructor(t){super(t),e(this,"onDisposed",new h),e(this,"directionalLights",new Map),e(this,"ambientLights",new Map)}dispose(){const t=this.components.get(g);for(const e of this.three.children){const i=e;i.geometry&&t.destroy(i)}this.deleteAllLights(),this.three.children=[],this.onDisposed.trigger(),this.onDisposed.reset()}deleteAllLights(){for(const[,t]of this.directionalLights)t.removeFromParent(),t.target.removeFromParent(),t.dispose();this.directionalLights.clear();for(const[,t]of this.ambientLights)t.removeFromParent(),t.dispose();this.ambientLights.clear()}}class y extends Set{constructor(t){super(t),e(this,"onItemAdded",new h),e(this,"onItemDeleted",new h),e(this,"onCleared",new h),e(this,"guard",()=>!0)}clear(){super.clear(),this.onCleared.trigger()}add(...t){for(const e of t){if(this.has(e))continue;this.guard(e)&&(super.add(e),this.onItemAdded||(this.onItemAdded=new h),this.onItemAdded.trigger(e))}return this}delete(t){const e=super.delete(t);return e&&this.onItemDeleted.trigger(),e}dispose(){this.clear(),this.onItemAdded.reset(),this.onItemDeleted.reset(),this.onCleared.reset()}}const w=class t{static create(){const e=4294967295*Math.random()|0,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0,n=4294967295*Math.random()|0;return`${t._lut[255&e]+t._lut[e>>8&255]+t._lut[e>>16&255]+t._lut[e>>24&255]}-${t._lut[255&i]}${t._lut[i>>8&255]}-${t._lut[i>>16&15|64]}${t._lut[i>>24&255]}-${t._lut[63&s|128]}${t._lut[s>>8&255]}-${t._lut[s>>16&255]}${t._lut[s>>24&255]}${t._lut[255&n]}${t._lut[n>>8&255]}${t._lut[n>>16&255]}${t._lut[n>>24&255]}`.toLowerCase()}static validate(e){if(!t._pattern.test(e))throw new Error(`${e} is not a valid UUID v4.\n\n- If you're the tool creator, you can take one from https://www.uuidgenerator.net/.\n\n- If you're using a platform tool, verify the uuid isn't misspelled or contact the tool creator.`)}};e(w,"_pattern",/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/),e(w,"_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"]);let v=w;var b="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function x(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var T={},C={};!function(t){const e=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",i="["+e+"]["+(e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040")+"]*",s=new RegExp("^"+i+"$");t.isExist=function(t){return void 0!==t},t.isEmptyObject=function(t){return 0===Object.keys(t).length},t.merge=function(t,e,i){if(e){const s=Object.keys(e),n=s.length;for(let r=0;r<n;r++)t[s[r]]="strict"===i?[e[s[r]]]:e[s[r]]}},t.getValue=function(e){return t.isExist(e)?e:""},t.isName=function(t){const e=s.exec(t);return!(null==e)},t.getAllMatches=function(t,e){const i=[];let s=e.exec(t);for(;s;){const n=[];n.startIndex=e.lastIndex-s[0].length;const r=s.length;for(let t=0;t<r;t++)n.push(s[t]);i.push(n),s=e.exec(t)}return i},t.nameRegexp=i}(C);const E=C,S={allowBooleanAttributes:!1,unpairedTags:[]};function A(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function O(t,e){const i=e;for(;e<t.length;e++)if("?"==t[e]||" "==t[e]){const s=t.substr(i,e-i);if(e>5&&"xml"===s)return N("InvalidXml","XML declaration allowed only at the start of the document.",R(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}continue}return e}function P(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e<t.length;e++)if("-"===t[e]&&"-"===t[e+1]&&">"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){let i=1;for(e+=8;e<t.length;e++)if("<"===t[e])i++;else if(">"===t[e]&&(i--,0===i))break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e<t.length;e++)if("]"===t[e]&&"]"===t[e+1]&&">"===t[e+2]){e+=2;break}return e}T.validate=function(t,e){e=Object.assign({},S,e);const i=[];let s=!1,n=!1;"\ufeff"===t[0]&&(t=t.substr(1));for(let r=0;r<t.length;r++)if("<"===t[r]&&"?"===t[r+1]){if(r+=2,r=O(t,r),r.err)return r}else{if("<"!==t[r]){if(A(t[r]))continue;return N("InvalidChar","char '"+t[r]+"' is not expected.",R(t,r))}{let o=r;if(r++,"!"===t[r]){r=P(t,r);continue}{let a=!1;"/"===t[r]&&(a=!0,r++);let l="";for(;r<t.length&&">"!==t[r]&&" "!==t[r]&&"\t"!==t[r]&&"\n"!==t[r]&&"\r"!==t[r];r++)l+=t[r];if(l=l.trim(),"/"===l[l.length-1]&&(l=l.substring(0,l.length-1),r--),!L(l)){let e;return e=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",N("InvalidTag",e,R(t,r))}const h=D(t,r);if(!1===h)return N("InvalidAttr","Attributes for '"+l+"' have open quote.",R(t,r));let c=h.value;if(r=h.index,"/"===c[c.length-1]){const i=r-c.length;c=c.substring(0,c.length-1);const n=z(c,e);if(!0!==n)return N(n.err.code,n.err.msg,R(t,i+n.err.line));s=!0}else if(a){if(!h.tagClosed)return N("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",R(t,r));if(c.trim().length>0)return N("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",R(t,o));if(0===i.length)return N("InvalidTag","Closing tag '"+l+"' has not been opened.",R(t,o));{const e=i.pop();if(l!==e.tagName){let i=R(t,e.tagStartPos);return N("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+i.line+", col "+i.col+") instead of closing tag '"+l+"'.",R(t,o))}0==i.length&&(n=!0)}}else{const a=z(c,e);if(!0!==a)return N(a.err.code,a.err.msg,R(t,r-c.length+a.err.line));if(!0===n)return N("InvalidXml","Multiple possible root nodes found.",R(t,r));-1!==e.unpairedTags.indexOf(l)||i.push({tagName:l,tagStartPos:o}),s=!0}for(r++;r<t.length;r++)if("<"===t[r]){if("!"===t[r+1]){r++,r=P(t,r);continue}if("?"!==t[r+1])break;if(r=O(t,++r),r.err)return r}else if("&"===t[r]){const e=B(t,r);if(-1==e)return N("InvalidChar","char '&' is not expected.",R(t,r));r=e}else if(!0===n&&!A(t[r]))return N("InvalidXml","Extra text at the end",R(t,r));"<"===t[r]&&r--}}}return s?1==i.length?N("InvalidTag","Unclosed tag '"+i[0].tagName+"'.",R(t,i[0].tagStartPos)):!(i.length>0)||N("InvalidXml","Invalid '"+JSON.stringify(i.map(t=>t.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):N("InvalidXml","Start tag expected.",1)};const I='"',M="'";function D(t,e){let i="",s="",n=!1;for(;e<t.length;e++){if(t[e]===I||t[e]===M)""===s?s=t[e]:s!==t[e]||(s="");else if(">"===t[e]&&""===s){n=!0;break}i+=t[e]}return""===s&&{value:i,index:e,tagClosed:n}}const k=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function z(t,e){const i=E.getAllMatches(t,k),s={};for(let t=0;t<i.length;t++){if(0===i[t][1].length)return N("InvalidAttr","Attribute '"+i[t][2]+"' has no space in starting.",F(i[t]));if(void 0!==i[t][3]&&void 0===i[t][4])return N("InvalidAttr","Attribute '"+i[t][2]+"' is without value.",F(i[t]));if(void 0===i[t][3]&&!e.allowBooleanAttributes)return N("InvalidAttr","boolean attribute '"+i[t][2]+"' is not allowed.",F(i[t]));const n=i[t][2];if(!U(n))return N("InvalidAttr","Attribute '"+n+"' is an invalid name.",F(i[t]));if(s.hasOwnProperty(n))return N("InvalidAttr","Attribute '"+n+"' is repeated.",F(i[t]));s[n]=1}return!0}function B(t,e){if(";"===t[++e])return-1;if("#"===t[e])return function(t,e){let i=/\d/;for("x"===t[e]&&(e++,i=/[\da-fA-F]/);e<t.length;e++){if(";"===t[e])return e;if(!t[e].match(i))break}return-1}(t,++e);let i=0;for(;e<t.length;e++,i++)if(!(t[e].match(/\w/)&&i<20)){if(";"===t[e])break;return-1}return e}function N(t,e,i){return{err:{code:t,msg:e,line:i.line||i,col:i.col}}}function U(t){return E.isName(t)}function L(t){return E.isName(t)}function R(t,e){const i=t.substring(0,e).split(/\r?\n/);return{line:i.length,col:i[i.length-1].length+1}}function F(t){return t.startIndex+t[1].length}var V={};const j={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,i){return t}};V.buildOptions=function(t){return Object.assign({},j,t)},V.defaultOptions=j;const H=C;function Z(t,e){let i="";for(;e<t.length&&"'"!==t[e]&&'"'!==t[e];e++)i+=t[e];if(i=i.trim(),-1!==i.indexOf(" "))throw new Error("External entites are not supported");const s=t[e++];let n="";for(;e<t.length&&t[e]!==s;e++)n+=t[e];return[i,n,e]}function $(t,e){return"!"===t[e+1]&&"-"===t[e+2]&&"-"===t[e+3]}function W(t,e){return"!"===t[e+1]&&"E"===t[e+2]&&"N"===t[e+3]&&"T"===t[e+4]&&"I"===t[e+5]&&"T"===t[e+6]&&"Y"===t[e+7]}function Y(t,e){return"!"===t[e+1]&&"E"===t[e+2]&&"L"===t[e+3]&&"E"===t[e+4]&&"M"===t[e+5]&&"E"===t[e+6]&&"N"===t[e+7]&&"T"===t[e+8]}function G(t,e){return"!"===t[e+1]&&"A"===t[e+2]&&"T"===t[e+3]&&"T"===t[e+4]&&"L"===t[e+5]&&"I"===t[e+6]&&"S"===t[e+7]&&"T"===t[e+8]}function X(t,e){return"!"===t[e+1]&&"N"===t[e+2]&&"O"===t[e+3]&&"T"===t[e+4]&&"A"===t[e+5]&&"T"===t[e+6]&&"I"===t[e+7]&&"O"===t[e+8]&&"N"===t[e+9]}function q(t){if(H.isName(t))return t;throw new Error(`Invalid entity name ${t}`)}const Q=/^[-+]?0x[a-fA-F0-9]+$/,K=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,J={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};const tt=C,et=class{constructor(t){this.tagname=t,this.child=[],this[":@"]={}}add(t,e){"__proto__"===t&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t){"__proto__"===t.tagname&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child})}},it=function(t,e){const i={};if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");{e+=9;let s=1,n=!1,r=!1,o="";for(;e<t.length;e++)if("<"!==t[e]||r)if(">"===t[e]){if(r?"-"===t[e-1]&&"-"===t[e-2]&&(r=!1,s--):s--,0===s)break}else"["===t[e]?n=!0:o+=t[e];else{if(n&&W(t,e))e+=7,[entityName,val,e]=Z(t,e+1),-1===val.indexOf("&")&&(i[q(entityName)]={regx:RegExp(`&${entityName};`,"g"),val:val});else if(n&&Y(t,e))e+=8;else if(n&&G(t,e))e+=8;else if(n&&X(t,e))e+=9;else{if(!$)throw new Error("Invalid DOCTYPE");r=!0}s++,o=""}if(0!==s)throw new Error("Unclosed DOCTYPE")}return{entities:i,i:e}},st=function(t,e={}){if(e=Object.assign({},J,e),!t||"string"!=typeof t)return t;let i=t.trim();if(void 0!==e.skipLike&&e.skipLike.test(i))return t;if("0"===t)return 0;if(e.hex&&Q.test(i))return function(t,e){if(parseInt)return parseInt(t,e);if(Number.parseInt)return Number.parseInt(t,e);if(window&&window.parseInt)return window.parseInt(t,e);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(i,16);if(-1!==i.search(/[eE]/)){const s=i.match(/^([-\+])?(0*)([0-9]*(\.[0-9]*)?[eE][-\+]?[0-9]+)$/);if(s){if(e.leadingZeros)i=(s[1]||"")+s[3];else if("0"!==s[2]||"."!==s[3][0])return t;return e.eNotation?Number(i):t}return t}{const s=K.exec(i);if(s){const n=s[1],r=s[2];let o=function(t){if(t&&-1!==t.indexOf("."))return"."===(t=t.replace(/0+$/,""))?t="0":"."===t[0]?t="0"+t:"."===t[t.length-1]&&(t=t.substr(0,t.length-1)),t;return t}(s[3]);if(!e.leadingZeros&&r.length>0&&n&&"."!==i[2])return t;if(!e.leadingZeros&&r.length>0&&!n&&"."!==i[1])return t;if(e.leadingZeros&&r===t)return 0;{const s=Number(i),a=""+s;return-1!==a.search(/[eE]/)?e.eNotation?s:t:-1!==i.indexOf(".")?"0"===a&&""===o||a===o||n&&a==="-"+o?s:t:r?o===a||n+o===a?s:t:i===a||i===n+a?s:t}}return t}};function nt(t){const e=Object.keys(t);for(let i=0;i<e.length;i++){const s=e[i];this.lastEntities[s]={regex:new RegExp("&"+s+";","g"),val:t[s]}}}function rt(t,e,i,s,n,r,o){if(void 0!==t&&(this.options.trimValues&&!s&&(t=t.trim()),t.length>0)){o||(t=this.replaceEntitiesValue(t));const s=this.options.tagValueProcessor(e,t,i,n,r);if(null==s)return t;if(typeof s!=typeof t||s!==t)return s;if(this.options.trimValues)return _t(t,this.options.parseTagValue,this.options.numberParseOptions);return t.trim()===t?_t(t,this.options.parseTagValue,this.options.numberParseOptions):t}}function ot(t){if(this.options.removeNSPrefix){const e=t.split(":"),i="/"===t.charAt(0)?"/":"";if("xmlns"===e[0])return"";2===e.length&&(t=i+e[1])}return t}const at=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function lt(t,e,i){if(!this.options.ignoreAttributes&&"string"==typeof t){const i=tt.getAllMatches(t,at),s=i.length,n={};for(let t=0;t<s;t++){const s=this.resolveNameSpace(i[t][1]);let r=i[t][4],o=this.options.attributeNamePrefix+s;if(s.length)if(this.options.transformAttributeName&&(o=this.options.transformAttributeName(o)),"__proto__"===o&&(o="#__proto__"),void 0!==r){this.options.trimValues&&(r=r.trim()),r=this.replaceEntitiesValue(r);const t=this.options.attributeValueProcessor(s,r,e);n[o]=null==t?r:typeof t!=typeof r||t!==r?t:_t(r,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(n[o]=!0)}if(!Object.keys(n).length)return;if(this.options.attributesGroupName){const t={};return t[this.options.attributesGroupName]=n,t}return n}}const ht=function(t){t=t.replace(/\r\n?/g,"\n");const e=new et("!xml");let i=e,s="",n="";for(let r=0;r<t.length;r++){if("<"===t[r])if("/"===t[r+1]){const e=ft(t,">",r,"Closing Tag is not closed.");let o=t.substring(r+2,e).trim();if(this.options.removeNSPrefix){const t=o.indexOf(":");-1!==t&&(o=o.substr(t+1))}this.options.transformTagName&&(o=this.options.transformTagName(o)),i&&(s=this.saveTextToParentTag(s,i,n));const a=n.substring(n.lastIndexOf(".")+1);if(o&&-1!==this.options.unpairedTags.indexOf(o))throw new Error(`Unpaired tag can not be used as closing tag: </${o}>`);let l=0;a&&-1!==this.options.unpairedTags.indexOf(a)?(l=n.lastIndexOf(".",n.lastIndexOf(".")-1),this.tagsNodeStack.pop()):l=n.lastIndexOf("."),n=n.substring(0,l),i=this.tagsNodeStack.pop(),s="",r=e}else if("?"===t[r+1]){let e=mt(t,r,!1,"?>");if(!e)throw new Error("Pi Tag is not closed.");if(s=this.saveTextToParentTag(s,i,n),this.options.ignoreDeclaration&&"?xml"===e.tagName||this.options.ignorePiTags);else{const t=new et(e.tagName);t.add(this.options.textNodeName,""),e.tagName!==e.tagExp&&e.attrExpPresent&&(t[":@"]=this.buildAttributesMap(e.tagExp,n,e.tagName)),this.addChild(i,t,n)}r=e.closeIndex+1}else if("!--"===t.substr(r+1,3)){const e=ft(t,"--\x3e",r+4,"Comment is not closed.");if(this.options.commentPropName){const o=t.substring(r+4,e-2);s=this.saveTextToParentTag(s,i,n),i.add(this.options.commentPropName,[{[this.options.textNodeName]:o}])}r=e}else if("!D"===t.substr(r+1,2)){const e=it(t,r);this.docTypeEntities=e.entities,r=e.i}else if("!["===t.substr(r+1,2)){const e=ft(t,"]]>",r,"CDATA is not closed.")-2,o=t.substring(r+9,e);s=this.saveTextToParentTag(s,i,n);let a=this.parseTextData(o,i.tagname,n,!0,!1,!0,!0);null==a&&(a=""),this.options.cdataPropName?i.add(this.options.cdataPropName,[{[this.options.textNodeName]:o}]):i.add(this.options.textNodeName,a),r=e+2}else{let o=mt(t,r,this.options.removeNSPrefix),a=o.tagName;const l=o.rawTagName;let h=o.tagExp,c=o.attrExpPresent,d=o.closeIndex;this.options.transformTagName&&(a=this.options.transformTagName(a)),i&&s&&"!xml"!==i.tagname&&(s=this.saveTextToParentTag(s,i,n,!1));const u=i;if(u&&-1!==this.options.unpairedTags.indexOf(u.tagname)&&(i=this.tagsNodeStack.pop(),n=n.substring(0,n.lastIndexOf("."))),a!==e.tagname&&(n+=n?"."+a:a),this.isItStopNode(this.options.stopNodes,n,a)){let e="";if(h.length>0&&h.lastIndexOf("/")===h.length-1)"/"===a[a.length-1]?(a=a.substr(0,a.length-1),n=n.substr(0,n.length-1),h=a):h=h.substr(0,h.length-1),r=o.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(a))r=o.closeIndex;else{const i=this.readStopNodeData(t,l,d+1);if(!i)throw new Error(`Unexpected end of ${l}`);r=i.i,e=i.tagContent}const s=new et(a);a!==h&&c&&(s[":@"]=this.buildAttributesMap(h,n,a)),e&&(e=this.parseTextData(e,a,n,!0,c,!0,!0)),n=n.substr(0,n.lastIndexOf(".")),s.add(this.options.textNodeName,e),this.addChild(i,s,n)}else{if(h.length>0&&h.lastIndexOf("/")===h.length-1){"/"===a[a.length-1]?(a=a.substr(0,a.length-1),n=n.substr(0,n.length-1),h=a):h=h.substr(0,h.length-1),this.options.transformTagName&&(a=this.options.transformTagName(a));const t=new et(a);a!==h&&c&&(t[":@"]=this.buildAttributesMap(h,n,a)),this.addChild(i,t,n),n=n.substr(0,n.lastIndexOf("."))}else{const t=new et(a);this.tagsNodeStack.push(i),a!==h&&c&&(t[":@"]=this.buildAttributesMap(h,n,a)),this.addChild(i,t,n),i=t}s="",r=d}}else s+=t[r]}return e.child};function ct(t,e,i){const s=this.options.updateTag(e.tagname,i,e[":@"]);!1===s||("string"==typeof s?(e.tagname=s,t.addChild(e)):t.addChild(e))}const dt=function(t){if(this.options.processEntities){for(let e in this.docTypeEntities){const i=this.docTypeEntities[e];t=t.replace(i.regx,i.val)}for(let e in this.lastEntities){const i=this.lastEntities[e];t=t.replace(i.regex,i.val)}if(this.options.htmlEntities)for(let e in this.htmlEntities){const i=this.htmlEntities[e];t=t.replace(i.regex,i.val)}t=t.replace(this.ampEntity.regex,this.ampEntity.val)}return t};function ut(t,e,i,s){return t&&(void 0===s&&(s=0===Object.keys(e.child).length),void 0!==(t=this.parseTextData(t,e.tagname,i,!1,!!e[":@"]&&0!==Object.keys(e[":@"]).length,s))&&""!==t&&e.add(this.options.textNodeName,t),t=""),t}function pt(t,e,i){const s="*."+i;for(const i in t){const n=t[i];if(s===n||e===n)return!0}return!1}function ft(t,e,i,s){const n=t.indexOf(e,i);if(-1===n)throw new Error(s);return n+e.length-1}function mt(t,e,i,s=">"){const n=function(t,e,i=">"){let s,n="";for(let r=e;r<t.length;r++){let e=t[r];if(s)e===s&&(s="");else if('"'===e||"'"===e)s=e;else if(e===i[0]){if(!i[1])return{data:n,index:r};if(t[r+1]===i[1])return{data:n,index:r}}else"\t"===e&&(e=" ");n+=e}}(t,e+1,s);if(!n)return;let r=n.data;const o=n.index,a=r.search(/\s/);let l=r,h=!0;-1!==a&&(l=r.substring(0,a),r=r.substring(a+1).trimStart());const c=l;if(i){const t=l.indexOf(":");-1!==t&&(l=l.substr(t+1),h=l!==n.data.substr(t+1))}return{tagName:l,tagExp:r,closeIndex:o,attrExpPresent:h,rawTagName:c}}function gt(t,e,i){const s=i;let n=1;for(;i<t.length;i++)if("<"===t[i])if("/"===t[i+1]){const r=ft(t,">",i,`${e} is not closed`);if(t.substring(i+2,r).trim()===e&&(n--,0===n))return{tagContent:t.substring(s,i),i:r};i=r}else if("?"===t[i+1]){i=ft(t,"?>",i+1,"StopNode is not closed.")}else if("!--"===t.substr(i+1,3)){i=ft(t,"--\x3e",i+3,"StopNode is not closed.")}else if("!["===t.substr(i+1,2)){i=ft(t,"]]>",i,"StopNode is not closed.")-2}else{const s=mt(t,i,">");if(s){(s&&s.tagName)===e&&"/"!==s.tagExp[s.tagExp.length-1]&&n++,i=s.closeIndex}}}function _t(t,e,i){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&st(t,i)}return tt.isExist(t)?t:""}var yt=class{constructor(t){this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(t,e)=>String.fromCharCode(Number.parseInt(e,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(t,e)=>String.fromCharCode(Number.parseInt(e,16))}},this.addExternalEntities=nt,this.parseXml=ht,this.parseTextData=rt,this.resolveNameSpace=ot,this.buildAttributesMap=lt,this.isItStopNode=pt,this.replaceEntitiesValue=dt,this.readStopNodeData=gt,this.saveTextToParentTag=ut,this.addChild=ct}},wt={};function vt(t,e,i){let s;const n={};for(let r=0;r<t.length;r++){const o=t[r],a=bt(o);let l="";if(l=void 0===i?a:i+"."+a,a===e.textNodeName)void 0===s?s=o[a]:s+=""+o[a];else{if(void 0===a)continue;if(o[a]){let t=vt(o[a],e,l);const i=Tt(t,e);o[":@"]?xt(t,o[":@"],l,e):1!==Object.keys(t).length||void 0===t[e.textNodeName]||e.alwaysCreateTextNode?0===Object.keys(t).length&&(e.alwaysCreateTextNode?t[e.textNodeName]="":t=""):t=t[e.textNodeName],void 0!==n[a]&&n.hasOwnProperty(a)?(Array.isArray(n[a])||(n[a]=[n[a]]),n[a].push(t)):e.isArray(a,l,i)?n[a]=[t]:n[a]=t}}}return"string"==typeof s?s.length>0&&(n[e.textNodeName]=s):void 0!==s&&(n[e.textNodeName]=s),n}function bt(t){const e=Object.keys(t);for(let t=0;t<e.length;t++){const i=e[t];if(":@"!==i)return i}}function xt(t,e,i,s){if(e){const n=Object.keys(e),r=n.length;for(let o=0;o<r;o++){const r=n[o];s.isArray(r,i+"."+r,!0,!0)?t[r]=[e[r]]:t[r]=e[r]}}}function Tt(t,e){const{textNodeName:i}=e,s=Object.keys(t).length;return 0===s||!(1!==s||!t[i]&&"boolean"!=typeof t[i]&&0!==t[i])}wt.prettify=function(t,e){return vt(t,e)};const{buildOptions:Ct}=V,Et=yt,{prettify:St}=wt,At=T;var Ot=class{constructor(t){this.externalEntities={},this.options=Ct(t)}parse(t,e){if("string"==typeof t);else{if(!t.toString)throw new Error("XML data is accepted in String or Bytes[] form.");t=t.toString()}if(e){!0===e&&(e={});const i=At.validate(t,e);if(!0!==i)throw Error(`${i.err.msg}:${i.err.line}:${i.err.col}`)}const i=new Et(this.options);i.addExternalEntities(this.externalEntities);const s=i.parseXml(t);return this.options.preserveOrder||void 0===s?s:St(s,this.options)}addEntity(t,e){if(-1!==e.indexOf("&"))throw new Error("Entity value can't have '&'");if(-1!==t.indexOf("&")||-1!==t.indexOf(";"))throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if("&"===e)throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}};function Pt(t,e,i,s){let n="",r=!1;for(let o=0;o<t.length;o++){const a=t[o],l=It(a);if(void 0===l)continue;let h="";if(h=0===i.length?l:`${i}.${l}`,l===e.textNodeName){let t=a[l];Dt(h,e)||(t=e.tagValueProcessor(l,t),t=kt(t,e)),r&&(n+=s),n+=t,r=!1;continue}if(l===e.cdataPropName){r&&(n+=s),n+=`<![CDATA[${a[l][0][e.textNodeName]}]]>`,r=!1;continue}if(l===e.commentPropName){n+=s+`\x3c!--${a[l][0][e.textNodeName]}--\x3e`,r=!0;continue}if("?"===l[0]){const t=Mt(a[":@"],e),i="?xml"===l?"":s;let o=a[l][0][e.textNodeName];o=0!==o.length?" "+o:"",n+=i+`<${l}${o}${t}?>`,r=!0;continue}let c=s;""!==c&&(c+=e.indentBy);const d=s+`<${l}${Mt(a[":@"],e)}`,u=Pt(a[l],e,h,c);-1!==e.unpairedTags.indexOf(l)?e.suppressUnpairedNode?n+=d+">":n+=d+"/>":u&&0!==u.length||!e.suppressEmptyNode?u&&u.endsWith(">")?n+=d+`>${u}${s}</${l}>`:(n+=d+">",u&&""!==s&&(u.includes("/>")||u.includes("</"))?n+=s+e.indentBy+u+s:n+=u,n+=`</${l}>`):n+=d+"/>",r=!0}return n}function It(t){const e=Object.keys(t);for(let i=0;i<e.length;i++){const s=e[i];if(t.hasOwnProperty(s)&&":@"!==s)return s}}function Mt(t,e){let i="";if(t&&!e.ignoreAttributes)for(let s in t){if(!t.hasOwnProperty(s))continue;let n=e.attributeValueProcessor(s,t[s]);n=kt(n,e),!0===n&&e.suppressBooleanAttributes?i+=` ${s.substr(e.attributeNamePrefix.length)}`:i+=` ${s.substr(e.attributeNamePrefix.length)}="${n}"`}return i}function Dt(t,e){let i=(t=t.substr(0,t.length-e.textNodeName.length-1)).substr(t.lastIndexOf(".")+1);for(let s in e.stopNodes)if(e.stopNodes[s]===t||e.stopNodes[s]==="*."+i)return!0;return!1}function kt(t,e){if(t&&t.length>0&&e.processEntities)for(let i=0;i<e.entities.length;i++){const s=e.entities[i];t=t.replace(s.regex,s.val)}return t}const zt=function(t,e){let i="";return e.format&&e.indentBy.length>0&&(i="\n"),Pt(t,e,"",i)},Bt={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function Nt(t){this.options=Object.assign({},Bt,t),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=Rt),this.processTextOrObjNode=Ut,this.options.format?(this.indentate=Lt,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function Ut(t,e,i){const s=this.j2x(t,i+1);return void 0!==t[this.options.textNodeName]&&1===Object.keys(t).length?this.buildTextValNode(t[this.options.textNodeName],e,s.attrStr,i):this.buildObjectNode(s.val,e,s.attrStr,i)}function Lt(t){return this.options.indentBy.repeat(t)}function Rt(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}Nt.prototype.build=function(t){return this.options.preserveOrder?zt(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0).val)},Nt.prototype.j2x=function(t,e){let i="",s="";for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n))if(void 0===t[n])this.isAttribute(n)&&(s+="");else if(null===t[n])this.isAttribute(n)?s+="":"?"===n[0]?s+=this.indentate(e)+"<"+n+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+n+"/"+this.tagEndChar;else if(t[n]instanceof Date)s+=this.buildTextValNode(t[n],n,"",e);else if("object"!=typeof t[n]){const r=this.isAttribute(n);if(r)i+=this.buildAttrPairStr(r,""+t[n]);else if(n===this.options.textNodeName){let e=this.options.tagValueProcessor(n,""+t[n]);s+=this.replaceEntitiesValue(e)}else s+=this.buildTextValNode(t[n],n,"",e)}else if(Array.isArray(t[n])){const i=t[n].length;let r="",o="";for(let a=0;a<i;a++){const i=t[n][a];if(void 0===i);else if(null===i)"?"===n[0]?s+=this.indentate(e)+"<"+n+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+n+"/"+this.tagEndChar;else if("object"==typeof i)if(this.options.oneListGroup){const t=this.j2x(i,e+1);r+=t.val,this.options.attributesGroupName&&i.hasOwnProperty(this.options.attributesGroupName)&&(o+=t.attrStr)}else r+=this.processTextOrObjNode(i,n,e);else if(this.options.oneListGroup){let t=this.options.tagValueProcessor(n,i);t=this.replaceEntitiesValue(t),r+=t}else r+=this.buildTextValNode(i,n,"",e)}this.options.oneListGroup&&(r=this.buildObjectNode(r,n,o,e)),s+=r}else if(this.options.attributesGroupName&&n===this.options.attributesGroupName){const e=Object.keys(t[n]),s=e.length;for(let r=0;r<s;r++)i+=this.buildAttrPairStr(e[r],""+t[n][e[r]])}else s+=this.processTextOrObjNode(t[n],n,e);return{attrStr:i,val:s}},Nt.prototype.buildAttrPairStr=function(t,e){return e=this.options.attributeValueProcessor(t,""+e),e=this.replaceEntitiesValue(e),this.options.suppressBooleanAttributes&&"true"===e?" "+t:" "+t+'="'+e+'"'},Nt.prototype.buildObjectNode=function(t,e,i,s){if(""===t)return"?"===e[0]?this.indentate(s)+"<"+e+i+"?"+this.tagEndChar:this.indentate(s)+"<"+e+i+this.closeTag(e)+this.tagEndChar;{let n="</"+e+this.tagEndChar,r="";return"?"===e[0]&&(r="?",n=""),!i&&""!==i||-1!==t.indexOf("<")?!1!==this.options.commentPropName&&e===this.options.commentPropName&&0===r.length?this.indentate(s)+`\x3c!--${t}--\x3e`+this.newLine:this.indentate(s)+"<"+e+i+r+this.tagEndChar+t+this.indentate(s)+n:this.indentate(s)+"<"+e+i+r+">"+t+n}},Nt.prototype.closeTag=function(t){let e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`></${t}`,e},Nt.prototype.buildTextValNode=function(t,e,i,s){if(!1!==this.options.cdataPropName&&e===this.options.cdataPropName)return this.indentate(s)+`<![CDATA[${t}]]>`+this.newLine;if(!1!==this.options.commentPropName&&e===this.options.commentPropName)return this.indentate(s)+`\x3c!--${t}--\x3e`+this.newLine;if("?"===e[0])return this.indentate(s)+"<"+e+i+"?"+this.tagEndChar;{let n=this.options.tagValueProcessor(e,t);return n=this.replaceEntitiesValue(n),""===n?this.indentate(s)+"<"+e+i+this.closeTag(e)+this.tagEndChar:this.indentate(s)+"<"+e+i+">"+n+"</"+e+this.tagEndChar}},Nt.prototype.replaceEntitiesValue=function(t){if(t&&t.length>0&&this.options.processEntities)for(let e=0;e<this.options.entities.length;e++){const i=this.options.entities[e];t=t.replace(i.regex,i.val)}return t};var Ft={XMLParser:Ot,XMLValidator:T,XMLBuilder:Nt};class Vt{}e(Vt,"parser",new Ft.XMLParser({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0})),e(Vt,"builder",new Ft.XMLBuilder({attributeNamePrefix:"$",ignoreAttributes:!1,suppressBooleanAttributes:!1}));class jt{static join(t){const e={};for(const i of t)for(const t in i)if(e[t])for(const s of i[t])e[t].add(s);else e[t]=new Set(i[t]);return e}static intersect(t){if(0===t.length)return{};let e=jt.clone(t[0]);for(let i=1;i<t.length;i++){const s=t[i],n={};for(const t in e)if(s[t]){const i=new Set;for(const n of e[t])s[t].has(n)&&i.add(n);i.size>0&&(n[t]=i)}e=n}return e}static clone(t){const e={};for(const i in t)e[i]=new Set(t[i]);return e}static remove(t,e,i=!1){i&&(t=jt.clone(t));for(const i in e)if(t[i]){for(const s of e[i])t[i].delete(s);0===t[i].size&&delete t[i]}}static add(t,e,i=!1){i&&(t=jt.clone(t));for(const i in e)if(t[i])for(const s of e[i])t[i].add(s);else t[i]=new Set(e[i])}static append(t,e,...i){let s=t[e];s||(s=new Set,t[e]=s);for(const t of i)s.add(t)}static isEqual(t,e){const i=Object.keys(t),s=Object.keys(e);if(i.length!==s.length)return!1;for(const s of i){if(!e[s])return!1;if(t[s].size!==e[s].size)return!1;for(const i of t[s])if(!e[s].has(i))return!1}return!0}static isEmpty(t){return 0===Object.values(t).reduce((t,e)=>t+e.size,0)}static toRaw(t){const e={};for(const i in t)e[i]=Array.from(t[i]);return e}static fromRaw(t){const e={};for(const i in t)e[i]=new Set(t[i]);return e}}class Ht extends Map{constructor(t){super(t),e(this,"onItemSet",new h),e(this,"onItemUpdated",new h),e(this,"onItemDeleted",new h),e(this,"onCleared",new h),e(this,"guard",()=>!0)}clear(){super.clear(),this.onCleared.trigger()}set(t,e){const i=this.has(t);if(!(this.guard??(()=>!0))(t,e))return this;const s=super.set(t,e);return i?(this.onItemUpdated||(this.onItemUpdated=new h),this.onItemUpdated.trigger({key:t,value:e})):(this.onItemSet||(this.onItemSet=new h),this.onItemSet.trigger({key:t,value:e})),s}add(t){const e=v.create();return this.set(e,t),e}delete(t){const e=super.delete(t);return e&&this.onItemDeleted.trigger(t),e}dispose(){this.clear(),this.onItemSet.reset(),this.onItemDeleted.reset(),this.onCleared.reset()}}class Zt{static isEntry(t){return new Set(["Boolean","Color","Text","Number","Select","Vector3","TextSet","None"]).has(t.type)}static copySchema(t,e={}){for(const i in t){const s=t[i];this.isEntry(s)?e[i]=this.copyEntry(s):(e[i]={},this.copySchema(s,e[i]))}return e}static copyEntry(t){if("Boolean"===t.type){const e=t;return{type:e.type,value:e.value}}if("Color"===t.type){const e=t;return{type:e.type,value:e.value.clone()}}if("Text"===t.type){const e=t;return{type:e.type,value:e.value}}if("Number"===t.type){const e=t;return{type:e.type,value:e.value,min:e.min,max:e.max,interpolable:e.interpolable}}if("Select"===t.type){const e=t;return{type:e.type,value:e.value,multiple:e.multiple,options:new Set(e.options)}}if("Vector3"===t.type){const e=t;return{type:e.type,value:e.value.clone()}}if("TextSet"===t.type){const e=t;return{type:e.type,value:new Set(e.value)}}if("None"===t.type){const e=t;return{type:e.type,value:e.value}}throw new Error("Invalid entry!")}}class $t{constructor(t,i,s,n){e(this,"_component"),e(this,"name"),e(this,"uuid"),this._component=t,this.name=s,this.uuid=n??v.create();i.get(Yt).list.set(this.uuid,this)}get controls(){return Zt.copySchema(this._config)}set(t){for(const e in t)if(e in this){this[e]=t[e].value}}export(t=this._config,e={}){for(const i in t){const s=t[i];if(Zt.isEntry(s))if("Color"===s.type){const{r:t,g:n,b:r}=s.value;e[i]={...s,value:{r:t,g:n,b:r}}}else if("Vector3"===s.type){const{x:t,y:n,z:r}=s.value;e[i]={...s,value:{x:t,y:n,z:r}}}else if("TextSet"===s.type){const t=Array.from(s.value);e[i]={...s,value:t}}else if("Select"===s.type){const t=Array.from(s.options);e[i]={...s,options:t}}else e[i]={...s};else e[i]={},this.export(s,e[i])}return e}import(t,e={},i=!0){for(const i in t){const s=t[i];if(Zt.isEntry(s))if("Color"===s.type){const{r:t,g:n,b:r}=s.value;e[i]={...s,value:new a.Color(t,n,r)}}else if("Vector3"===s.type){const{x:t,y:n,z:r}=s.value;e[i]={...s,value:new a.Vector3(t,n,r)}}else"TextSet"===s.type?e[i]={...s,value:new Set(s.value)}:"Select"===s.type?e[i]={...s,options:new Set(s.options)}:e[i]={...s};else e[i]={},this.import(s,e[i],!1)}i&&this.set(e)}}const Wt=class t extends d{constructor(s){super(s),e(this,"list",new i.DataMap),e(this,"enabled",!0),s.add(t.uuid,this)}};e(Wt,"uuid","b8c764e0-6b24-4e77-9a32-35fa728ee5b4");let Yt=Wt;class Gt{constructor(t){e(this,"_event"),e(this,"_position",new a.Vector2),e(this,"onDisposed",new h),e(this,"updateMouseInfo",t=>{this._event=t}),this.dom=t,this.setupEvents(!0)}get position(){return this.updatePosition(!1),this._position.clone()}get rawPosition(){return this.updatePosition(!0),this._position.clone()}dispose(){this.setupEvents(!1),this.onDisposed.trigger(),this.onDisposed.reset()}updatePosition(t){if(this._event){const e=this.dom.getBoundingClientRect();this._position.x=this.getPositionX(e,this._event,t),this._position.y=this.getPositionY(e,this._event,t)}}getPositionY(t,e,i){const s=this.getDataObject(e);return i?s.clientY:-(s.clientY-t.top)/(t.bottom-t.top)*2+1}getPositionX(t,e,i){const s=this.getDataObject(e);return i?s.clientX:(s.clientX-t.left)/(t.right-t.left)*2-1}getDataObject(t){return t instanceof MouseEvent?t:t.touches[0]}setupEvents(t){t?(this.dom.addEventListener("pointermove",this.updateMouseInfo),this.dom.addEventListener("touchstart",this.updateMouseInfo)):(this.dom.removeEventListener("pointermove",this.updateMouseInfo),this.dom.removeEventListener("touchstart",this.updateMouseInfo))}}const Xt=class t extends d{constructor(i){super(i),e(this,"onDisposed",new h),e(this,"onBeforeDispose",new h),e(this,"onFragmentsLoaded",new h),e(this,"baseCoordinationModel",""),e(this,"baseCoordinationMatrix",new a.Matrix4),e(this,"enabled",!0),e(this,"_core"),this.components.add(t.uuid,this)}get initialized(){return!!this._core}get list(){return this.core.models.list}get core(){if(!this._core)throw new Error("FragmentsManager not initialized. Call init() first.");return this._core}get _hasCoordinationModel(){return""!==this.baseCoordinationModel}dispose(){this.onBeforeDispose.trigger(),this._core&&(this.core.dispose(),this._core=void 0),this.baseCoordinationModel="",this.onFragmentsLoaded.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}init(t,e){this._core=new i.FragmentsModels(t,e),this.core.onModelLoaded.add(async()=>{if(this._hasCoordinationModel)return;const t=[...this.list.values()][0];t&&(this.baseCoordinationModel=t.modelId,this.baseCoordinationMatrix=await t.getCoordinationMatrix())}),this.list.onItemDeleted.add(()=>{this.list.size>0||(this.baseCoordinationModel="",this.baseCoordinationMatrix=new a.Matrix4)})}async raycast(t){const e=[];for(const i of this.core.models.list.values())if(t.snappingClasses&&t.snappingClasses.length>0){const s=await i.raycastWithSnapping(t);if(s&&s.length>0)e.push(s[0]);else{const s=await i.raycast(t);s&&e.push(s)}}else{const s=await i.raycast(t);s&&e.push(s)}if(await Promise.all(e),0===e.length)return;let i=e[0],s=i.distance;for(let t=1;t<e.length;t++)e[t].distance<s&&(s=e[t].distance,i=e[t]);return i}async getPositions(t){const e=[],i=async(t,i)=>{const s=await t.getPositions(i);for(const t of s)e.push(t)},s=[];for(const e in t){const n=this.core.models.list.get(e);n&&s.push(i(n,Array.from(t[e])))}return await Promise.all(s),e}async getBBoxes(t){const e=[],i=async(t,i)=>{const s=await t.getBoxes(i);if(s)for(const t of s)e.push(t)},s=[];for(const e in t){const n=this.core.models.list.get(e);n&&s.push(i(n,Array.from(t[e])))}return await Promise.all(s),e}async highlight(t,e){await this.forEachModel(e,"highlight",t)}async getData(t,e){const i={};for(const[s,n]of Object.entries(t)){const t=this.list.get(s);if(!t)continue;if(0===n.size){i[s]=[];continue}const r=await t.getItemsData([...n],e);i[s]=r}return i}async resetHighlight(t){await this.forEachModel(t,"resetHighlight")}async forEachModel(t,e,...i){const s={};if(t)for(const e in t){const i=t[e];s[e]=Array.from(i)}else for(const t of this.core.models.list.keys())s[t]=void 0;const n=[];for(const t in s){const r=this.core.models.list.get(t);if(r){const o=s[t],a=r[e](o,...i);n.push(a)}}await Promise.all(n)}async guidsToModelIdMap(t){const e={};for(const[i,s]of this.list){const n=(await s.getLocalIdsByGuids([...t])).filter(t=>null!==t);e[i]=new Set(n)}return e}async modelIdMapToGuids(t){const e=[];for(const[i,s]of Object.entries(t)){const t=this.list.get(i);if(!t)continue;const n=(await t.getGuidsByLocalIds([...s])).filter(t=>null!==t);e.push(...n)}return e}applyBaseCoordinateSystem(t,e){const i=new a.Matrix4;return e&&i.copy(e.clone()).invert(),i.multiply(this.baseCoordinationMatrix),t.applyMatrix4(i),i}};e(Xt,"uuid","fef46874-46a3-461b-8c44-2922ab77c806");let qt=Xt;class Qt{constructor(){e(this,"wasm",{path:"",absolute:!1,logLevel:l.LogLevel.LOG_LEVEL_OFF}),e(this,"webIfc",{COORDINATE_TO_ORIGIN:!0}),e(this,"autoSetWasm",!0),e(this,"customLocateFileHandler",null)}}const Kt=class t extends d{constructor(i){super(i),e(this,"onDisposed",new h),e(this,"onIfcStartedLoading",new h),e(this,"onIfcImporterInitialized",new h),e(this,"onSetup",new h),e(this,"settings",new Qt),e(this,"webIfc",new l.IfcAPI),e(this,"enabled",!0),this.components.add(t.uuid,this)}dispose(){this.webIfc=null,this.onDisposed.trigger(t.uuid),this.onDisposed.reset()}async setup(t){this.settings={...this.settings,...t},this.settings.autoSetWasm&&await this.autoSetWasm(),this.onSetup.trigger()}async load(t,e,i,s){const n=this.components.get(qt);if(!n.initialized)throw new Error("You need to initialize fragments first.");this.settings.autoSetWasm&&await this.autoSetWasm(),n.core.settings.autoCoordinate=e;const r=new o.IfcImporter;r.wasm.path=this.settings.wasm.path,r.wasm.absolute=this.settings.wasm.absolute,r.webIfcSettings=this.settings.webIfc,this.onIfcImporterInitialized.trigger(r),(null==s?void 0:s.instanceCallback)&&s.instanceCallback(r);const a=await r.process({...null==s?void 0:s.processData,bytes:t});return await n.core.load(a,{modelId:i,userData:null==s?void 0:s.userData})}async readIfcFile(t){const{path:e,absolute:i,logLevel:s}=this.settings.wasm;return this.webIfc.SetWasmPath(e,i),await this.webIfc.Init(this.settings.customLocateFileHandler||void 0),s&&this.webIfc.SetLogLevel(s),this.webIfc.OpenModel(t,this.settings.webIfc)}cleanUp(){try{this.webIfc.Dispose()}catch(t){console.log("Web-ifc wasn't disposed.")}this.webIfc=null,this.webIfc=new l.IfcAPI}async autoSetWasm(){const t=await fetch(`https://unpkg.com/@thatopen/components@${Kn.release}/package.json`);if(!t.ok)return void console.warn("Couldn't get openbim-components package.json. Set wasm settings manually.");const e=await t.json();if("web-ifc"in e.peerDependencies){const t=e.peerDependencies["web-ifc"];this.settings.wasm.path=`https://unpkg.com/web-ifc@${t}/`,this.settings.wasm.absolute=!0}else console.warn("Couldn't get web-ifc from peer dependencies in openbim-components. Set wasm settings manually.")}};e(Kt,"uuid","a659add7-1418-4771-a0d6-7d4d438e4624");let Jt=Kt;const te=class t extends d{constructor(i){super(i),e(this,"enabled",!0),this.components.add(t.uuid,this)}async set(t,e){const i=this.components.get(qt),s=[];if(e)for(const[n,r]of Object.entries(e)){const e=i.list.get(n);e&&s.push(e.setVisible([...r],t))}else for(const e of i.list.values())s.push(e.setVisible(void 0,t));await Promise.all(s),await i.core.update(!0)}async isolate(t){await Promise.all([this.set(!1),this.set(!0,t)])}async toggle(t){const e=[],i=this.components.get(qt);for(const[s,n]of Object.entries(t)){const t=i.list.get(s);t&&e.push(t.toggleVisible([...n]))}await Promise.all(e),await i.core.update(!0)}async getVisibilityMap(t,e){const i=[],s=[],n=this.components.get(qt);if(e)for(const r of e){const e=n.list.get(r);e&&(i.push(e.modelId),s.push(e.getItemsByVisibility(t)))}else for(const e of n.list.values())i.push(e.modelId),s.push(e.getItemsByVisibility(t));const r=await Promise.all(s),o={};for(const[t,e]of i.entries())o[e]=r[t];return o}};e(te,"uuid","dd9ccf2d-8a21-4821-b7f6-2949add16a29");let ee=te;const ie=class t extends d{constructor(i){super(i),e(this,"enabled",!0),e(this,"onDisposed",new h),e(this,"list",new o.DataSet),this.components.add(t.uuid,this)}dispose(e=!0){this.list.clear(),this.onDisposed.trigger(t.uuid),e&&(this.onDisposed.reset(),this.list.eventsEnabled=!1,this.list.dispose())}get(){const t=new a.Box3;for(const e of this.list)t.union(e);return t}async addFromModelIdMap(t){const e=this.components.get(qt),i=new a.Box3;for(const[s,n]of Object.entries(t)){const t=e.list.get(s);if(!t)continue;const r=await t.getMergedBox([...n]);i.union(r)}this.list.add(i)}addFromModels(t){const e=this.components.get(qt);for(const[i,s]of e.list)t&&!t.some(t=>t.test(i))||this.list.add(s.box)}async getCenter(t){this.list.clear(),await this.addFromModelIdMap(t);const e=this.get();this.list.clear();const i=new a.Vector3;return e.getCenter(i),i}async getCameraOrientation(t,e=1){const i=this.components.get(qt);this.list.clear();for(const[t,e]of i.list)this.list.add(e.box);const s=this.get();this.list.clear();const n=new a.Vector3;s.getCenter(n);const r=new a.Vector3;s.getSize(r);const o=Math.max(r.x,r.y,r.z)*e,l=new a.Vector3;switch(t){case"front":default:l.set(n.x,n.y,n.z+o);break;case"back":l.set(n.x,n.y,n.z-o);break;case"left":l.set(n.x-o,n.y,n.z);break;case"right":l.set(n.x+o,n.y,n.z);break;case"top":l.set(n.x,n.y+o,n.z);break;case"bottom":l.set(n.x,n.y-o,n.z)}return{position:l,target:n}}};e(ie,"uuid","d1444724-dba6-4cdd-a0c7-68ee1450d166");let se=ie;class ne{constructor(t,i){e(this,"name","Query"),e(this,"customData",{}),e(this,"_components"),e(this,"_queries",[]),e(this,"_aggregation","exclusive"),e(this,"result",null),e(this,"cache",!0),e(this,"serializeQueryParameters",t=>{var e;return{categories:null==(e=t.categories)?void 0:e.map(t=>t.source),attributes:t.attributes?{aggregation:t.attributes.aggregation,queries:t.attributes.queries.map(this.serializeAttributeQuery)}:void 0,relation:t.relation?{name:t.relation.name,query:t.relation.query?this.serializeQueryParameters(t.relation.query):void 0}:void 0}}),e(this,"deserializeQueryParameters",t=>{var e;return{categories:null==(e=t.categories)?void 0:e.map(t=>new RegExp(t)),attributes:t.attributes?{aggregation:t.attributes.aggregation,queries:t.attributes.queries.map(this.deserializeAttributeQuery)}:void 0,relation:t.relation?{name:t.relation.name,query:t.relation.query?this.deserializeQueryParameters(t.relation.query):void 0}:void 0}}),this._components=t,this.queries=i}set queries(t){this._queries=t,this.clearCache()}get queries(){return this._queries}set aggregation(t){t!==this._aggregation&&this.clearCache(),this._aggregation=t}get aggregation(){return this._aggregation}async test(t){const{modelIds:e,force:i}={force:!1,...t};if(this.result&&!i)return this.result;const s=this._components.get(oe),n=await s.getItems(this.queries,{modelIds:e,aggregation:this.aggregation});return this.cache&&(this.result=n),n}clearCache(){this.result=null}serializeAttributeQuery(t){let e;e=Array.isArray(t.value)?t.value.map(t=>t.source):t.value instanceof RegExp?t.value.source:t.value;return{name:t.name.source,value:e,type:t.type instanceof RegExp?t.type.source:t.type,negate:t.negate,itemIds:t.itemIds}}toJSON(){return{guid:this._components.get(oe).list.getKey(this)??v.create(),name:this.name,customData:this.customData,queries:this.queries.map(this.serializeQueryParameters),aggregation:this.aggregation,cache:this.cache}}deserializeAttributeQuery(t){let e;e=Array.isArray(t.value)?t.value.map(t=>new RegExp(t)):"string"==typeof t.value?new RegExp(t.value):t.value;return{name:new RegExp(t.name),value:e,type:t.type?new RegExp(t.type):void 0,negate:t.negate,itemIds:t.itemIds}}fromJSON(t){return this.name=t.name,this.customData=t.customData,this.aggregation=t.aggregation,this.cache=t.cache,this.queries=t.queries.map(this.deserializeQueryParameters),this}}const re=class t extends d{constructor(i){super(i),e(this,"enabled",!0),e(this,"list",new o.DataMap),i.add(t.uuid,this)}async getItems(t,e){let i;if(e){const{modelIds:t,items:s}=e;if(s){const t=Object.keys(s);t.length>0&&(i=t.map(t=>new RegExp(`^${t}$`)))}else t&&(i=t)}const s=(null==e?void 0:e.aggregation)??"exclusive",n=this.components.get(qt),r=await Promise.all(t.map(async t=>{const s={};return await Promise.all(Array.from(n.list).map(async([n,r])=>{var o;if(i&&!i.some(t=>t.test(n)))return;const a=null==(o=null==e?void 0:e.items)?void 0:o[n],l=await r.getItemsByQuery(t,{localIds:a?[...a]:void 0});s[n]=new Set(l)})),s}));return"inclusive"===s?jt.join(r):jt.intersect(r)}create(t,e){const i=new ne(this.components,e);return this.list.set(t,i),i}async addFromCategories(t){const e=new Set,i=this.components.get(qt);for(const[s,n]of i.list){if(t&&!t.some(t=>t.test(s)))continue;const i=(await n.getItemsWithGeometryCategories()).filter(t=>null!==t),r=new Set(i);for(const t of r)this.list.has(t)||(this.create(t,[{categories:[new RegExp(`^${t}$`)]}]),e.add(t))}return[...e]}import(t){const{data:e}=t,i=[];if(!e)return i;for(const t of e){const e=this.create(t.guid,[]);e.fromJSON(t),i.push(e)}return i}export(){const t=[];for(const[e,i]of this.list.entries()){const s={...i.toJSON(),name:e};t.push(s)}return{data:t}}};e(re,"uuid","0da7ad77-f734-42ca-942f-a074adfd1e3a");let oe=re;const ae=class t extends d{constructor(i){super(i),e(this,"enabled",!0),e(this,"onDisposed",new h),e(this,"list",new o.DataMap),e(this,"defaultSaveFunction",t=>"value"in t.Name?t.Name.value:null),e(this,"onBeforeFragmentsDispose",async t=>{const{key:e,value:i}=t,s=await i.getLocalIds(),n={[e]:new Set(s)};this.removeItems(n)}),i.add(t.uuid,this),this.setupEvents();i.get(qt).list.onBeforeDelete.add(this.onBeforeFragmentsDispose)}setupEvents(){this.list.onBeforeDelete.add(({value:t})=>t.dispose())}getClassificationGroups(t){let e=this.list.get(t);return e||(e=new o.DataMap,this.list.set(t,e)),e}getModelItems(t,e,i){const{map:s}=this.getGroupData(t,e);let n=s[i];return n||(n=new Set,s[i]=n),n}getGroupData(t,e){const i=this.components.get(oe),s=this.getClassificationGroups(t);let n=s.get(e);return n||(n={map:{},get:()=>new Promise(t=>{if(n)if(n.query){const{name:e,config:s}=n.query,r=i.list.get(e);if(!r)throw new Error("Classifier: the query name associated with the group doesn't exist in the ItemsFinder component");r.test(s).then(e=>{if(!n)return void t({});const i=jt.join([e,n.map]);t(i)})}else t(n.map);else t({})})},s.set(e,n)),n}async aggregateItems(t,e,i){const s=(null==i?void 0:i.data)??void 0,n=(null==i?void 0:i.aggregationCallback)??this.defaultSaveFunction,r=this.components.get(qt),o=this.components.get(oe),a=await o.getItems([e],{modelIds:null==i?void 0:i.modelIds});for(const[e,i]of Object.entries(a)){const o=r.list.get(e);if(!o)continue;const a=(i,...s)=>{const n=this.getModelItems(t,i,e);for(const t of s)n.add(t)},l=await o.getItemsData([...i],s);for(const t of l)n(t,a)}}addGroupItems(t,e,i){const{map:s}=this.getGroupData(t,e);jt.add(s,i)}setGroupQuery(t,e,i){this.getGroupData(t,e).query=i}async find(t){const e=[];for(const[i,s]of Object.entries(t)){const t=[],n=this.list.get(i);if(!n)continue;for(const e of s){const i=n.get(e);if(!i)continue;const s=await i.get();t.push(s)}const r=jt.join(t);e.push(r)}return jt.intersect(e)}async aggregateItemRelations(t,e,i,s){const n=(null==s?void 0:s.attribute)??"Name",r={relations:{[i]:{attributes:!0,relations:!1}}};await this.aggregateItems(t,e,{modelIds:null==s?void 0:s.modelIds,data:r,aggregationCallback:(t,e)=>{if(!(null==t?void 0:t[n]))return;const s=t[n];if(!("value"in s))return;const r=t[i];if(Array.isArray(r))for(const t of r)"value"in t._localId&&e(s.value,t._localId.value)}})}async byIfcBuildingStorey(t){await this.aggregateItemRelations((null==t?void 0:t.classificationName)??"Storeys",{categories:[/BUILDINGSTOREY/]},"ContainsElements",{modelIds:null==t?void 0:t.modelIds})}async byCategory(t){const e=this.components.get(oe),i=await e.addFromCategories(null==t?void 0:t.modelIds);for(const e of i)this.setGroupQuery((null==t?void 0:t.classificationName)??"Categories",e,{name:e})}dispose(){this.list.clear();this.components.get(qt).list.onBeforeDelete.remove(this.onBeforeFragmentsDispose),this.onDisposed.trigger()}removeItems(t,e){if(e&&e.classificationName){const i=this.list.get(e.classificationName);if(!i)return;if(e.groupName){if(!i.get(e.groupName))return}for(const[,e]of i)jt.remove(e.map,t);return}for(const[,e]of this.list.entries())for(const[,i]of e)jt.remove(i.map,t)}async byModel(t){const e=this.components.get(qt),i=(null==t?void 0:t.classificationName)??"Models";for(const[s,n]of e.list){if(t&&t.modelIds&&!t.modelIds.some(t=>t.test(s)))continue;const e=await n.getItemsIdsWithGeometry(),r={[s]:new Set(e)};this.getGroupData(i,s),this.addGroupItems(i,s,r)}}};e(ae,"uuid","e25a7f3c-46c4-4a14-9d3d-5115f24ebeb7");let le=ae;class he{constructor(t,i){e(this,"enabled",!0),e(this,"components"),e(this,"onDisposed",new h),e(this,"mouse"),e(this,"world"),e(this,"debugMode",!1),e(this,"colorToModelId",new Map),e(this,"modelIdToColor",new Map),e(this,"renderTarget"),e(this,"renderTargetSize",new a.Vector2),e(this,"debugCanvas"),e(this,"debugContainer"),e(this,"colorMaterials",new Map),e(this,"originalMaterials",new Map),e(this,"originalLodColors",new Map),e(this,"colorsNeedUpdate",!0);const s=i.renderer;if(!s)throw new Error("A renderer is needed for the FastModelPicker to work!");this.world=i,this.mouse=new Gt(s.three.domElement),this.components=t,this.setupRenderTarget(),this.setupFragmentListeners()}setupFragmentListeners(){const t=this.components.get(qt);t.list.onItemSet.add(()=>{this.colorsNeedUpdate=!0}),t.list.onItemDeleted.add(()=>{this.colorsNeedUpdate=!0})}setupRenderTarget(){const t=this.world.renderer.three.getSize(new a.Vector2);this.renderTargetSize.copy(t),this.renderTarget=new a.WebGLRenderTarget(t.x,t.y),this.renderTarget.texture.format=a.RGBAFormat,this.renderTarget.texture.type=a.UnsignedByteType,this.debugMode&&this.setupDebugCanvas(),this.world.renderer.onResize.add(t=>{this.renderTargetSize.copy(t),this.renderTarget.setSize(t.x,t.y),this.debugCanvas&&(this.debugCanvas.width=t.x,this.debugCanvas.height=t.y)})}setupDebugCanvas(){if(this.debugCanvas)return;const t=this.world.renderer.three.getSize(new a.Vector2);this.debugContainer=document.createElement("div"),this.debugContainer.style.position="fixed",this.debugContainer.style.top="10px",this.debugContainer.style.right="10px",this.debugContainer.style.width="300px",this.debugContainer.style.height="300px",this.debugContainer.style.border="2px solid #fff",this.debugContainer.style.backgroundColor="#000",this.debugContainer.style.zIndex="10000",this.debugContainer.style.pointerEvents="none",this.debugCanvas=document.createElement("canvas"),this.debugCanvas.width=t.x,this.debugCanvas.height=t.y,this.debugCanvas.style.width="100%",this.debugCanvas.style.height="100%",this.debugCanvas.style.imageRendering="pixelated",this.debugContainer.appendChild(this.debugCanvas),document.body.appendChild(this.debugContainer)}generateColorForModel(t){let e=0;for(let i=0;i<t.length;i++)e=(e<<5)-e+t.charCodeAt(i),e&=e;let i=Math.abs(e)%16777215;0===i&&(i=1);const s=i>>16&255||1,n=i>>8&255||1,r=255&i||1;return new a.Color(s/255,n/255,r/255)}colorToId(t){return Math.round(255*t.r)<<16|Math.round(255*t.g)<<8|Math.round(255*t.b)}assignColors(){const t=this.components.get(qt);if(t.initialized){if(!this.colorsNeedUpdate){const e=new Set(t.list.keys()),i=new Set(this.modelIdToColor.keys());(e.size!==i.size||[...e].some(t=>!i.has(t)))&&(this.colorsNeedUpdate=!0)}if(this.colorsNeedUpdate){this.colorToModelId.clear(),this.modelIdToColor.clear();for(const t of this.colorMaterials.values())t.dispose();this.colorMaterials.clear();for(const[e]of t.list){const t=this.generateColorForModel(e),i=this.colorToId(t);this.colorToModelId.set(i,e),this.modelIdToColor.set(e,t);const s=new a.MeshBasicMaterial({color:t,depthTest:!0,depthWrite:!0});this.colorMaterials.set(e,s)}this.colorsNeedUpdate=!1}}}applyColorMaterials(){const t=this.components.get(qt);if(t.initialized)for(const[e,i]of t.list){const t=this.colorMaterials.get(e);t&&i.object.traverse(e=>{if(e instanceof a.Mesh){if("isLODGeometry"in e.geometry){const i=e.material[0].uniforms.lodColor;return this.originalLodColors.has(i)||this.originalLodColors.set(i,i.value),void(i.value=t.color)}this.originalMaterials.has(e)||this.originalMaterials.set(e,e.material),e.material=t}})}}restoreOriginalMaterials(){for(const[t,e]of this.originalMaterials)t.material=e;for(const[t,e]of this.originalLodColors)t.value=e;this.originalMaterials.clear()}renderColorCoded(){if(!this.renderTarget||!this.world.renderer)throw new Error("Render target not initialized!");const t=this.world.renderer.three,e=this.world.scene.three,i=this.world.camera.three,s=t.getRenderTarget(),n=t.autoClear,r=new a.Color,o=t.getClearAlpha();t.getClearColor(r),this.applyColorMaterials(),t.setRenderTarget(this.renderTarget),t.autoClear=!0,t.setClearColor(0,1),t.clear(!0,!0,!1),t.render(e,i),t.setRenderTarget(s),t.autoClear=n,t.setClearColor(r,o),this.restoreOriginalMaterials(),this.debugMode&&this.debugCanvas&&this.updateDebugCanvas()}updateDebugCanvas(){if(!this.debugCanvas||!this.renderTarget||!this.world.renderer)return;const t=this.world.renderer.three,e=this.renderTargetSize,i=new Uint8Array(e.x*e.y*4);t.readRenderTargetPixels(this.renderTarget,0,0,e.x,e.y,i);const s=this.debugCanvas.getContext("2d");if(!s)return;const n=s.createImageData(e.x,e.y),r=4*e.x;for(let t=0;t<e.y;t++){const s=t*r,o=(e.y-1-t)*r;n.data.set(i.subarray(s,s+r),o)}s.putImageData(n,0,0)}async getModelAt(t){if(!this.renderTarget||!this.world.renderer)throw new Error("Render target not initialized!");const e=this.components.get(qt);if(!e.initialized||0===e.list.size)return null;this.assignColors(),this.renderColorCoded();const i=t||this.mouse.position,s=this.renderTargetSize,n=Math.floor(.5*(i.x+1)*s.x),r=Math.floor(.5*(i.y+1)*(s.y-1)),o=Math.max(0,Math.min(s.x-1,n)),a=Math.max(0,Math.min(s.y-1,r)),l=this.world.renderer.three,h=new Uint8Array(4);l.readRenderTargetPixels(this.renderTarget,o,a,1,1,h);const c=h[0]<<16|h[1]<<8|h[2];return this.colorToModelId.get(c)||null}setDebugMode(t){this.debugMode=t,t?this.setupDebugCanvas():this.removeDebugCanvas()}removeDebugCanvas(){this.debugContainer&&(this.debugContainer.remove(),this.debugContainer=void 0,this.debugCanvas=void 0)}dispose(){this.mouse.dispose(),this.removeDebugCanvas();for(const t of this.colorMaterials.values())t.dispose();this.colorMaterials.clear(),this.renderTarget&&this.renderTarget.dispose(),this.colorToModelId.clear(),this.modelIdToColor.clear(),this.originalMaterials.clear(),this.originalLodColors.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}}const ce=class t extends d{constructor(i){super(i),e(this,"enabled",!0),e(this,"list",new Map),e(this,"onDisposed",new h),i.add(t.uuid,this)}get(t){if(this.list.has(t.uuid))return this.list.get(t.uuid);const e=new he(this.components,t);return this.list.set(t.uuid,e),t.onDisposed.add(()=>{this.delete(t)}),e}delete(t){const e=this.list.get(t.uuid);e&&e.dispose(),this.list.delete(t.uuid)}dispose(){for(const[t,e]of this.list)e.dispose();this.list.clear(),this.onDisposed.trigger()}};e(ce,"uuid","4a82430c-7ff2-49ea-9401-60807502dad6");let de=ce;class ue{constructor(t,i){e(this,"enabled",!0),e(this,"components"),e(this,"onDisposed",new h),e(this,"mouse"),e(this,"three",new a.Raycaster),e(this,"world"),e(this,"useFastModelPicking",!1);const s=i.renderer;if(!s)throw new Error("A renderer is needed for the raycaster to work!");this.world=i,this.mouse=new Gt(s.three.domElement),this.components=t}dispose(){this.mouse.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}castRayToObjects(t=Array.from(this.world.meshes),e=this.mouse.position){if(!this.world)throw new Error("A world is needed to cast rays!");const i=this.world.camera.three;return this.three.setFromCamera(e,i),this.intersect(t)}async castRay(t){const e=null==t?void 0:t.snappingClasses,i=(null==t?void 0:t.items)??Array.from(this.world.meshes),s=(null==t?void 0:t.position)??this.mouse.position;if(!this.world)throw new Error("A world is needed to cast rays!");const n=this.world.camera.three,r=this.components.get(qt),o=this.world.renderer.three.domElement,a=this.mouse.rawPosition;let l=null;if(r.initialized){if(this.useFastModelPicking){const t=this.components.get(de).get(this.world),i=await t.getModelAt(s);if(i){const t=r.list.get(i);if(t)if(e&&e.length>0){const i=await t.raycastWithSnapping({camera:n,dom:o,mouse:a,snappingClasses:e});l=i&&i.length>0?i[0]:await t.raycast({camera:n,dom:o,mouse:a})}else l=await t.raycast({camera:n,dom:o,mouse:a})}}else l=await r.raycast({camera:n,dom:o,mouse:a,snappingClasses:e});if(0===i.length)return l}this.three.setFromCamera(s,n);const h=this.intersect(i);return l?h&&h.distance<l.distance?h:l:h}castRayFromVector(t,e,i=Array.from(this.world.meshes)){return this.three.set(t,e),this.intersect(i)}intersect(t=Array.from(this.world.meshes)){const e=this.three.intersectObjects(t),i=this.filterClippingPlanes(e);return i.length>0?i[0]:null}filterClippingPlanes(t){if(!this.world.renderer)throw new Error("Renderer not found!");const e=this.world.renderer.three;if(!e.clippingPlanes)return t;const i=e.clippingPlanes;return t.length<=0||!i||(null==i?void 0:i.length)<=0?t:t.filter(t=>i.every(e=>e.distanceToPoint(t.point)>0))}}const pe=class t extends d{constructor(i){super(i),e(this,"enabled",!0),e(this,"list",new Map),e(this,"onDisposed",new h),i.add(t.uuid,this)}get(t){if(this.list.has(t.uuid))return this.list.get(t.uuid);const e=new ue(this.components,t);return this.list.set(t.uuid,e),t.onDisposed.add(()=>{this.delete(t)}),e}delete(t){const e=this.list.get(t.uuid);e&&e.dispose(),this.list.delete(t.uuid)}dispose(){for(const[t,e]of this.list)e.dispose();this.list.clear(),this.onDisposed.trigger()}};e(pe,"uuid","d5d8bdf0-db25-4952-b951-b643af207ace");let fe=pe;class me extends c{constructor(){super(...arguments),e(this,"onCameraChanged",new h),e(this,"meshes",new Set),e(this,"onAfterUpdate",new h),e(this,"onBeforeUpdate",new h),e(this,"onDisposed",new h),e(this,"isDisposing",!1),e(this,"enabled",!0),e(this,"_dynamicAnchor",!1),e(this,"uuid",v.create()),e(this,"name"),e(this,"_scene"),e(this,"_camera"),e(this,"_renderer",null),e(this,"onPointerDown",async t=>{if(!this.camera.hasCameraControls())throw new Error("World: can't set dynamic anchor if the camera doesn't have controls.");const e=this.components.get(fe).get(this),i=await e.castRay();i&&i.point&&0===t.button&&this.camera.controls.setOrbitPoint(i.point.x,i.point.y,i.point.z)}),e(this,"_defaultCamera")}set dynamicAnchor(t){var e;const i=null==(e=this.renderer)?void 0:e.three.domElement.parentElement;if(!i)throw new Error("World: the renderer must have a parentElement to set dynamic anchoring.");t?(this.camera.controls&&(this.camera.controls.minDistance=.01),i.addEventListener("pointerdown",this.onPointerDown)):i.removeEventListener("pointerdown",this.onPointerDown)}get dynamicAnchor(){return this._dynamicAnchor}get defaultCamera(){if(!this._defaultCamera)throw new Error("World: there is no default camera defined.");return this._defaultCamera}set defaultCamera(t){this._defaultCamera=t}get scene(){if(!this._scene)throw new Error("No scene initialized!");return this._scene}set scene(t){this._scene=t,t.worlds.set(this.uuid,this),t.currentWorld=this,t.onWorldChanged.trigger({world:this,action:"added"})}get camera(){if(!this._camera)throw new Error("No camera initialized!");return this._camera}set camera(t){this._camera||(this.defaultCamera=t),this._camera=t,t.currentWorld=this,this.onCameraChanged.trigger(t)}get renderer(){return this._renderer}set renderer(t){this._renderer=t,t&&(t.worlds.set(this.uuid,this),t.currentWorld=this,t.onWorldChanged.trigger({world:this,action:"added"}))}useDefaultCamera(){this.camera=this.defaultCamera}update(t){this.enabled&&this._scene&&this._camera&&(this.scene.currentWorld=this,this.camera.currentWorld=this,this.renderer&&(this.renderer.currentWorld=this),this.onBeforeUpdate.trigger(),this.scene.isUpdateable()&&this.scene.update(t),this.camera.isUpdateable()&&this.camera.update(t),this.renderer&&this.renderer.update(t),this.onAfterUpdate.trigger())}dispose(t=!0){if(this.enabled=!1,this.isDisposing=!0,this.scene.onWorldChanged.trigger({world:this,action:"removed"}),this.camera.onWorldChanged.trigger({world:this,action:"removed"}),this.renderer&&this.renderer.onWorldChanged.trigger({world:this,action:"removed"}),t){const t=this.components.get(g);this.scene.dispose(),this.camera.isDisposeable()&&this.camera.dispose(),this.renderer&&this.renderer.dispose();for(const e of this.meshes)t.destroy(e);this.meshes.clear()}this._scene=null,this._camera=null,this._renderer=null;this.components.get(wi).list.delete(this.uuid),this.onDisposed.trigger(),this.onDisposed.reset()}}class ge{constructor(t,i){e(this,"_list"),e(this,"_scene"),this._list=t,this._scene=i}get color(){return this._list.directionalLight.color.value}set color(t){this._list.directionalLight.color.value=t;for(const[,e]of this._scene.directionalLights)e.color.copy(t)}get intensity(){return this._list.directionalLight.intensity.value}set intensity(t){this._list.directionalLight.intensity.value=t;for(const[,e]of this._scene.directionalLights)e.intensity=t}get position(){return this._list.directionalLight.position.value.clone()}set position(t){this._list.directionalLight.position.value=t;for(const[,e]of this._scene.directionalLights)e.position.copy(t)}}class _e{constructor(t,i){e(this,"_list"),e(this,"_scene"),this._list=t,this._scene=i}get color(){return this._list.ambientLight.color.value}set color(t){this._list.ambientLight.color.value=t;for(const[,e]of this._scene.ambientLights)e.color.copy(t)}get intensity(){return this._list.ambientLight.intensity.value}set intensity(t){this._list.ambientLight.intensity.value=t;for(const[,e]of this._scene.ambientLights)e.intensity=t}}class ye extends $t{constructor(){super(...arguments),e(this,"_config",{backgroundColor:{value:new a.Color,type:"Color"},ambientLight:{color:{type:"Color",value:new a.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2}},directionalLight:{color:{type:"Color",value:new a.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2},position:{type:"Vector3",value:new a.Vector3}}}),e(this,"ambientLight",new _e(this._config,this._component)),e(this,"directionalLight",new ge(this._config,this._component))}get backgroundColor(){return this._config.backgroundColor.value}set backgroundColor(t){this._config.backgroundColor.value=t,this._component.three.background=t}}class we extends _{constructor(t){super(t),e(this,"onSetup",new h),e(this,"isSetup",!1),e(this,"three"),e(this,"config",new ye(this,this.components,"Scene")),e(this,"_defaultConfig",{backgroundColor:new a.Color(2107698),directionalLight:{color:new a.Color("white"),intensity:1.5,position:new a.Vector3(5,10,3)},ambientLight:{color:new a.Color("white"),intensity:1}}),this.three=new a.Scene,this.three.background=new a.Color(2107698)}setup(t){const e={...this._defaultConfig,...t};this.config.backgroundColor=e.backgroundColor;const i=e.ambientLight;this.config.ambientLight.color=i.color,this.config.ambientLight.intensity=i.intensity;const s=e.directionalLight;this.config.directionalLight.color=s.color,this.config.directionalLight.intensity=s.intensity,this.config.directionalLight.position=s.position,this.deleteAllLights();const{color:n,intensity:r}=this.config.directionalLight,o=new a.DirectionalLight(n,r);o.position.copy(s.position);const{color:l,intensity:h}=this.config.directionalLight,c=new a.AmbientLight(l,h);this.three.add(o,c),this.directionalLights.set(o.uuid,o),this.ambientLights.set(c.uuid,c),this.isSetup=!0,this.onSetup.trigger()}dispose(){super.dispose();this.components.get(Yt).list.delete(this.config.uuid)}}var ve=(t=>(t[t.MANUAL=0]="MANUAL",t[t.AUTO=1]="AUTO",t))(ve||{});
2
- /*!
3
- * camera-controls
4
- * https://github.com/yomotsu/camera-controls
5
- * (c) 2017 @yomotsu
6
- * Released under the MIT License.
7
- */
8
- const be=1,xe=2,Te=4,Ce=Object.freeze({NONE:0,ROTATE:1,TRUCK:2,SCREEN_PAN:4,OFFSET:8,DOLLY:16,ZOOM:32,TOUCH_ROTATE:64,TOUCH_TRUCK:128,TOUCH_SCREEN_PAN:256,TOUCH_OFFSET:512,TOUCH_DOLLY:1024,TOUCH_ZOOM:2048,TOUCH_DOLLY_TRUCK:4096,TOUCH_DOLLY_SCREEN_PAN:8192,TOUCH_DOLLY_OFFSET:16384,TOUCH_DOLLY_ROTATE:32768,TOUCH_ZOOM_TRUCK:65536,TOUCH_ZOOM_OFFSET:131072,TOUCH_ZOOM_SCREEN_PAN:262144,TOUCH_ZOOM_ROTATE:524288}),Ee=0,Se=1,Ae=-1;function Oe(t){return t.isPerspectiveCamera}function Pe(t){return t.isOrthographicCamera}const Ie=2*Math.PI,Me=Math.PI/2,De=Math.PI/180;function ke(t,e,i){return Math.max(e,Math.min(i,t))}function ze(t,e=1e-5){return Math.abs(t)<e}function Be(t,e,i=1e-5){return ze(t-e,i)}function Ne(t,e){return Math.round(t/e)*e}function Ue(t){return isFinite(t)?t:t<0?-Number.MAX_VALUE:Number.MAX_VALUE}function Le(t){return Math.abs(t)<Number.MAX_VALUE?t:t*(1/0)}function Re(t,e,i,s,n=1/0,r){const o=2/(s=Math.max(1e-4,s)),a=o*r,l=1/(1+a+.48*a*a+.235*a*a*a);let h=t-e;const c=e,d=n*s;h=ke(h,-d,d),e=t-h;const u=(i.value+o*h)*r;i.value=(i.value-o*u)*l;let p=e+(h+u)*l;return c-t>0==p>c&&(p=c,i.value=(p-c)/r),p}function Fe(t,e,i,s,n=1/0,r,o){const a=2/(s=Math.max(1e-4,s)),l=a*r,h=1/(1+l+.48*l*l+.235*l*l*l);let c=e.x,d=e.y,u=e.z,p=t.x-c,f=t.y-d,m=t.z-u;const g=c,_=d,y=u,w=n*s,v=p*p+f*f+m*m;if(v>w*w){const t=Math.sqrt(v);p=p/t*w,f=f/t*w,m=m/t*w}c=t.x-p,d=t.y-f,u=t.z-m;const b=(i.x+a*p)*r,x=(i.y+a*f)*r,T=(i.z+a*m)*r;i.x=(i.x-a*b)*h,i.y=(i.y-a*x)*h,i.z=(i.z-a*T)*h,o.x=c+(p+b)*h,o.y=d+(f+x)*h,o.z=u+(m+T)*h;const C=g-t.x,E=_-t.y,S=y-t.z;return C*(o.x-g)+E*(o.y-_)+S*(o.z-y)>0&&(o.x=g,o.y=_,o.z=y,i.x=(o.x-g)/r,i.y=(o.y-_)/r,i.z=(o.z-y)/r),o}function Ve(t,e){e.set(0,0),t.forEach(t=>{e.x+=t.clientX,e.y+=t.clientY}),e.x/=t.length,e.y/=t.length}function je(t,e){return!!Pe(t)&&(console.warn(`${e} is not supported in OrthographicCamera`),!0)}class He{constructor(){this._listeners={}}addEventListener(t,e){const i=this._listeners;void 0===i[t]&&(i[t]=[]),-1===i[t].indexOf(e)&&i[t].push(e)}hasEventListener(t,e){const i=this._listeners;return void 0!==i[t]&&-1!==i[t].indexOf(e)}removeEventListener(t,e){const i=this._listeners[t];if(void 0!==i){const t=i.indexOf(e);-1!==t&&i.splice(t,1)}}removeAllEventListeners(t){t?Array.isArray(this._listeners[t])&&(this._listeners[t].length=0):this._listeners={}}dispatchEvent(t){const e=this._listeners[t.type];if(void 0!==e){t.target=this;const i=e.slice(0);for(let e=0,s=i.length;e<s;e++)i[e].call(this,t)}}}var Ze;const $e=1/8,We=/Mac/.test(null===(Ze=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===Ze?void 0:Ze.platform);let Ye,Ge,Xe,qe,Qe,Ke,Je,ti,ei,ii,si,ni,ri,oi,ai,li,hi,ci,di,ui,pi,fi,mi;class gi extends He{static install(t){Ye=t.THREE,Ge=Object.freeze(new Ye.Vector3(0,0,0)),Xe=Object.freeze(new Ye.Vector3(0,1,0)),qe=Object.freeze(new Ye.Vector3(0,0,1)),Qe=new Ye.Vector2,Ke=new Ye.Vector3,Je=new Ye.Vector3,ti=new Ye.Vector3,ei=new Ye.Vector3,ii=new Ye.Vector3,si=new Ye.Vector3,ni=new Ye.Vector3,ri=new Ye.Vector3,oi=new Ye.Vector3,ai=new Ye.Spherical,li=new Ye.Spherical,hi=new Ye.Box3,ci=new Ye.Box3,di=new Ye.Sphere,ui=new Ye.Quaternion,pi=new Ye.Quaternion,fi=new Ye.Matrix4,mi=new Ye.Raycaster}static get ACTION(){return Ce}set verticalDragToForward(t){console.warn("camera-controls: `verticalDragToForward` was removed. Use `mouseButtons.left = CameraControls.ACTION.SCREEN_PAN` instead.")}constructor(t,e){super(),this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.minDistance=Number.EPSILON,this.maxDistance=1/0,this.infinityDolly=!1,this.minZoom=.01,this.maxZoom=1/0,this.smoothTime=.25,this.draggingSmoothTime=.125,this.maxSpeed=1/0,this.azimuthRotateSpeed=1,this.polarRotateSpeed=1,this.dollySpeed=1,this.dollyDragInverted=!1,this.truckSpeed=2,this.dollyToCursor=!1,this.dragToOffset=!1,this.boundaryFriction=0,this.restThreshold=.01,this.colliderMeshes=[],this.cancel=()=>{},this._enabled=!0,this._state=Ce.NONE,this._viewport=null,this._changedDolly=0,this._changedZoom=0,this._hasRested=!0,this._boundaryEnclosesCamera=!1,this._needsUpdate=!0,this._updatedLastTime=!1,this._elementRect=new DOMRect,this._isDragging=!1,this._dragNeedsUpdate=!0,this._activePointers=[],this._lockedPointer=null,this._interactiveArea=new DOMRect(0,0,1,1),this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._isUserControllingOffset=!1,this._isUserControllingZoom=!1,this._lastDollyDirection=Ee,this._thetaVelocity={value:0},this._phiVelocity={value:0},this._radiusVelocity={value:0},this._targetVelocity=new Ye.Vector3,this._focalOffsetVelocity=new Ye.Vector3,this._zoomVelocity={value:0},this._truckInternal=(t,e,i,s)=>{let n,r;if(Oe(this._camera)){const i=Ke.copy(this._camera.position).sub(this._target),s=this._camera.getEffectiveFOV()*De,o=i.length()*Math.tan(.5*s);n=this.truckSpeed*t*o/this._elementRect.height,r=this.truckSpeed*e*o/this._elementRect.height}else{if(!Pe(this._camera))return;{const i=this._camera;n=this.truckSpeed*t*(i.right-i.left)/i.zoom/this._elementRect.width,r=this.truckSpeed*e*(i.top-i.bottom)/i.zoom/this._elementRect.height}}s?(i?this.setFocalOffset(this._focalOffsetEnd.x+n,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(n,0,!0),this.forward(-r,!0)):i?this.setFocalOffset(this._focalOffsetEnd.x+n,this._focalOffsetEnd.y+r,this._focalOffsetEnd.z,!0):this.truck(n,r,!0)},this._rotateInternal=(t,e)=>{const i=Ie*this.azimuthRotateSpeed*t/this._elementRect.height,s=Ie*this.polarRotateSpeed*e/this._elementRect.height;this.rotate(i,s,!0)},this._dollyInternal=(t,e,i)=>{const s=Math.pow(.95,-t*this.dollySpeed),n=this._sphericalEnd.radius,r=this._sphericalEnd.radius*s,o=ke(r,this.minDistance,this.maxDistance),a=o-r;this.infinityDolly&&this.dollyToCursor?this._dollyToNoClamp(r,!0):this.infinityDolly&&!this.dollyToCursor?(this.dollyInFixed(a,!0),this._dollyToNoClamp(o,!0)):this._dollyToNoClamp(o,!0),this.dollyToCursor&&(this._changedDolly+=(this.infinityDolly?r:o)-n,this._dollyControlCoord.set(e,i)),this._lastDollyDirection=Math.sign(-t)},this._zoomInternal=(t,e,i)=>{const s=Math.pow(.95,t*this.dollySpeed),n=this._zoom,r=this._zoom*s;this.zoomTo(r,!0),this.dollyToCursor&&(this._changedZoom+=r-n,this._dollyControlCoord.set(e,i))},void 0===Ye&&console.error("camera-controls: `THREE` is undefined. You must first run `CameraControls.install( { THREE: THREE } )`. Check the docs for further information."),this._camera=t,this._yAxisUpSpace=(new Ye.Quaternion).setFromUnitVectors(this._camera.up,Xe),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=Ce.NONE,this._target=new Ye.Vector3,this._targetEnd=this._target.clone(),this._focalOffset=new Ye.Vector3,this._focalOffsetEnd=this._focalOffset.clone(),this._spherical=(new Ye.Spherical).setFromVector3(Ke.copy(this._camera.position).applyQuaternion(this._yAxisUpSpace)),this._sphericalEnd=this._spherical.clone(),this._lastDistance=this._spherical.radius,this._zoom=this._camera.zoom,this._zoomEnd=this._zoom,this._lastZoom=this._zoom,this._nearPlaneCorners=[new Ye.Vector3,new Ye.Vector3,new Ye.Vector3,new Ye.Vector3],this._updateNearPlaneCorners(),this._boundary=new Ye.Box3(new Ye.Vector3(-1/0,-1/0,-1/0),new Ye.Vector3(1/0,1/0,1/0)),this._cameraUp0=this._camera.up.clone(),this._target0=this._target.clone(),this._position0=this._camera.position.clone(),this._zoom0=this._zoom,this._focalOffset0=this._focalOffset.clone(),this._dollyControlCoord=new Ye.Vector2,this.mouseButtons={left:Ce.ROTATE,middle:Ce.DOLLY,right:Ce.TRUCK,wheel:Oe(this._camera)?Ce.DOLLY:Pe(this._camera)?Ce.ZOOM:Ce.NONE},this.touches={one:Ce.TOUCH_ROTATE,two:Oe(this._camera)?Ce.TOUCH_DOLLY_TRUCK:Pe(this._camera)?Ce.TOUCH_ZOOM_TRUCK:Ce.NONE,three:Ce.TOUCH_TRUCK};const i=new Ye.Vector2,s=new Ye.Vector2,n=new Ye.Vector2,r=t=>{if(!this._enabled||!this._domElement)return;if(0!==this._interactiveArea.left||0!==this._interactiveArea.top||1!==this._interactiveArea.width||1!==this._interactiveArea.height){const e=this._domElement.getBoundingClientRect(),i=t.clientX/e.width,s=t.clientY/e.height;if(i<this._interactiveArea.left||i>this._interactiveArea.right||s<this._interactiveArea.top||s>this._interactiveArea.bottom)return}const e="mouse"!==t.pointerType?null:(t.buttons&be)===be?be:(t.buttons&Te)===Te?Te:(t.buttons&xe)===xe?xe:null;if(null!==e){const t=this._findPointerByMouseButton(e);t&&this._disposePointer(t)}if((t.buttons&be)===be&&this._lockedPointer)return;const i={pointerId:t.pointerId,clientX:t.clientX,clientY:t.clientY,deltaX:0,deltaY:0,mouseButton:e};this._activePointers.push(i),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",a),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",a),this._isDragging=!0,d(t)},o=t=>{t.cancelable&&t.preventDefault();const e=t.pointerId,i=this._lockedPointer||this._findPointerById(e);if(i){if(i.clientX=t.clientX,i.clientY=t.clientY,i.deltaX=t.movementX,i.deltaY=t.movementY,this._state=0,"touch"===t.pointerType)switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three}else(!this._isDragging&&this._lockedPointer||this._isDragging&&(t.buttons&be)===be)&&(this._state=this._state|this.mouseButtons.left),this._isDragging&&(t.buttons&Te)===Te&&(this._state=this._state|this.mouseButtons.middle),this._isDragging&&(t.buttons&xe)===xe&&(this._state=this._state|this.mouseButtons.right);u()}},a=t=>{const e=this._findPointerById(t.pointerId);if(!e||e!==this._lockedPointer){if(e&&this._disposePointer(e),"touch"===t.pointerType)switch(this._activePointers.length){case 0:this._state=Ce.NONE;break;case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three}else this._state=Ce.NONE;p()}};let l=-1;const h=t=>{if(!this._domElement)return;if(!this._enabled||this.mouseButtons.wheel===Ce.NONE)return;if(0!==this._interactiveArea.left||0!==this._interactiveArea.top||1!==this._interactiveArea.width||1!==this._interactiveArea.height){const e=this._domElement.getBoundingClientRect(),i=t.clientX/e.width,s=t.clientY/e.height;if(i<this._interactiveArea.left||i>this._interactiveArea.right||s<this._interactiveArea.top||s>this._interactiveArea.bottom)return}if(t.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===Ce.ROTATE||this.mouseButtons.wheel===Ce.TRUCK){const t=performance.now();l-t<1e3&&this._getClientRect(this._elementRect),l=t}const e=We?-1:-3,i=1===t.deltaMode||t.ctrlKey?t.deltaY/e:t.deltaY/(10*e),s=this.dollyToCursor?(t.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,n=this.dollyToCursor?(t.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(this.mouseButtons.wheel){case Ce.ROTATE:this._rotateInternal(t.deltaX,t.deltaY),this._isUserControllingRotate=!0;break;case Ce.TRUCK:this._truckInternal(t.deltaX,t.deltaY,!1,!1),this._isUserControllingTruck=!0;break;case Ce.SCREEN_PAN:this._truckInternal(t.deltaX,t.deltaY,!1,!0),this._isUserControllingTruck=!0;break;case Ce.OFFSET:this._truckInternal(t.deltaX,t.deltaY,!0,!1),this._isUserControllingOffset=!0;break;case Ce.DOLLY:this._dollyInternal(-i,s,n),this._isUserControllingDolly=!0;break;case Ce.ZOOM:this._zoomInternal(-i,s,n),this._isUserControllingZoom=!0}this.dispatchEvent({type:"control"})},c=t=>{if(this._domElement&&this._enabled){if(this.mouseButtons.right===gi.ACTION.NONE){const e=t instanceof PointerEvent?t.pointerId:0,i=this._findPointerById(e);return i&&this._disposePointer(i),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),void this._domElement.ownerDocument.removeEventListener("pointerup",a)}t.preventDefault()}},d=t=>{if(!this._enabled)return;Ve(this._activePointers,Qe),this._getClientRect(this._elementRect),i.copy(Qe),s.copy(Qe);if(this._activePointers.length>=2){const t=Qe.x-this._activePointers[1].clientX,e=Qe.y-this._activePointers[1].clientY,i=Math.sqrt(t*t+e*e);n.set(0,i);const r=.5*(this._activePointers[0].clientX+this._activePointers[1].clientX),o=.5*(this._activePointers[0].clientY+this._activePointers[1].clientY);s.set(r,o)}if(this._state=0,t)if("pointerType"in t&&"touch"===t.pointerType)switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three}else this._lockedPointer||(t.buttons&be)!==be||(this._state=this._state|this.mouseButtons.left),(t.buttons&Te)===Te&&(this._state=this._state|this.mouseButtons.middle),(t.buttons&xe)===xe&&(this._state=this._state|this.mouseButtons.right);else this._lockedPointer&&(this._state=this._state|this.mouseButtons.left);(this._state&Ce.ROTATE)!==Ce.ROTATE&&(this._state&Ce.TOUCH_ROTATE)!==Ce.TOUCH_ROTATE&&(this._state&Ce.TOUCH_DOLLY_ROTATE)!==Ce.TOUCH_DOLLY_ROTATE&&(this._state&Ce.TOUCH_ZOOM_ROTATE)!==Ce.TOUCH_ZOOM_ROTATE||(this._sphericalEnd.theta=this._spherical.theta,this._sphericalEnd.phi=this._spherical.phi,this._thetaVelocity.value=0,this._phiVelocity.value=0),(this._state&Ce.TRUCK)!==Ce.TRUCK&&(this._state&Ce.SCREEN_PAN)!==Ce.SCREEN_PAN&&(this._state&Ce.TOUCH_TRUCK)!==Ce.TOUCH_TRUCK&&(this._state&Ce.TOUCH_SCREEN_PAN)!==Ce.TOUCH_SCREEN_PAN&&(this._state&Ce.TOUCH_DOLLY_TRUCK)!==Ce.TOUCH_DOLLY_TRUCK&&(this._state&Ce.TOUCH_DOLLY_SCREEN_PAN)!==Ce.TOUCH_DOLLY_SCREEN_PAN&&(this._state&Ce.TOUCH_ZOOM_TRUCK)!==Ce.TOUCH_ZOOM_TRUCK&&(this._state&Ce.TOUCH_ZOOM_SCREEN_PAN)!==Ce.TOUCH_DOLLY_SCREEN_PAN||(this._targetEnd.copy(this._target),this._targetVelocity.set(0,0,0)),(this._state&Ce.DOLLY)!==Ce.DOLLY&&(this._state&Ce.TOUCH_DOLLY)!==Ce.TOUCH_DOLLY&&(this._state&Ce.TOUCH_DOLLY_TRUCK)!==Ce.TOUCH_DOLLY_TRUCK&&(this._state&Ce.TOUCH_DOLLY_SCREEN_PAN)!==Ce.TOUCH_DOLLY_SCREEN_PAN&&(this._state&Ce.TOUCH_DOLLY_OFFSET)!==Ce.TOUCH_DOLLY_OFFSET&&(this._state&Ce.TOUCH_DOLLY_ROTATE)!==Ce.TOUCH_DOLLY_ROTATE||(this._sphericalEnd.radius=this._spherical.radius,this._radiusVelocity.value=0),(this._state&Ce.ZOOM)!==Ce.ZOOM&&(this._state&Ce.TOUCH_ZOOM)!==Ce.TOUCH_ZOOM&&(this._state&Ce.TOUCH_ZOOM_TRUCK)!==Ce.TOUCH_ZOOM_TRUCK&&(this._state&Ce.TOUCH_ZOOM_SCREEN_PAN)!==Ce.TOUCH_ZOOM_SCREEN_PAN&&(this._state&Ce.TOUCH_ZOOM_OFFSET)!==Ce.TOUCH_ZOOM_OFFSET&&(this._state&Ce.TOUCH_ZOOM_ROTATE)!==Ce.TOUCH_ZOOM_ROTATE||(this._zoomEnd=this._zoom,this._zoomVelocity.value=0),(this._state&Ce.OFFSET)!==Ce.OFFSET&&(this._state&Ce.TOUCH_OFFSET)!==Ce.TOUCH_OFFSET&&(this._state&Ce.TOUCH_DOLLY_OFFSET)!==Ce.TOUCH_DOLLY_OFFSET&&(this._state&Ce.TOUCH_ZOOM_OFFSET)!==Ce.TOUCH_ZOOM_OFFSET||(this._focalOffsetEnd.copy(this._focalOffset),this._focalOffsetVelocity.set(0,0,0)),this.dispatchEvent({type:"controlstart"})},u=()=>{if(!this._enabled||!this._dragNeedsUpdate)return;this._dragNeedsUpdate=!1,Ve(this._activePointers,Qe);const t=this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement?this._lockedPointer||this._activePointers[0]:null,e=t?-t.deltaX:s.x-Qe.x,r=t?-t.deltaY:s.y-Qe.y;if(s.copy(Qe),(this._state&Ce.ROTATE)!==Ce.ROTATE&&(this._state&Ce.TOUCH_ROTATE)!==Ce.TOUCH_ROTATE&&(this._state&Ce.TOUCH_DOLLY_ROTATE)!==Ce.TOUCH_DOLLY_ROTATE&&(this._state&Ce.TOUCH_ZOOM_ROTATE)!==Ce.TOUCH_ZOOM_ROTATE||(this._rotateInternal(e,r),this._isUserControllingRotate=!0),(this._state&Ce.DOLLY)===Ce.DOLLY||(this._state&Ce.ZOOM)===Ce.ZOOM){const t=this.dollyToCursor?(i.x-this._elementRect.x)/this._elementRect.width*2-1:0,e=this.dollyToCursor?(i.y-this._elementRect.y)/this._elementRect.height*-2+1:0,s=this.dollyDragInverted?-1:1;(this._state&Ce.DOLLY)===Ce.DOLLY?(this._dollyInternal(s*r*$e,t,e),this._isUserControllingDolly=!0):(this._zoomInternal(s*r*$e,t,e),this._isUserControllingZoom=!0)}if((this._state&Ce.TOUCH_DOLLY)===Ce.TOUCH_DOLLY||(this._state&Ce.TOUCH_ZOOM)===Ce.TOUCH_ZOOM||(this._state&Ce.TOUCH_DOLLY_TRUCK)===Ce.TOUCH_DOLLY_TRUCK||(this._state&Ce.TOUCH_ZOOM_TRUCK)===Ce.TOUCH_ZOOM_TRUCK||(this._state&Ce.TOUCH_DOLLY_SCREEN_PAN)===Ce.TOUCH_DOLLY_SCREEN_PAN||(this._state&Ce.TOUCH_ZOOM_SCREEN_PAN)===Ce.TOUCH_ZOOM_SCREEN_PAN||(this._state&Ce.TOUCH_DOLLY_OFFSET)===Ce.TOUCH_DOLLY_OFFSET||(this._state&Ce.TOUCH_ZOOM_OFFSET)===Ce.TOUCH_ZOOM_OFFSET||(this._state&Ce.TOUCH_DOLLY_ROTATE)===Ce.TOUCH_DOLLY_ROTATE||(this._state&Ce.TOUCH_ZOOM_ROTATE)===Ce.TOUCH_ZOOM_ROTATE){const t=Qe.x-this._activePointers[1].clientX,e=Qe.y-this._activePointers[1].clientY,i=Math.sqrt(t*t+e*e),r=n.y-i;n.set(0,i);const o=this.dollyToCursor?(s.x-this._elementRect.x)/this._elementRect.width*2-1:0,a=this.dollyToCursor?(s.y-this._elementRect.y)/this._elementRect.height*-2+1:0;(this._state&Ce.TOUCH_DOLLY)===Ce.TOUCH_DOLLY||(this._state&Ce.TOUCH_DOLLY_ROTATE)===Ce.TOUCH_DOLLY_ROTATE||(this._state&Ce.TOUCH_DOLLY_TRUCK)===Ce.TOUCH_DOLLY_TRUCK||(this._state&Ce.TOUCH_DOLLY_SCREEN_PAN)===Ce.TOUCH_DOLLY_SCREEN_PAN||(this._state&Ce.TOUCH_DOLLY_OFFSET)===Ce.TOUCH_DOLLY_OFFSET?(this._dollyInternal(r*$e,o,a),this._isUserControllingDolly=!0):(this._zoomInternal(r*$e,o,a),this._isUserControllingZoom=!0)}(this._state&Ce.TRUCK)!==Ce.TRUCK&&(this._state&Ce.TOUCH_TRUCK)!==Ce.TOUCH_TRUCK&&(this._state&Ce.TOUCH_DOLLY_TRUCK)!==Ce.TOUCH_DOLLY_TRUCK&&(this._state&Ce.TOUCH_ZOOM_TRUCK)!==Ce.TOUCH_ZOOM_TRUCK||(this._truckInternal(e,r,!1,!1),this._isUserControllingTruck=!0),(this._state&Ce.SCREEN_PAN)!==Ce.SCREEN_PAN&&(this._state&Ce.TOUCH_SCREEN_PAN)!==Ce.TOUCH_SCREEN_PAN&&(this._state&Ce.TOUCH_DOLLY_SCREEN_PAN)!==Ce.TOUCH_DOLLY_SCREEN_PAN&&(this._state&Ce.TOUCH_ZOOM_SCREEN_PAN)!==Ce.TOUCH_ZOOM_SCREEN_PAN||(this._truckInternal(e,r,!1,!0),this._isUserControllingTruck=!0),(this._state&Ce.OFFSET)!==Ce.OFFSET&&(this._state&Ce.TOUCH_OFFSET)!==Ce.TOUCH_OFFSET&&(this._state&Ce.TOUCH_DOLLY_OFFSET)!==Ce.TOUCH_DOLLY_OFFSET&&(this._state&Ce.TOUCH_ZOOM_OFFSET)!==Ce.TOUCH_ZOOM_OFFSET||(this._truckInternal(e,r,!0,!1),this._isUserControllingOffset=!0),this.dispatchEvent({type:"control"})},p=()=>{Ve(this._activePointers,Qe),s.copy(Qe),this._dragNeedsUpdate=!1,(0===this._activePointers.length||1===this._activePointers.length&&this._activePointers[0]===this._lockedPointer)&&(this._isDragging=!1),0===this._activePointers.length&&this._domElement&&(this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",a),this.dispatchEvent({type:"controlend"}))};this.lockPointer=()=>{this._enabled&&this._domElement&&(this.cancel(),this._lockedPointer={pointerId:-1,clientX:0,clientY:0,deltaX:0,deltaY:0,mouseButton:null},this._activePointers.push(this._lockedPointer),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",a),this._domElement.requestPointerLock(),this._domElement.ownerDocument.addEventListener("pointerlockchange",f),this._domElement.ownerDocument.addEventListener("pointerlockerror",m),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",a),d())},this.unlockPointer=()=>{var t,e,i;null!==this._lockedPointer&&(this._disposePointer(this._lockedPointer),this._lockedPointer=null),null===(t=this._domElement)||void 0===t||t.ownerDocument.exitPointerLock(),null===(e=this._domElement)||void 0===e||e.ownerDocument.removeEventListener("pointerlockchange",f),null===(i=this._domElement)||void 0===i||i.ownerDocument.removeEventListener("pointerlockerror",m),this.cancel()};const f=()=>{this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement||this.unlockPointer()},m=()=>{this.unlockPointer()};this._addAllEventListeners=t=>{this._domElement=t,this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none",this._domElement.addEventListener("pointerdown",r),this._domElement.addEventListener("pointercancel",a),this._domElement.addEventListener("wheel",h,{passive:!1}),this._domElement.addEventListener("contextmenu",c)},this._removeAllEventListeners=()=>{this._domElement&&(this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect="",this._domElement.removeEventListener("pointerdown",r),this._domElement.removeEventListener("pointercancel",a),this._domElement.removeEventListener("wheel",h,{passive:!1}),this._domElement.removeEventListener("contextmenu",c),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",a),this._domElement.ownerDocument.removeEventListener("pointerlockchange",f),this._domElement.ownerDocument.removeEventListener("pointerlockerror",m))},this.cancel=()=>{this._state!==Ce.NONE&&(this._state=Ce.NONE,this._activePointers.length=0,p())},e&&this.connect(e),this.update(0)}get camera(){return this._camera}set camera(t){this._camera=t,this.updateCameraUp(),this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0}get enabled(){return this._enabled}set enabled(t){this._enabled=t,this._domElement&&(t?(this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none"):(this.cancel(),this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect=""))}get active(){return!this._hasRested}get currentAction(){return this._state}get distance(){return this._spherical.radius}set distance(t){this._spherical.radius===t&&this._sphericalEnd.radius===t||(this._spherical.radius=t,this._sphericalEnd.radius=t,this._needsUpdate=!0)}get azimuthAngle(){return this._spherical.theta}set azimuthAngle(t){this._spherical.theta===t&&this._sphericalEnd.theta===t||(this._spherical.theta=t,this._sphericalEnd.theta=t,this._needsUpdate=!0)}get polarAngle(){return this._spherical.phi}set polarAngle(t){this._spherical.phi===t&&this._sphericalEnd.phi===t||(this._spherical.phi=t,this._sphericalEnd.phi=t,this._needsUpdate=!0)}get boundaryEnclosesCamera(){return this._boundaryEnclosesCamera}set boundaryEnclosesCamera(t){this._boundaryEnclosesCamera=t,this._needsUpdate=!0}set interactiveArea(t){this._interactiveArea.width=ke(t.width,0,1),this._interactiveArea.height=ke(t.height,0,1),this._interactiveArea.x=ke(t.x,0,1-this._interactiveArea.width),this._interactiveArea.y=ke(t.y,0,1-this._interactiveArea.height)}addEventListener(t,e){super.addEventListener(t,e)}removeEventListener(t,e){super.removeEventListener(t,e)}rotate(t,e,i=!1){return this.rotateTo(this._sphericalEnd.theta+t,this._sphericalEnd.phi+e,i)}rotateAzimuthTo(t,e=!1){return this.rotateTo(t,this._sphericalEnd.phi,e)}rotatePolarTo(t,e=!1){return this.rotateTo(this._sphericalEnd.theta,t,e)}rotateTo(t,e,i=!1){this._isUserControllingRotate=!1;const s=ke(t,this.minAzimuthAngle,this.maxAzimuthAngle),n=ke(e,this.minPolarAngle,this.maxPolarAngle);this._sphericalEnd.theta=s,this._sphericalEnd.phi=n,this._sphericalEnd.makeSafe(),this._needsUpdate=!0,i||(this._spherical.theta=this._sphericalEnd.theta,this._spherical.phi=this._sphericalEnd.phi);const r=!i||Be(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Be(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold);return this._createOnRestPromise(r)}dolly(t,e=!1){return this.dollyTo(this._sphericalEnd.radius-t,e)}dollyTo(t,e=!1){return this._isUserControllingDolly=!1,this._lastDollyDirection=Ee,this._changedDolly=0,this._dollyToNoClamp(ke(t,this.minDistance,this.maxDistance),e)}_dollyToNoClamp(t,e=!1){const i=this._sphericalEnd.radius;if(this.colliderMeshes.length>=1){const e=this._collisionTest(),s=Be(e,this._spherical.radius);if(!(i>t)&&s)return Promise.resolve();this._sphericalEnd.radius=Math.min(t,e)}else this._sphericalEnd.radius=t;this._needsUpdate=!0,e||(this._spherical.radius=this._sphericalEnd.radius);const s=!e||Be(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(s)}dollyInFixed(t,e=!1){this._targetEnd.add(this._getCameraDirection(ei).multiplyScalar(t)),e||this._target.copy(this._targetEnd);const i=!e||Be(this._target.x,this._targetEnd.x,this.restThreshold)&&Be(this._target.y,this._targetEnd.y,this.restThreshold)&&Be(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(i)}zoom(t,e=!1){return this.zoomTo(this._zoomEnd+t,e)}zoomTo(t,e=!1){this._isUserControllingZoom=!1,this._zoomEnd=ke(t,this.minZoom,this.maxZoom),this._needsUpdate=!0,e||(this._zoom=this._zoomEnd);const i=!e||Be(this._zoom,this._zoomEnd,this.restThreshold);return this._changedZoom=0,this._createOnRestPromise(i)}pan(t,e,i=!1){return console.warn("`pan` has been renamed to `truck`"),this.truck(t,e,i)}truck(t,e,i=!1){this._camera.updateMatrix(),ii.setFromMatrixColumn(this._camera.matrix,0),si.setFromMatrixColumn(this._camera.matrix,1),ii.multiplyScalar(t),si.multiplyScalar(-e);const s=Ke.copy(ii).add(si),n=Je.copy(this._targetEnd).add(s);return this.moveTo(n.x,n.y,n.z,i)}forward(t,e=!1){Ke.setFromMatrixColumn(this._camera.matrix,0),Ke.crossVectors(this._camera.up,Ke),Ke.multiplyScalar(t);const i=Je.copy(this._targetEnd).add(Ke);return this.moveTo(i.x,i.y,i.z,e)}elevate(t,e=!1){return Ke.copy(this._camera.up).multiplyScalar(t),this.moveTo(this._targetEnd.x+Ke.x,this._targetEnd.y+Ke.y,this._targetEnd.z+Ke.z,e)}moveTo(t,e,i,s=!1){this._isUserControllingTruck=!1;const n=Ke.set(t,e,i).sub(this._targetEnd);this._encloseToBoundary(this._targetEnd,n,this.boundaryFriction),this._needsUpdate=!0,s||this._target.copy(this._targetEnd);const r=!s||Be(this._target.x,this._targetEnd.x,this.restThreshold)&&Be(this._target.y,this._targetEnd.y,this.restThreshold)&&Be(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(r)}lookInDirectionOf(t,e,i,s=!1){const n=Ke.set(t,e,i).sub(this._targetEnd).normalize().multiplyScalar(-this._sphericalEnd.radius).add(this._targetEnd);return this.setPosition(n.x,n.y,n.z,s)}fitToBox(t,e,{cover:i=!1,paddingLeft:s=0,paddingRight:n=0,paddingBottom:r=0,paddingTop:o=0}={}){const a=[],l=t.isBox3?hi.copy(t):hi.setFromObject(t);l.isEmpty()&&(console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"),Promise.resolve());const h=Ne(this._sphericalEnd.theta,Me),c=Ne(this._sphericalEnd.phi,Me);a.push(this.rotateTo(h,c,e));const d=Ke.setFromSpherical(this._sphericalEnd).normalize(),u=ui.setFromUnitVectors(d,qe),p=Be(Math.abs(d.y),1);p&&u.multiply(pi.setFromAxisAngle(Xe,h)),u.multiply(this._yAxisUpSpaceInverse);const f=ci.makeEmpty();Je.copy(l.min).applyQuaternion(u),f.expandByPoint(Je),Je.copy(l.min).setX(l.max.x).applyQuaternion(u),f.expandByPoint(Je),Je.copy(l.min).setY(l.max.y).applyQuaternion(u),f.expandByPoint(Je),Je.copy(l.max).setZ(l.min.z).applyQuaternion(u),f.expandByPoint(Je),Je.copy(l.min).setZ(l.max.z).applyQuaternion(u),f.expandByPoint(Je),Je.copy(l.max).setY(l.min.y).applyQuaternion(u),f.expandByPoint(Je),Je.copy(l.max).setX(l.min.x).applyQuaternion(u),f.expandByPoint(Je),Je.copy(l.max).applyQuaternion(u),f.expandByPoint(Je),f.min.x-=s,f.min.y-=r,f.max.x+=n,f.max.y+=o,u.setFromUnitVectors(qe,d),p&&u.premultiply(pi.invert()),u.premultiply(this._yAxisUpSpace);const m=f.getSize(Ke),g=f.getCenter(Je).applyQuaternion(u);if(Oe(this._camera)){const t=this.getDistanceToFitBox(m.x,m.y,m.z,i);a.push(this.moveTo(g.x,g.y,g.z,e)),a.push(this.dollyTo(t,e)),a.push(this.setFocalOffset(0,0,0,e))}else if(Pe(this._camera)){const t=this._camera,s=t.right-t.left,n=t.top-t.bottom,r=i?Math.max(s/m.x,n/m.y):Math.min(s/m.x,n/m.y);a.push(this.moveTo(g.x,g.y,g.z,e)),a.push(this.zoomTo(r,e)),a.push(this.setFocalOffset(0,0,0,e))}return Promise.all(a)}fitToSphere(t,e){const i=[],s="isObject3D"in t?gi.createBoundingSphere(t,di):di.copy(t);if(i.push(this.moveTo(s.center.x,s.center.y,s.center.z,e)),Oe(this._camera)){const t=this.getDistanceToFitSphere(s.radius);i.push(this.dollyTo(t,e))}else if(Pe(this._camera)){const t=this._camera.right-this._camera.left,n=this._camera.top-this._camera.bottom,r=2*s.radius,o=Math.min(t/r,n/r);i.push(this.zoomTo(o,e))}return i.push(this.setFocalOffset(0,0,0,e)),Promise.all(i)}setLookAt(t,e,i,s,n,r,o=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Ee,this._changedDolly=0;const a=Je.set(s,n,r),l=Ke.set(t,e,i);this._targetEnd.copy(a),this._sphericalEnd.setFromVector3(l.sub(a).applyQuaternion(this._yAxisUpSpace)),this.normalizeRotations(),this._needsUpdate=!0,o||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const h=!o||Be(this._target.x,this._targetEnd.x,this.restThreshold)&&Be(this._target.y,this._targetEnd.y,this.restThreshold)&&Be(this._target.z,this._targetEnd.z,this.restThreshold)&&Be(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Be(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Be(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(h)}lerpLookAt(t,e,i,s,n,r,o,a,l,h,c,d,u,p=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Ee,this._changedDolly=0;const f=Ke.set(s,n,r),m=Je.set(t,e,i);ai.setFromVector3(m.sub(f).applyQuaternion(this._yAxisUpSpace));const g=ti.set(h,c,d),_=Je.set(o,a,l);li.setFromVector3(_.sub(g).applyQuaternion(this._yAxisUpSpace)),this._targetEnd.copy(f.lerp(g,u));const y=li.theta-ai.theta,w=li.phi-ai.phi,v=li.radius-ai.radius;this._sphericalEnd.set(ai.radius+v*u,ai.phi+w*u,ai.theta+y*u),this.normalizeRotations(),this._needsUpdate=!0,p||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const b=!p||Be(this._target.x,this._targetEnd.x,this.restThreshold)&&Be(this._target.y,this._targetEnd.y,this.restThreshold)&&Be(this._target.z,this._targetEnd.z,this.restThreshold)&&Be(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Be(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Be(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(b)}setPosition(t,e,i,s=!1){return this.setLookAt(t,e,i,this._targetEnd.x,this._targetEnd.y,this._targetEnd.z,s)}setTarget(t,e,i,s=!1){const n=this.getPosition(Ke),r=this.setLookAt(n.x,n.y,n.z,t,e,i,s);return this._sphericalEnd.phi=ke(this._sphericalEnd.phi,this.minPolarAngle,this.maxPolarAngle),r}setFocalOffset(t,e,i,s=!1){this._isUserControllingOffset=!1,this._focalOffsetEnd.set(t,e,i),this._needsUpdate=!0,s||this._focalOffset.copy(this._focalOffsetEnd);const n=!s||Be(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&Be(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&Be(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(n)}setOrbitPoint(t,e,i){this._camera.updateMatrixWorld(),ii.setFromMatrixColumn(this._camera.matrixWorldInverse,0),si.setFromMatrixColumn(this._camera.matrixWorldInverse,1),ni.setFromMatrixColumn(this._camera.matrixWorldInverse,2);const s=Ke.set(t,e,i),n=s.distanceTo(this._camera.position),r=s.sub(this._camera.position);ii.multiplyScalar(r.x),si.multiplyScalar(r.y),ni.multiplyScalar(r.z),Ke.copy(ii).add(si).add(ni),Ke.z=Ke.z+n,this.dollyTo(n,!1),this.setFocalOffset(-Ke.x,Ke.y,-Ke.z,!1),this.moveTo(t,e,i,!1)}setBoundary(t){if(!t)return this._boundary.min.set(-1/0,-1/0,-1/0),this._boundary.max.set(1/0,1/0,1/0),void(this._needsUpdate=!0);this._boundary.copy(t),this._boundary.clampPoint(this._targetEnd,this._targetEnd),this._needsUpdate=!0}setViewport(t,e,i,s){null!==t?(this._viewport=this._viewport||new Ye.Vector4,"number"==typeof t?this._viewport.set(t,e,i,s):this._viewport.copy(t)):this._viewport=null}getDistanceToFitBox(t,e,i,s=!1){if(je(this._camera,"getDistanceToFitBox"))return this._spherical.radius;const n=t/e,r=this._camera.getEffectiveFOV()*De,o=this._camera.aspect;return.5*((s?n>o:n<o)?e:t/o)/Math.tan(.5*r)+.5*i}getDistanceToFitSphere(t){if(je(this._camera,"getDistanceToFitSphere"))return this._spherical.radius;const e=this._camera.getEffectiveFOV()*De,i=2*Math.atan(Math.tan(.5*e)*this._camera.aspect),s=1<this._camera.aspect?e:i;return t/Math.sin(.5*s)}getTarget(t,e=!0){return(t&&t.isVector3?t:new Ye.Vector3).copy(e?this._targetEnd:this._target)}getPosition(t,e=!0){return(t&&t.isVector3?t:new Ye.Vector3).setFromSpherical(e?this._sphericalEnd:this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(e?this._targetEnd:this._target)}getSpherical(t,e=!0){return(t||new Ye.Spherical).copy(e?this._sphericalEnd:this._spherical)}getFocalOffset(t,e=!0){return(t&&t.isVector3?t:new Ye.Vector3).copy(e?this._focalOffsetEnd:this._focalOffset)}normalizeRotations(){this._sphericalEnd.theta=this._sphericalEnd.theta%Ie,this._sphericalEnd.theta<0&&(this._sphericalEnd.theta+=Ie),this._spherical.theta+=Ie*Math.round((this._sphericalEnd.theta-this._spherical.theta)/Ie)}stop(){this._focalOffset.copy(this._focalOffsetEnd),this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd),this._zoom=this._zoomEnd}reset(t=!1){if(!Be(this._camera.up.x,this._cameraUp0.x)||!Be(this._camera.up.y,this._cameraUp0.y)||!Be(this._camera.up.z,this._cameraUp0.z)){this._camera.up.copy(this._cameraUp0);const t=this.getPosition(Ke);this.updateCameraUp(),this.setPosition(t.x,t.y,t.z)}const e=[this.setLookAt(this._position0.x,this._position0.y,this._position0.z,this._target0.x,this._target0.y,this._target0.z,t),this.setFocalOffset(this._focalOffset0.x,this._focalOffset0.y,this._focalOffset0.z,t),this.zoomTo(this._zoom0,t)];return Promise.all(e)}saveState(){this._cameraUp0.copy(this._camera.up),this.getTarget(this._target0),this.getPosition(this._position0),this._zoom0=this._zoom,this._focalOffset0.copy(this._focalOffset)}updateCameraUp(){this._yAxisUpSpace.setFromUnitVectors(this._camera.up,Xe),this._yAxisUpSpaceInverse.copy(this._yAxisUpSpace).invert()}applyCameraUp(){const t=Ke.subVectors(this._target,this._camera.position).normalize(),e=Je.crossVectors(t,this._camera.up);this._camera.up.crossVectors(e,t).normalize(),this._camera.updateMatrixWorld();const i=this.getPosition(Ke);this.updateCameraUp(),this.setPosition(i.x,i.y,i.z)}update(t){const e=this._sphericalEnd.theta-this._spherical.theta,i=this._sphericalEnd.phi-this._spherical.phi,s=this._sphericalEnd.radius-this._spherical.radius,n=ri.subVectors(this._targetEnd,this._target),r=oi.subVectors(this._focalOffsetEnd,this._focalOffset),o=this._zoomEnd-this._zoom;if(ze(e))this._thetaVelocity.value=0,this._spherical.theta=this._sphericalEnd.theta;else{const e=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.theta=Re(this._spherical.theta,this._sphericalEnd.theta,this._thetaVelocity,e,1/0,t),this._needsUpdate=!0}if(ze(i))this._phiVelocity.value=0,this._spherical.phi=this._sphericalEnd.phi;else{const e=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.phi=Re(this._spherical.phi,this._sphericalEnd.phi,this._phiVelocity,e,1/0,t),this._needsUpdate=!0}if(ze(s))this._radiusVelocity.value=0,this._spherical.radius=this._sphericalEnd.radius;else{const e=this._isUserControllingDolly?this.draggingSmoothTime:this.smoothTime;this._spherical.radius=Re(this._spherical.radius,this._sphericalEnd.radius,this._radiusVelocity,e,this.maxSpeed,t),this._needsUpdate=!0}if(ze(n.x)&&ze(n.y)&&ze(n.z))this._targetVelocity.set(0,0,0),this._target.copy(this._targetEnd);else{const e=this._isUserControllingTruck?this.draggingSmoothTime:this.smoothTime;Fe(this._target,this._targetEnd,this._targetVelocity,e,this.maxSpeed,t,this._target),this._needsUpdate=!0}if(ze(r.x)&&ze(r.y)&&ze(r.z))this._focalOffsetVelocity.set(0,0,0),this._focalOffset.copy(this._focalOffsetEnd);else{const e=this._isUserControllingOffset?this.draggingSmoothTime:this.smoothTime;Fe(this._focalOffset,this._focalOffsetEnd,this._focalOffsetVelocity,e,this.maxSpeed,t,this._focalOffset),this._needsUpdate=!0}if(ze(o))this._zoomVelocity.value=0,this._zoom=this._zoomEnd;else{const e=this._isUserControllingZoom?this.draggingSmoothTime:this.smoothTime;this._zoom=Re(this._zoom,this._zoomEnd,this._zoomVelocity,e,1/0,t)}if(this.dollyToCursor)if(Oe(this._camera)&&0!==this._changedDolly){const t=this._spherical.radius-this._lastDistance,e=this._camera,i=this._getCameraDirection(ei),s=Ke.copy(i).cross(e.up).normalize();0===s.lengthSq()&&(s.x=1);const n=Je.crossVectors(s,i),r=this._sphericalEnd.radius*Math.tan(e.getEffectiveFOV()*De*.5),o=(this._sphericalEnd.radius-t-this._sphericalEnd.radius)/this._sphericalEnd.radius,a=ti.copy(this._targetEnd).add(s.multiplyScalar(this._dollyControlCoord.x*r*e.aspect)).add(n.multiplyScalar(this._dollyControlCoord.y*r)),l=Ke.copy(this._targetEnd).lerp(a,o),h=this._lastDollyDirection===Se&&this._spherical.radius<=this.minDistance,c=this._lastDollyDirection===Ae&&this.maxDistance<=this._spherical.radius;if(this.infinityDolly&&(h||c)){this._sphericalEnd.radius-=t,this._spherical.radius-=t;const e=Je.copy(i).multiplyScalar(-t);l.add(e)}this._boundary.clampPoint(l,l);const d=Je.subVectors(l,this._targetEnd);this._targetEnd.copy(l),this._target.add(d),this._changedDolly-=t,ze(this._changedDolly)&&(this._changedDolly=0)}else if(Pe(this._camera)&&0!==this._changedZoom){const t=this._zoom-this._lastZoom,e=this._camera,i=Ke.set(this._dollyControlCoord.x,this._dollyControlCoord.y,(e.near+e.far)/(e.near-e.far)).unproject(e),s=Je.set(0,0,-1).applyQuaternion(e.quaternion),n=ti.copy(i).add(s.multiplyScalar(-i.dot(e.up))),r=-(this._zoom-t-this._zoom)/this._zoom,o=this._getCameraDirection(ei),a=this._targetEnd.dot(o),l=Ke.copy(this._targetEnd).lerp(n,r),h=l.dot(o),c=o.multiplyScalar(h-a);l.sub(c),this._boundary.clampPoint(l,l);const d=Je.subVectors(l,this._targetEnd);this._targetEnd.copy(l),this._target.add(d),this._changedZoom-=t,ze(this._changedZoom)&&(this._changedZoom=0)}this._camera.zoom!==this._zoom&&(this._camera.zoom=this._zoom,this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0),this._dragNeedsUpdate=!0;const a=this._collisionTest();this._spherical.radius=Math.min(this._spherical.radius,a),this._spherical.makeSafe(),this._camera.position.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(this._target),this._camera.lookAt(this._target);(!ze(this._focalOffset.x)||!ze(this._focalOffset.y)||!ze(this._focalOffset.z))&&(ii.setFromMatrixColumn(this._camera.matrix,0),si.setFromMatrixColumn(this._camera.matrix,1),ni.setFromMatrixColumn(this._camera.matrix,2),ii.multiplyScalar(this._focalOffset.x),si.multiplyScalar(-this._focalOffset.y),ni.multiplyScalar(this._focalOffset.z),Ke.copy(ii).add(si).add(ni),this._camera.position.add(Ke),this._camera.updateMatrixWorld()),this._boundaryEnclosesCamera&&this._encloseToBoundary(this._camera.position.copy(this._target),Ke.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse),1);const l=this._needsUpdate;return l&&!this._updatedLastTime?(this._hasRested=!1,this.dispatchEvent({type:"wake"}),this.dispatchEvent({type:"update"})):l?(this.dispatchEvent({type:"update"}),ze(e,this.restThreshold)&&ze(i,this.restThreshold)&&ze(s,this.restThreshold)&&ze(n.x,this.restThreshold)&&ze(n.y,this.restThreshold)&&ze(n.z,this.restThreshold)&&ze(r.x,this.restThreshold)&&ze(r.y,this.restThreshold)&&ze(r.z,this.restThreshold)&&ze(o,this.restThreshold)&&!this._hasRested&&(this._hasRested=!0,this.dispatchEvent({type:"rest"}))):!l&&this._updatedLastTime&&this.dispatchEvent({type:"sleep"}),this._lastDistance=this._spherical.radius,this._lastZoom=this._zoom,this._updatedLastTime=l,this._needsUpdate=!1,l}toJSON(){return JSON.stringify({enabled:this._enabled,minDistance:this.minDistance,maxDistance:Ue(this.maxDistance),minZoom:this.minZoom,maxZoom:Ue(this.maxZoom),minPolarAngle:this.minPolarAngle,maxPolarAngle:Ue(this.maxPolarAngle),minAzimuthAngle:Ue(this.minAzimuthAngle),maxAzimuthAngle:Ue(this.maxAzimuthAngle),smoothTime:this.smoothTime,draggingSmoothTime:this.draggingSmoothTime,dollySpeed:this.dollySpeed,truckSpeed:this.truckSpeed,dollyToCursor:this.dollyToCursor,target:this._targetEnd.toArray(),position:Ke.setFromSpherical(this._sphericalEnd).add(this._targetEnd).toArray(),zoom:this._zoomEnd,focalOffset:this._focalOffsetEnd.toArray(),target0:this._target0.toArray(),position0:this._position0.toArray(),zoom0:this._zoom0,focalOffset0:this._focalOffset0.toArray()})}fromJSON(t,e=!1){const i=JSON.parse(t);this.enabled=i.enabled,this.minDistance=i.minDistance,this.maxDistance=Le(i.maxDistance),this.minZoom=i.minZoom,this.maxZoom=Le(i.maxZoom),this.minPolarAngle=i.minPolarAngle,this.maxPolarAngle=Le(i.maxPolarAngle),this.minAzimuthAngle=Le(i.minAzimuthAngle),this.maxAzimuthAngle=Le(i.maxAzimuthAngle),this.smoothTime=i.smoothTime,this.draggingSmoothTime=i.draggingSmoothTime,this.dollySpeed=i.dollySpeed,this.truckSpeed=i.truckSpeed,this.dollyToCursor=i.dollyToCursor,this._target0.fromArray(i.target0),this._position0.fromArray(i.position0),this._zoom0=i.zoom0,this._focalOffset0.fromArray(i.focalOffset0),this.moveTo(i.target[0],i.target[1],i.target[2],e),ai.setFromVector3(Ke.fromArray(i.position).sub(this._targetEnd).applyQuaternion(this._yAxisUpSpace)),this.rotateTo(ai.theta,ai.phi,e),this.dollyTo(ai.radius,e),this.zoomTo(i.zoom,e),this.setFocalOffset(i.focalOffset[0],i.focalOffset[1],i.focalOffset[2],e),this._needsUpdate=!0}connect(t){this._domElement?console.warn("camera-controls is already connected."):(t.setAttribute("data-camera-controls-version","2.10.1"),this._addAllEventListeners(t),this._getClientRect(this._elementRect))}disconnect(){this.cancel(),this._removeAllEventListeners(),this._domElement&&(this._domElement.removeAttribute("data-camera-controls-version"),this._domElement=void 0)}dispose(){this.removeAllEventListeners(),this.disconnect()}_getTargetDirection(t){return t.setFromSpherical(this._spherical).divideScalar(this._spherical.radius).applyQuaternion(this._yAxisUpSpaceInverse)}_getCameraDirection(t){return this._getTargetDirection(t).negate()}_findPointerById(t){return this._activePointers.find(e=>e.pointerId===t)}_findPointerByMouseButton(t){return this._activePointers.find(e=>e.mouseButton===t)}_disposePointer(t){this._activePointers.splice(this._activePointers.indexOf(t),1)}_encloseToBoundary(t,e,i){const s=e.lengthSq();if(0===s)return t;const n=Je.copy(e).add(t),r=this._boundary.clampPoint(n,ti).sub(n),o=r.lengthSq();if(0===o)return t.add(e);if(o===s)return t;if(0===i)return t.add(e).add(r);{const s=1+i*o/e.dot(r);return t.add(Je.copy(e).multiplyScalar(s)).add(r.multiplyScalar(1-i))}}_updateNearPlaneCorners(){if(Oe(this._camera)){const t=this._camera,e=t.near,i=t.getEffectiveFOV()*De,s=Math.tan(.5*i)*e,n=s*t.aspect;this._nearPlaneCorners[0].set(-n,-s,0),this._nearPlaneCorners[1].set(n,-s,0),this._nearPlaneCorners[2].set(n,s,0),this._nearPlaneCorners[3].set(-n,s,0)}else if(Pe(this._camera)){const t=this._camera,e=1/t.zoom,i=t.left*e,s=t.right*e,n=t.top*e,r=t.bottom*e;this._nearPlaneCorners[0].set(i,n,0),this._nearPlaneCorners[1].set(s,n,0),this._nearPlaneCorners[2].set(s,r,0),this._nearPlaneCorners[3].set(i,r,0)}}_collisionTest(){let t=1/0;if(!(this.colliderMeshes.length>=1))return t;if(je(this._camera,"_collisionTest"))return t;const e=this._getTargetDirection(ei);fi.lookAt(Ge,e,this._camera.up);for(let i=0;i<4;i++){const s=Je.copy(this._nearPlaneCorners[i]);s.applyMatrix4(fi);const n=ti.addVectors(this._target,s);mi.set(n,e),mi.far=this._spherical.radius+1;const r=mi.intersectObjects(this.colliderMeshes);0!==r.length&&r[0].distance<t&&(t=r[0].distance)}return t}_getClientRect(t){if(!this._domElement)return;const e=this._domElement.getBoundingClientRect();return t.x=e.left,t.y=e.top,this._viewport?(t.x+=this._viewport.x,t.y+=e.height-this._viewport.w-this._viewport.y,t.width=this._viewport.z,t.height=this._viewport.w):(t.width=e.width,t.height=e.height),t}_createOnRestPromise(t){return t?Promise.resolve():(this._hasRested=!1,this.dispatchEvent({type:"transitionstart"}),new Promise(t=>{const e=()=>{this.removeEventListener("rest",e),t()};this.addEventListener("rest",e)}))}_addAllEventListeners(t){}_removeAllEventListeners(){}get dampingFactor(){return console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead."),0}set dampingFactor(t){console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead.")}get draggingDampingFactor(){return console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead."),0}set draggingDampingFactor(t){console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead.")}static createBoundingSphere(t,e=new Ye.Sphere){const i=e,s=i.center;hi.makeEmpty(),t.traverseVisible(t=>{t.isMesh&&hi.expandByObject(t)}),hi.getCenter(s);let n=0;return t.traverseVisible(t=>{if(!t.isMesh)return;const e=t;if(!e.geometry)return;const i=e.geometry.clone();i.applyMatrix4(e.matrixWorld);const r=i.attributes.position;for(let t=0,e=r.count;t<e;t++)Ke.fromBufferAttribute(r,t),n=Math.max(n,s.distanceToSquared(Ke))}),i.radius=Math.sqrt(n),i}}class _i extends p{constructor(t){super(t),e(this,"onBeforeUpdate",new h),e(this,"onAfterUpdate",new h),e(this,"onAspectUpdated",new h),e(this,"onDisposed",new h),e(this,"three"),e(this,"_allControls",new Map),e(this,"updateAspect",()=>{var t;if(this.currentWorld&&this.currentWorld.renderer)if(this.three instanceof a.OrthographicCamera)this.onAspectUpdated.trigger();else if(null==(t=this.currentWorld.renderer)?void 0:t.isResizeable()){const t=this.currentWorld.renderer.getSize();this.three.aspect=t.width/t.height,this.three.updateProjectionMatrix(),this.onAspectUpdated.trigger()}}),this.three=this.setupCamera(),this.setupEvents(!0),this.worlds.onItemSet.add(({value:t})=>{const e=this.newCameraControls();this._allControls.set(t.uuid,e)}),this.worlds.onBeforeDelete.add(({value:t})=>{const e=this._allControls.get(t.uuid);e&&(e.dispose(),this._allControls.delete(t.uuid))})}get controls(){if(!this.currentWorld)throw new Error("This camera needs a world to work!");const t=this._allControls.get(this.currentWorld.uuid);if(!t)throw new Error("Controls not found!");return t}get enabled(){return null!==this.currentWorld&&this.controls.enabled}set enabled(t){null!==this.currentWorld&&(this.controls.enabled=t)}set currentWorld(t){if(super.currentWorld=t,!t)return;this.worlds.get(t.uuid)||this.worlds.set(t.uuid,t)}get currentWorld(){return this._currentWorld}dispose(){this.setupEvents(!1),this.onAspectUpdated.reset(),this.onBeforeUpdate.reset(),this.onAfterUpdate.reset(),this.three.removeFromParent(),this.onDisposed.trigger(),this.onDisposed.reset();for(const[t,e]of this._allControls)e.dispose();this.worlds.clear()}async fitToItems(t){const e=await this.getItemsBounding(t);await this.controls.fitToSphere(e,!0)}async setOrbitToItems(t){const e=await this.getItemsBounding(t);this.controls.setOrbitPoint(e.center.x,e.center.y,e.center.z)}update(t){this.enabled&&(this.onBeforeUpdate.trigger(this),this.controls.update(t),this.onAfterUpdate.trigger(this))}async getItemsBounding(t){const e=this.components.get(qt),i=this.components.get(se);i.list.clear();const s=new a.Sphere;if(t)await i.addFromModelIdMap(t);else for(const[,t]of e.list)i.list.add(t.box);return i.get().getBoundingSphere(s),i.list.clear(),s}setupCamera(){const t=window.innerWidth/window.innerHeight,e=new a.PerspectiveCamera(60,t,1,1e3);return e.position.set(50,50,50),e.lookAt(new a.Vector3(0,0,0)),e}newCameraControls(){if(!this.currentWorld)throw new Error("This camera needs a world to work!");if(!this.currentWorld.renderer)throw new Error("This camera needs a renderer to work!");gi.install({THREE:_i.getSubsetOfThree()});const{domElement:t}=this.currentWorld.renderer.three,e=new gi(this.three,t);return e.smoothTime=.2,e.dollyToCursor=!0,e.infinityDolly=!0,e.minDistance=6,e}setupEvents(t){t?window.addEventListener("resize",this.updateAspect):window.removeEventListener("resize",this.updateAspect)}static getSubsetOfThree(){return{MOUSE:a.MOUSE,Vector2:a.Vector2,Vector3:a.Vector3,Vector4:a.Vector4,Quaternion:a.Quaternion,Matrix4:a.Matrix4,Spherical:a.Spherical,Box3:a.Box3,Sphere:a.Sphere,Raycaster:a.Raycaster,MathUtils:a.MathUtils}}}const yi=class t extends d{constructor(s){super(s),e(this,"onAfterUpdate",new h),e(this,"onBeforeUpdate",new h),e(this,"onDisposed",new h),e(this,"list",new i.DataMap),e(this,"enabled",!0),s.add(t.uuid,this)}create(){const t=new me(this.components),e=t.uuid;if(this.list.has(e))throw new Error("There is already a world with this name!");return this.list.set(e,t),t}delete(t){if(!this.list.has(t.uuid))throw new Error("The provided world is not found in the list!");this.list.delete(t.uuid),t.dispose()}dispose(){this.enabled=!1;for(const[t,e]of this.list)e.dispose();this.list.clear(),this.onDisposed.trigger()}update(t){if(this.enabled)for(const[e,i]of this.list)i.update(t)}};e(yi,"uuid","fdb61dc4-2ec1-4966-b83d-54ea795fad4a");let wi=yi;class vi extends $t{constructor(){super(...arguments),e(this,"_config",{visible:{value:!0,type:"Boolean"},color:{value:new a.Color,type:"Color"},primarySize:{type:"Number",interpolable:!0,value:1,min:0,max:1e3},secondarySize:{type:"Number",interpolable:!0,value:10,min:0,max:1e3},distance:{type:"Number",interpolable:!0,value:500,min:0,max:500}})}get visible(){return this._config.visible.value}set visible(t){this._config.visible.value=t,this._component.visible=t}get color(){return this._config.color.value}set color(t){this._config.color.value=t,this._component.material.uniforms.uColor.value=t,this._component.material.uniformsNeedUpdate=!0}get primarySize(){return this._config.primarySize.value}set primarySize(t){this._config.primarySize.value=t,this._component.material.uniforms.uSize1.value=t,this._component.material.uniformsNeedUpdate=!0}get secondarySize(){return this._config.secondarySize.value}set secondarySize(t){this._config.secondarySize.value=t,this._component.material.uniforms.uSize2.value=t,this._component.material.uniformsNeedUpdate=!0}get distance(){return this._config.distance.value}set distance(t){this._config.distance.value=t,this._component.material.uniforms.uDistance.value=t,this._component.material.uniformsNeedUpdate=!0}}class bi{constructor(t,i){e(this,"onDisposed",new h),e(this,"onSetup",new h),e(this,"isSetup",!1),e(this,"world"),e(this,"components"),e(this,"config"),e(this,"_defaultConfig",{visible:!0,color:new a.Color(12303291),primarySize:1,secondarySize:10,distance:500}),e(this,"three"),e(this,"_fade",3),e(this,"updateZoom",()=>{this.world.camera instanceof _i&&(this.material.uniforms.uZoom.value=this.world.camera.three.zoom)}),this.world=i;const{color:s,primarySize:n,secondarySize:r,distance:o}=this._defaultConfig;this.components=t,this.config=new vi(this,this.components,"Grid");const l=new a.PlaneGeometry(2,2,1,1),c=new a.ShaderMaterial({side:a.DoubleSide,uniforms:{uSize1:{value:n},uSize2:{value:r},uColor:{value:s},uDistance:{value:o},uFade:{value:this._fade},uZoom:{value:1}},transparent:!0,vertexShader:"\n \n varying vec3 worldPosition;\n \n uniform float uDistance;\n \n void main() {\n \n vec3 pos = position.xzy * uDistance;\n pos.xz += cameraPosition.xz;\n \n worldPosition = pos;\n \n gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);\n \n }\n ",fragmentShader:"\n \n varying vec3 worldPosition;\n \n uniform float uZoom;\n uniform float uFade;\n uniform float uSize1;\n uniform float uSize2;\n uniform vec3 uColor;\n uniform float uDistance;\n \n \n \n float getGrid(float size) {\n \n vec2 r = worldPosition.xz / size;\n \n \n vec2 grid = abs(fract(r - 0.5) - 0.5) / fwidth(r);\n float line = min(grid.x, grid.y);\n \n \n return 1.0 - min(line, 1.0);\n }\n \n void main() {\n \n \n float d = 1.0 - min(distance(cameraPosition.xz, worldPosition.xz) / uDistance, 1.0);\n \n float g1 = getGrid(uSize1);\n float g2 = getGrid(uSize2);\n \n // Ortho camera fades the grid away when zooming out\n float minZoom = step(0.2, uZoom);\n float zoomFactor = pow(min(uZoom, 1.), 2.) * minZoom;\n \n gl_FragColor = vec4(uColor.rgb, mix(g2, g1, g1) * pow(d, uFade));\n gl_FragColor.a = mix(0.5 * gl_FragColor.a, gl_FragColor.a, g2) * zoomFactor;\n \n if ( gl_FragColor.a <= 0.0 ) discard;\n \n \n }\n \n ",extensions:{derivatives:!0}});this.three=new a.Mesh(l,c),this.three.frustumCulled=!1,i.scene.three.add(this.three),this.setupEvents(!0)}get visible(){return this.three.visible}set visible(t){if(this.three.visible=t,t){this.world.scene.three.add(this.three)}else this.three.removeFromParent()}get material(){return this.three.material}get fade(){return 3===this._fade}set fade(t){this._fade=t?3:0,this.material.uniforms.uFade.value=this._fade}setup(t){const e={...this._defaultConfig,...t};this.config.visible=!0,this.config.color=e.color,this.config.primarySize=e.primarySize,this.config.secondarySize=e.secondarySize,this.config.distance=e.distance,this.isSetup=!0,this.onSetup.trigger()}dispose(){this.setupEvents(!1);this.components.get(Yt).list.delete(this.config.uuid);this.components.get(g).destroy(this.three),this.onDisposed.trigger(),this.onDisposed.reset(),this.world=null,this.components=null}setupEvents(t){if(this.world.isDisposing)return;if(!(this.world.camera instanceof _i))return;const e=this.world.camera.controls;t?e.addEventListener("update",this.updateZoom):e.removeEventListener("update",this.updateZoom)}}const xi=class t extends d{constructor(i){super(i),e(this,"list",new Map),e(this,"onDisposed",new h),e(this,"enabled",!0),i.add(t.uuid,this)}create(t){if(this.list.has(t.uuid))throw new Error("This world already has a grid!");const e=new bi(this.components,t);return this.list.set(t.uuid,e),t.onDisposed.add(()=>{this.delete(t)}),e}delete(t){const e=this.list.get(t.uuid);e&&e.dispose(),this.list.delete(t.uuid)}dispose(){for(const[t,e]of this.list)e.dispose();this.list.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}};e(xi,"uuid","d1e814d5-b81c-4452-87a2-f039375e0489");let Ti=xi;const Ci=1.25,Ei=65535,Si=Math.pow(2,-24),Ai=Symbol("SKIP_GENERATION");function Oi(t){return function(t){return t.index?t.index.count:t.attributes.position.count}(t)/3}function Pi(t,e){if(!t.index){const i=t.attributes.position.count,n=function(t,e=ArrayBuffer){return t>65535?new Uint32Array(new e(4*t)):new Uint16Array(new e(2*t))}(i,e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer);t.setIndex(new s.BufferAttribute(n,1));for(let t=0;t<i;t++)n[t]=t}}function Ii(t){const e=Oi(t),i=t.drawRange,s=i.start/3,n=(i.start+i.count)/3,r=Math.max(0,s),o=Math.min(e,n)-r;return[{offset:Math.floor(r),count:Math.floor(o)}]}function Mi(t){if(!t.groups||!t.groups.length)return Ii(t);const e=[],i=new Set,s=t.drawRange,n=s.start/3,r=(s.start+s.count)/3;for(const e of t.groups){const t=e.start/3,s=(e.start+e.count)/3;i.add(Math.max(n,t)),i.add(Math.min(r,s))}const o=Array.from(i.values()).sort((t,e)=>t-e);for(let t=0;t<o.length-1;t++){const i=o[t],s=o[t+1];e.push({offset:Math.floor(i),count:Math.floor(s-i)})}return e}function Di(t,e,i){return i.min.x=e[t],i.min.y=e[t+1],i.min.z=e[t+2],i.max.x=e[t+3],i.max.y=e[t+4],i.max.z=e[t+5],i}function ki(t){let e=-1,i=-1/0;for(let s=0;s<3;s++){const n=t[s+3]-t[s];n>i&&(i=n,e=s)}return e}function zi(t,e){e.set(t)}function Bi(t,e,i){let s,n;for(let r=0;r<3;r++){const o=r+3;s=t[r],n=e[r],i[r]=s<n?s:n,s=t[o],n=e[o],i[o]=s>n?s:n}}function Ni(t,e,i){for(let s=0;s<3;s++){const n=e[t+2*s],r=e[t+2*s+1],o=n-r,a=n+r;o<i[s]&&(i[s]=o),a>i[s+3]&&(i[s+3]=a)}}function Ui(t){const e=t[3]-t[0],i=t[4]-t[1],s=t[5]-t[2];return 2*(e*i+i*s+s*e)}function Li(t,e,i,s,n=null){let r=1/0,o=1/0,a=1/0,l=-1/0,h=-1/0,c=-1/0,d=1/0,u=1/0,p=1/0,f=-1/0,m=-1/0,g=-1/0;const _=null!==n;for(let s=6*e,n=6*(e+i);s<n;s+=6){const e=t[s+0],i=t[s+1],n=e-i,y=e+i;n<r&&(r=n),y>l&&(l=y),_&&e<d&&(d=e),_&&e>f&&(f=e);const w=t[s+2],v=t[s+3],b=w-v,x=w+v;b<o&&(o=b),x>h&&(h=x),_&&w<u&&(u=w),_&&w>m&&(m=w);const T=t[s+4],C=t[s+5],E=T-C,S=T+C;E<a&&(a=E),S>c&&(c=S),_&&T<p&&(p=T),_&&T>g&&(g=T)}s[0]=r,s[1]=o,s[2]=a,s[3]=l,s[4]=h,s[5]=c,_&&(n[0]=d,n[1]=u,n[2]=p,n[3]=f,n[4]=m,n[5]=g)}const Ri=32,Fi=(t,e)=>t.candidate-e.candidate,Vi=new Array(Ri).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),ji=new Float32Array(6);class Hi{constructor(){}}function Zi(t,e,i,s,n,r){let o=s,a=s+n-1;const l=r.pos,h=2*r.axis;for(;;){for(;o<=a&&i[6*o+h]<l;)o++;for(;o<=a&&i[6*a+h]>=l;)a--;if(!(o<a))return o;for(let t=0;t<3;t++){let i=e[3*o+t];e[3*o+t]=e[3*a+t],e[3*a+t]=i}for(let t=0;t<6;t++){let e=i[6*o+t];i[6*o+t]=i[6*a+t],i[6*a+t]=e}o++,a--}}function $i(t,e,i,s,n,r){let o=s,a=s+n-1;const l=r.pos,h=2*r.axis;for(;;){for(;o<=a&&i[6*o+h]<l;)o++;for(;o<=a&&i[6*a+h]>=l;)a--;if(!(o<a))return o;{let e=t[o];t[o]=t[a],t[a]=e;for(let t=0;t<6;t++){let e=i[6*o+t];i[6*o+t]=i[6*a+t],i[6*a+t]=e}o++,a--}}}function Wi(t,e){const i=t.geometry,s=i.index?i.index.array:null,n=e.maxDepth,r=e.verbose,o=e.maxLeafTris,a=e.strategy,l=e.onProgress,h=Oi(i),c=t._indirectBuffer;let d=!1;const u=new Float32Array(6),p=new Float32Array(6),f=function(t,e){var i;(i=e)[0]=i[1]=i[2]=1/0,i[3]=i[4]=i[5]=-1/0;const s=t.attributes.position,n=t.index?t.index.array:null,r=Oi(t),o=new Float32Array(6*r),a=s.normalized,l=s.array,h=s.offset||0;let c=3;s.isInterleavedBufferAttribute&&(c=s.data.stride);const d=["getX","getY","getZ"];for(let t=0;t<r;t++){const i=3*t,r=6*t;let u=i+0,p=i+1,f=i+2;n&&(u=n[u],p=n[p],f=n[f]),a||(u=u*c+h,p=p*c+h,f=f*c+h);for(let t=0;t<3;t++){let i,n,h;a?(i=s[d[t]](u),n=s[d[t]](p),h=s[d[t]](f)):(i=l[u+t],n=l[p+t],h=l[f+t]);let c=i;n<c&&(c=n),h<c&&(c=h);let m=i;n>m&&(m=n),h>m&&(m=h);const g=(m-c)/2,_=2*t;o[r+_+0]=c+g,o[r+_+1]=g+(Math.abs(c)+g)*Si,c<e[t]&&(e[t]=c),m>e[t+3]&&(e[t+3]=m)}}return o}(i,u),m=e.indirect?$i:Zi,g=[],_=e.indirect?Ii(i):Mi(i);if(1===_.length){const t=_[0],e=new Hi;e.boundingData=u,function(t,e,i,s){let n=1/0,r=1/0,o=1/0,a=-1/0,l=-1/0,h=-1/0;for(let s=6*e,c=6*(e+i);s<c;s+=6){const e=t[s+0];e<n&&(n=e),e>a&&(a=e);const i=t[s+2];i<r&&(r=i),i>l&&(l=i);const c=t[s+4];c<o&&(o=c),c>h&&(h=c)}s[0]=n,s[1]=r,s[2]=o,s[3]=a,s[4]=l,s[5]=h}(f,t.offset,t.count,p),w(e,t.offset,t.count,p),g.push(e)}else for(let t of _){const e=new Hi;e.boundingData=new Float32Array(6),Li(f,t.offset,t.count,e.boundingData,p),w(e,t.offset,t.count,p),g.push(e)}return g;function y(t){l&&l(t/h)}function w(t,e,l,h=null,u=0){if(!d&&u>=n&&(d=!0,r&&(console.warn(`MeshBVH: Max depth of ${n} reached when generating BVH. Consider increasing maxDepth.`),console.warn(i))),l<=o||u>=n)return y(e+l),t.offset=e,t.count=l,t;const g=function(t,e,i,s,n,r){let o=-1,a=0;if(0===r)o=ki(e),-1!==o&&(a=(e[o]+e[o+3])/2);else if(1===r)o=ki(t),-1!==o&&(a=function(t,e,i,s){let n=0;for(let r=e,o=e+i;r<o;r++)n+=t[6*r+2*s];return n/i}(i,s,n,o));else if(2===r){const r=Ui(t);let l=Ci*n;const h=6*s,c=6*(s+n);for(let t=0;t<3;t++){const s=e[t],d=(e[t+3]-s)/Ri;if(n<8){const e=[...Vi];e.length=n;let s=0;for(let n=h;n<c;n+=6,s++){const r=e[s];r.candidate=i[n+2*t],r.count=0;const{bounds:o,leftCacheBounds:a,rightCacheBounds:l}=r;for(let t=0;t<3;t++)l[t]=1/0,l[t+3]=-1/0,a[t]=1/0,a[t+3]=-1/0,o[t]=1/0,o[t+3]=-1/0;Ni(n,i,o)}e.sort(Fi);let d=n;for(let t=0;t<d;t++){const i=e[t];for(;t+1<d&&e[t+1].candidate===i.candidate;)e.splice(t+1,1),d--}for(let s=h;s<c;s+=6){const n=i[s+2*t];for(let t=0;t<d;t++){const r=e[t];n>=r.candidate?Ni(s,i,r.rightCacheBounds):(Ni(s,i,r.leftCacheBounds),r.count++)}}for(let i=0;i<d;i++){const s=e[i],h=s.count,c=n-s.count,d=s.leftCacheBounds,u=s.rightCacheBounds;let p=0;0!==h&&(p=Ui(d)/r);let f=0;0!==c&&(f=Ui(u)/r);const m=1+Ci*(p*h+f*c);m<l&&(o=t,l=m,a=s.candidate)}}else{for(let t=0;t<Ri;t++){const e=Vi[t];e.count=0,e.candidate=s+d+t*d;const i=e.bounds;for(let t=0;t<3;t++)i[t]=1/0,i[t+3]=-1/0}for(let e=h;e<c;e+=6){let n=~~((i[e+2*t]-s)/d);n>=Ri&&(n=31);const r=Vi[n];r.count++,Ni(e,i,r.bounds)}const e=Vi[31];zi(e.bounds,e.rightCacheBounds);for(let t=30;t>=0;t--){const e=Vi[t],i=Vi[t+1];Bi(e.bounds,i.rightCacheBounds,e.rightCacheBounds)}let u=0;for(let e=0;e<31;e++){const i=Vi[e],s=i.count,h=i.bounds,c=Vi[e+1].rightCacheBounds;0!==s&&(0===u?zi(h,ji):Bi(h,ji,ji)),u+=s;let d=0,p=0;0!==u&&(d=Ui(ji)/r);const f=n-u;0!==f&&(p=Ui(c)/r);const m=1+Ci*(d*u+p*f);m<l&&(o=t,l=m,a=i.candidate)}}}}else console.warn(`MeshBVH: Invalid build strategy value ${r} used.`);return{axis:o,pos:a}}(t.boundingData,h,f,e,l,a);if(-1===g.axis)return y(e+l),t.offset=e,t.count=l,t;const _=m(c,s,f,e,l,g);if(_===e||_===e+l)y(e+l),t.offset=e,t.count=l;else{t.splitAxis=g.axis;const i=new Hi,s=e,n=_-e;t.left=i,i.boundingData=new Float32Array(6),Li(f,s,n,i.boundingData,p),w(i,s,n,p,u+1);const r=new Hi,o=_,a=l-n;t.right=r,r.boundingData=new Float32Array(6),Li(f,o,a,r.boundingData,p),w(r,o,a,p,u+1)}return t}}function Yi(t,e){const i=t.geometry;e.indirect&&(t._indirectBuffer=function(t,e){const i=(t.index?t.index.count:t.attributes.position.count)/3,s=i>65536,n=s?4:2,r=e?new SharedArrayBuffer(i*n):new ArrayBuffer(i*n),o=s?new Uint32Array(r):new Uint16Array(r);for(let t=0,e=o.length;t<e;t++)o[t]=t;return o}(i,e.useSharedArrayBuffer),function(t){if(0===t.groups.length)return!1;const e=Oi(t),i=Mi(t).sort((t,e)=>t.offset-e.offset),s=i[i.length-1];s.count=Math.min(e-s.offset,s.count);let n=0;return i.forEach(({count:t})=>n+=t),e!==n}(i)&&!e.verbose&&console.warn('MeshBVH: Provided geometry contains groups that do not fully span the vertex contents while using the "indirect" option. BVH may incorrectly report intersections on unrendered portions of the geometry.')),t._indirectBuffer||Pi(i,e);const s=Wi(t,e);let n,r,o;const a=[],l=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer;for(let t=0;t<s.length;t++){const e=s[t];const i=new l(32*h(e));n=new Float32Array(i),r=new Uint32Array(i),o=new Uint16Array(i),c(0,e),a.push(i)}return void(t._roots=a);function h(t){return t.count?1:1+h(t.left)+h(t.right)}function c(t,e){const i=t/4,s=t/2,a=!!e.count,l=e.boundingData;for(let t=0;t<6;t++)n[i+t]=l[t];if(a){const n=e.offset,a=e.count;return r[i+6]=n,o[s+14]=a,o[s+15]=Ei,t+32}{const s=e.left,n=e.right,o=e.splitAxis;let a;if(a=c(t+32,s),a/4>Math.pow(2,32))throw new Error("MeshBVH: Cannot store child pointer greater than 32 bits.");return r[i+6]=a/4,a=c(a,n),r[i+7]=o,a}}}class Gi{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(t,e){let i=1/0,s=-1/0;for(let n=0,r=t.length;n<r;n++){const r=t[n][e];i=r<i?r:i,s=r>s?r:s}this.min=i,this.max=s}setFromPoints(t,e){let i=1/0,s=-1/0;for(let n=0,r=e.length;n<r;n++){const r=e[n],o=t.dot(r);i=o<i?o:i,s=o>s?o:s}this.min=i,this.max=s}isSeparated(t){return this.min>t.max||t.min>this.max}}Gi.prototype.setFromBox=function(){const t=new s.Vector3;return function(e,i){const s=i.min,n=i.max;let r=1/0,o=-1/0;for(let i=0;i<=1;i++)for(let a=0;a<=1;a++)for(let l=0;l<=1;l++){t.x=s.x*i+n.x*(1-i),t.y=s.y*a+n.y*(1-a),t.z=s.z*l+n.z*(1-l);const h=e.dot(t);r=Math.min(h,r),o=Math.max(h,o)}this.min=r,this.max=o}}();const Xi=function(){const t=new s.Vector3,e=new s.Vector3,i=new s.Vector3;return function(s,n,r){const o=s.start,a=t,l=n.start,h=e;i.subVectors(o,l),t.subVectors(s.end,s.start),e.subVectors(n.end,n.start);const c=i.dot(h),d=h.dot(a),u=h.dot(h),p=i.dot(a),f=a.dot(a)*u-d*d;let m,g;m=0!==f?(c*d-p*u)/f:0,g=(c+m*d)/u,r.x=m,r.y=g}}(),qi=function(){const t=new s.Vector2,e=new s.Vector3,i=new s.Vector3;return function(s,n,r,o){Xi(s,n,t);let a=t.x,l=t.y;if(a>=0&&a<=1&&l>=0&&l<=1)return s.at(a,r),void n.at(l,o);if(a>=0&&a<=1)return l<0?n.at(0,o):n.at(1,o),void s.closestPointToPoint(o,!0,r);if(l>=0&&l<=1)return a<0?s.at(0,r):s.at(1,r),void n.closestPointToPoint(r,!0,o);{let t,h;t=a<0?s.start:s.end,h=l<0?n.start:n.end;const c=e,d=i;return s.closestPointToPoint(h,!0,e),n.closestPointToPoint(t,!0,i),c.distanceToSquared(h)<=d.distanceToSquared(t)?(r.copy(c),void o.copy(h)):(r.copy(t),void o.copy(d))}}}(),Qi=function(){const t=new s.Vector3,e=new s.Vector3,i=new s.Plane,n=new s.Line3;return function(s,r){const{radius:o,center:a}=s,{a:l,b:h,c:c}=r;n.start=l,n.end=h;if(n.closestPointToPoint(a,!0,t).distanceTo(a)<=o)return!0;n.start=l,n.end=c;if(n.closestPointToPoint(a,!0,t).distanceTo(a)<=o)return!0;n.start=h,n.end=c;if(n.closestPointToPoint(a,!0,t).distanceTo(a)<=o)return!0;const d=r.getPlane(i);if(Math.abs(d.distanceToPoint(a))<=o){const t=d.projectPoint(a,e);if(r.containsPoint(t))return!0}return!1}}();function Ki(t){return Math.abs(t)<1e-15}class Ji extends s.Triangle{constructor(...t){super(...t),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new s.Vector3),this.satBounds=new Array(4).fill().map(()=>new Gi),this.points=[this.a,this.b,this.c],this.sphere=new s.Sphere,this.plane=new s.Plane,this.needsUpdate=!0}intersectsSphere(t){return Qi(t,this)}update(){const t=this.a,e=this.b,i=this.c,s=this.points,n=this.satAxes,r=this.satBounds,o=n[0],a=r[0];this.getNormal(o),a.setFromPoints(o,s);const l=n[1],h=r[1];l.subVectors(t,e),h.setFromPoints(l,s);const c=n[2],d=r[2];c.subVectors(e,i),d.setFromPoints(c,s);const u=n[3],p=r[3];u.subVectors(i,t),p.setFromPoints(u,s),this.sphere.setFromPoints(this.points),this.plane.setFromNormalAndCoplanarPoint(o,t),this.needsUpdate=!1}}Ji.prototype.closestPointToSegment=function(){const t=new s.Vector3,e=new s.Vector3,i=new s.Line3;return function(s,n=null,r=null){const{start:o,end:a}=s,l=this.points;let h,c=1/0;for(let o=0;o<3;o++){const a=(o+1)%3;i.start.copy(l[o]),i.end.copy(l[a]),qi(i,s,t,e),h=t.distanceToSquared(e),h<c&&(c=h,n&&n.copy(t),r&&r.copy(e))}return this.closestPointToPoint(o,t),h=o.distanceToSquared(t),h<c&&(c=h,n&&n.copy(t),r&&r.copy(o)),this.closestPointToPoint(a,t),h=a.distanceToSquared(t),h<c&&(c=h,n&&n.copy(t),r&&r.copy(a)),Math.sqrt(c)}}(),Ji.prototype.intersectsTriangle=function(){const t=new Ji,e=new Array(3),i=new Array(3),n=new Gi,r=new Gi,o=new s.Vector3,a=new s.Vector3,l=new s.Vector3,h=new s.Vector3,c=new s.Vector3,d=new s.Line3,u=new s.Line3,p=new s.Line3,f=new s.Vector3;function m(t,e,i){const s=t.points;let n=0,r=-1;for(let t=0;t<3;t++){const{start:o,end:l}=d;o.copy(s[t]),l.copy(s[(t+1)%3]),d.delta(a);const h=Ki(e.distanceToPoint(o));if(Ki(e.normal.dot(a))&&h){i.copy(d),n=2;break}const c=e.intersectLine(d,f);if(!c&&h&&f.copy(o),(c||h)&&!Ki(f.distanceTo(l))){if(n<=1){(1===n?i.start:i.end).copy(f),h&&(r=n)}else if(n>=2){(1===r?i.start:i.end).copy(f),n=2;break}if(n++,2===n&&-1===r)break}}return n}return function(s,a=null,d=!1){this.needsUpdate&&this.update(),s.isExtendedTriangle?s.needsUpdate&&s.update():(t.copy(s),t.update(),s=t);const f=this.plane,g=s.plane;if(Math.abs(f.normal.dot(g.normal))>1-1e-10){const t=this.satBounds,l=this.satAxes;i[0]=s.a,i[1]=s.b,i[2]=s.c;for(let e=0;e<4;e++){const s=t[e],r=l[e];if(n.setFromPoints(r,i),s.isSeparated(n))return!1}const h=s.satBounds,c=s.satAxes;e[0]=this.a,e[1]=this.b,e[2]=this.c;for(let t=0;t<4;t++){const i=h[t],s=c[t];if(n.setFromPoints(s,e),i.isSeparated(n))return!1}for(let t=0;t<4;t++){const s=l[t];for(let t=0;t<4;t++){const a=c[t];if(o.crossVectors(s,a),n.setFromPoints(o,e),r.setFromPoints(o,i),n.isSeparated(r))return!1}}return a&&(d||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),a.start.set(0,0,0),a.end.set(0,0,0)),!0}{const t=m(this,g,u);if(1===t&&s.containsPoint(u.end))return a&&(a.start.copy(u.end),a.end.copy(u.end)),!0;if(2!==t)return!1;const e=m(s,f,p);if(1===e&&this.containsPoint(p.end))return a&&(a.start.copy(p.end),a.end.copy(p.end)),!0;if(2!==e)return!1;if(u.delta(l),p.delta(h),l.dot(h)<0){let t=p.start;p.start=p.end,p.end=t}const i=u.start.dot(l),n=u.end.dot(l),r=p.start.dot(l),o=p.end.dot(l);return(i===o||r===n||n<r!==i<o)&&(a&&(c.subVectors(u.start,p.start),c.dot(l)>0?a.start.copy(u.start):a.start.copy(p.start),c.subVectors(u.end,p.end),c.dot(l)<0?a.end.copy(u.end):a.end.copy(p.end)),!0)}}}(),Ji.prototype.distanceToPoint=function(){const t=new s.Vector3;return function(e){return this.closestPointToPoint(e,t),e.distanceTo(t)}}(),Ji.prototype.distanceToTriangle=function(){const t=new s.Vector3,e=new s.Vector3,i=["a","b","c"],n=new s.Line3,r=new s.Line3;return function(s,o=null,a=null){const l=o||a?n:null;if(this.intersectsTriangle(s,l))return(o||a)&&(o&&l.getCenter(o),a&&l.getCenter(a)),0;let h=1/0;for(let e=0;e<3;e++){let n;const r=i[e],l=s[r];this.closestPointToPoint(l,t),n=l.distanceToSquared(t),n<h&&(h=n,o&&o.copy(t),a&&a.copy(l));const c=this[r];s.closestPointToPoint(c,t),n=c.distanceToSquared(t),n<h&&(h=n,o&&o.copy(c),a&&a.copy(t))}for(let l=0;l<3;l++){const c=i[l],d=i[(l+1)%3];n.set(this[c],this[d]);for(let l=0;l<3;l++){const c=i[l],d=i[(l+1)%3];r.set(s[c],s[d]),qi(n,r,t,e);const u=t.distanceToSquared(e);u<h&&(h=u,o&&o.copy(t),a&&a.copy(e))}}return Math.sqrt(h)}}();class ts{constructor(t,e,i){this.isOrientedBox=!0,this.min=new s.Vector3,this.max=new s.Vector3,this.matrix=new s.Matrix4,this.invMatrix=new s.Matrix4,this.points=new Array(8).fill().map(()=>new s.Vector3),this.satAxes=new Array(3).fill().map(()=>new s.Vector3),this.satBounds=new Array(3).fill().map(()=>new Gi),this.alignedSatBounds=new Array(3).fill().map(()=>new Gi),this.needsUpdate=!1,t&&this.min.copy(t),e&&this.max.copy(e),i&&this.matrix.copy(i)}set(t,e,i){this.min.copy(t),this.max.copy(e),this.matrix.copy(i),this.needsUpdate=!0}copy(t){this.min.copy(t.min),this.max.copy(t.max),this.matrix.copy(t.matrix),this.needsUpdate=!0}}ts.prototype.update=function(){return function(){const t=this.matrix,e=this.min,i=this.max,s=this.points;for(let n=0;n<=1;n++)for(let r=0;r<=1;r++)for(let o=0;o<=1;o++){const a=s[1*n|2*r|4*o];a.x=n?i.x:e.x,a.y=r?i.y:e.y,a.z=o?i.z:e.z,a.applyMatrix4(t)}const n=this.satBounds,r=this.satAxes,o=s[0];for(let t=0;t<3;t++){const e=r[t],i=n[t],a=s[1<<t];e.subVectors(o,a),i.setFromPoints(e,s)}const a=this.alignedSatBounds;a[0].setFromPointsField(s,"x"),a[1].setFromPointsField(s,"y"),a[2].setFromPointsField(s,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}}(),ts.prototype.intersectsBox=function(){const t=new Gi;return function(e){this.needsUpdate&&this.update();const i=e.min,s=e.max,n=this.satBounds,r=this.satAxes,o=this.alignedSatBounds;if(t.min=i.x,t.max=s.x,o[0].isSeparated(t))return!1;if(t.min=i.y,t.max=s.y,o[1].isSeparated(t))return!1;if(t.min=i.z,t.max=s.z,o[2].isSeparated(t))return!1;for(let i=0;i<3;i++){const s=r[i],o=n[i];if(t.setFromBox(s,e),o.isSeparated(t))return!1}return!0}}(),ts.prototype.intersectsTriangle=function(){const t=new Ji,e=new Array(3),i=new Gi,n=new Gi,r=new s.Vector3;return function(s){this.needsUpdate&&this.update(),s.isExtendedTriangle?s.needsUpdate&&s.update():(t.copy(s),t.update(),s=t);const o=this.satBounds,a=this.satAxes;e[0]=s.a,e[1]=s.b,e[2]=s.c;for(let t=0;t<3;t++){const s=o[t],n=a[t];if(i.setFromPoints(n,e),s.isSeparated(i))return!1}const l=s.satBounds,h=s.satAxes,c=this.points;for(let t=0;t<3;t++){const e=l[t],s=h[t];if(i.setFromPoints(s,c),e.isSeparated(i))return!1}for(let t=0;t<3;t++){const s=a[t];for(let t=0;t<4;t++){const o=h[t];if(r.crossVectors(s,o),i.setFromPoints(r,e),n.setFromPoints(r,c),i.isSeparated(n))return!1}}return!0}}(),ts.prototype.closestPointToPoint=function(){return function(t,e){return this.needsUpdate&&this.update(),e.copy(t).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),e}}(),ts.prototype.distanceToPoint=function(){const t=new s.Vector3;return function(e){return this.closestPointToPoint(e,t),e.distanceTo(t)}}(),ts.prototype.distanceToBox=function(){const t=["x","y","z"],e=new Array(12).fill().map(()=>new s.Line3),i=new Array(12).fill().map(()=>new s.Line3),n=new s.Vector3,r=new s.Vector3;return function(s,o=0,a=null,l=null){if(this.needsUpdate&&this.update(),this.intersectsBox(s))return(a||l)&&(s.getCenter(r),this.closestPointToPoint(r,n),s.closestPointToPoint(n,r),a&&a.copy(n),l&&l.copy(r)),0;const h=o*o,c=s.min,d=s.max,u=this.points;let p=1/0;for(let t=0;t<8;t++){const e=u[t];r.copy(e).clamp(c,d);const i=e.distanceToSquared(r);if(i<p&&(p=i,a&&a.copy(e),l&&l.copy(r),i<h))return Math.sqrt(i)}let f=0;for(let s=0;s<3;s++)for(let n=0;n<=1;n++)for(let r=0;r<=1;r++){const o=(s+1)%3,a=(s+2)%3,l=1<<s|n<<o|r<<a,h=u[n<<o|r<<a],p=u[l];e[f].set(h,p);const m=t[s],g=t[o],_=t[a],y=i[f],w=y.start,v=y.end;w[m]=c[m],w[g]=n?c[g]:d[g],w[_]=r?c[_]:d[g],v[m]=d[m],v[g]=n?c[g]:d[g],v[_]=r?c[_]:d[g],f++}for(let t=0;t<=1;t++)for(let e=0;e<=1;e++)for(let i=0;i<=1;i++){r.x=t?d.x:c.x,r.y=e?d.y:c.y,r.z=i?d.z:c.z,this.closestPointToPoint(r,n);const s=r.distanceToSquared(n);if(s<p&&(p=s,a&&a.copy(n),l&&l.copy(r),s<h))return Math.sqrt(s)}for(let t=0;t<12;t++){const s=e[t];for(let t=0;t<12;t++){const e=i[t];qi(s,e,n,r);const o=n.distanceToSquared(r);if(o<p&&(p=o,a&&a.copy(n),l&&l.copy(r),o<h))return Math.sqrt(o)}}return Math.sqrt(p)}}();class es{constructor(t){this._getNewPrimitive=t,this._primitives=[]}getPrimitive(){const t=this._primitives;return 0===t.length?this._getNewPrimitive():t.pop()}releasePrimitive(t){this._primitives.push(t)}}class is extends es{constructor(){super(()=>new Ji)}}const ss=new is;function ns(t,e){return 65535===e[t+15]}function rs(t,e){return e[t+6]}function os(t,e){return e[t+14]}function as(t){return t+8}function ls(t,e){return e[t+6]}function hs(t,e){return e[t+7]}function cs(t){return t}const ds=new class{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const t=[];let e=null;this.setBuffer=i=>{e&&t.push(e),e=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{e=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,0!==t.length&&this.setBuffer(t.pop())}}};let us,ps;const fs=[],ms=new es(()=>new s.Box3);function gs(t,e,i,s,n,r){us=ms.getPrimitive(),ps=ms.getPrimitive(),fs.push(us,ps),ds.setBuffer(t._roots[e]);const o=_s(0,t.geometry,i,s,n,r);ds.clearBuffer(),ms.releasePrimitive(us),ms.releasePrimitive(ps),fs.pop(),fs.pop();const a=fs.length;return a>0&&(ps=fs[a-1],us=fs[a-2]),o}function _s(t,e,i,s,n=null,r=0,o=0){const{float32Array:a,uint16Array:l,uint32Array:h}=ds;let c=2*t;if(ns(c,l)){const e=rs(t,h),i=os(c,l);return Di(t,a,us),s(e,i,!1,o,r+t,us)}{let c=function(t){const{uint16Array:e,uint32Array:i}=ds;let s=2*t;for(;!ns(s,e);)s=2*(t=as(t));return rs(t,i)},d=function(t){const{uint16Array:e,uint32Array:i}=ds;let s=2*t;for(;!ns(s,e);)s=2*(t=ls(t,i));return rs(t,i)+os(s,e)};const u=as(t),p=ls(t,h);let f,m,g,_,y=u,w=p;if(n&&(g=us,_=ps,Di(y,a,g),Di(w,a,_),f=n(g),m=n(_),m<f)){y=p,w=u;const t=f;f=m,m=t,g=_}g||(g=us,Di(y,a,g));const v=i(g,ns(2*y,l),f,o+1,r+y);let b;if(2===v){const t=c(y);b=s(t,d(y)-t,!0,o+1,r+y,g)}else b=v&&_s(y,e,i,s,n,r,o+1);if(b)return!0;_=ps,Di(w,a,_);const x=i(_,ns(2*w,l),m,o+1,r+w);let T;if(2===x){const t=c(w);T=s(t,d(w)-t,!0,o+1,r+w,_)}else T=x&&_s(w,e,i,s,n,r,o+1);return!!T}}const ys=new s.Vector3,ws=new s.Vector3;const vs=new s.Vector3,bs=new s.Vector3,xs=new s.Vector3,Ts=new s.Vector2,Cs=new s.Vector2,Es=new s.Vector2,Ss=new s.Vector3,As=new s.Vector3,Os=new s.Vector3,Ps=new s.Vector3;function Is(t,e,i,n,r,o,a,l,h){vs.fromBufferAttribute(e,o),bs.fromBufferAttribute(e,a),xs.fromBufferAttribute(e,l);const c=function(t,e,i,n,r,o){let a;return a=o===s.BackSide?t.intersectTriangle(n,i,e,!0,r):t.intersectTriangle(e,i,n,o!==s.DoubleSide,r),null===a?null:{distance:t.origin.distanceTo(r),point:r.clone()}}(t,vs,bs,xs,Ps,h);if(c){n&&(Ts.fromBufferAttribute(n,o),Cs.fromBufferAttribute(n,a),Es.fromBufferAttribute(n,l),c.uv=s.Triangle.getInterpolation(Ps,vs,bs,xs,Ts,Cs,Es,new s.Vector2)),r&&(Ts.fromBufferAttribute(r,o),Cs.fromBufferAttribute(r,a),Es.fromBufferAttribute(r,l),c.uv1=s.Triangle.getInterpolation(Ps,vs,bs,xs,Ts,Cs,Es,new s.Vector2)),i&&(Ss.fromBufferAttribute(i,o),As.fromBufferAttribute(i,a),Os.fromBufferAttribute(i,l),c.normal=s.Triangle.getInterpolation(Ps,vs,bs,xs,Ss,As,Os,new s.Vector3),c.normal.dot(t.direction)>0&&c.normal.multiplyScalar(-1));const e={a:o,b:a,c:l,normal:new s.Vector3,materialIndex:0};s.Triangle.getNormal(vs,bs,xs,e.normal),c.face=e,c.faceIndex=o}return c}function Ms(t,e,i,s,n){const r=3*s;let o=r+0,a=r+1,l=r+2;const h=t.index;t.index&&(o=h.getX(o),a=h.getX(a),l=h.getX(l));const{position:c,normal:d,uv:u,uv1:p}=t.attributes,f=Is(i,c,d,u,p,o,a,l,e);return f?(f.faceIndex=s,n&&n.push(f),f):null}function Ds(t,e,i,s){const n=t.a,r=t.b,o=t.c;let a=e,l=e+1,h=e+2;i&&(a=i.getX(a),l=i.getX(l),h=i.getX(h)),n.x=s.getX(a),n.y=s.getY(a),n.z=s.getZ(a),r.x=s.getX(l),r.y=s.getY(l),r.z=s.getZ(l),o.x=s.getX(h),o.y=s.getY(h),o.z=s.getZ(h)}function ks(t,e,i,s,n,r,o){const{geometry:a}=i,{index:l}=a,h=a.attributes.position;for(let i=t,a=e+t;i<a;i++){let t;if(t=i,Ds(o,3*t,l,h),o.needsUpdate=!0,s(o,t,n,r))return!0}return!1}function zs(t,e=null){e&&Array.isArray(e)&&(e=new Set(e));const i=t.geometry,s=i.index?i.index.array:null,n=i.attributes.position;let r,o,a,l,h=0;const c=t._roots;for(let t=0,e=c.length;t<e;t++)r=c[t],o=new Uint32Array(r),a=new Uint16Array(r),l=new Float32Array(r),d(0,h),h+=r.byteLength;function d(t,i,r=!1){const h=2*t;if(a[h+15]===Ei){const e=o[t+6];let i=1/0,r=1/0,c=1/0,d=-1/0,u=-1/0,p=-1/0;for(let t=3*e,o=3*(e+a[h+14]);t<o;t++){let e=s[t];const o=n.getX(e),a=n.getY(e),l=n.getZ(e);o<i&&(i=o),o>d&&(d=o),a<r&&(r=a),a>u&&(u=a),l<c&&(c=l),l>p&&(p=l)}return(l[t+0]!==i||l[t+1]!==r||l[t+2]!==c||l[t+3]!==d||l[t+4]!==u||l[t+5]!==p)&&(l[t+0]=i,l[t+1]=r,l[t+2]=c,l[t+3]=d,l[t+4]=u,l[t+5]=p,!0)}{const s=t+8,n=o[t+6],a=s+i,h=n+i;let c=r,u=!1,p=!1;e?c||(u=e.has(a),p=e.has(h),c=!u&&!p):(u=!0,p=!0);const f=c||p;let m=!1;(c||u)&&(m=d(s,i,c));let g=!1;f&&(g=d(n,i,c));const _=m||g;if(_)for(let e=0;e<3;e++){const i=s+e,r=n+e,o=l[i],a=l[i+3],h=l[r],c=l[r+3];l[t+e]=o<h?o:h,l[t+e+3]=a>c?a:c}return _}}}const Bs=new s.Box3;function Ns(t,e,i,s){return Di(t,e,Bs),i.intersectBox(Bs,s)}function Us(t,e,i,s,n,r,o){const{geometry:a}=i,{index:l}=a,h=a.attributes.position;for(let a=t,c=e+t;a<c;a++){let t;if(t=i.resolveTriangleIndex(a),Ds(o,3*t,l,h),o.needsUpdate=!0,s(o,t,n,r))return!0}return!1}const Ls=new s.Vector3;function Rs(t,e,i,s,n){ds.setBuffer(t._roots[e]),Fs(0,t,i,s,n),ds.clearBuffer()}function Fs(t,e,i,s,n){const{float32Array:r,uint16Array:o,uint32Array:a}=ds,l=2*t;if(ns(l,o)){!function(t,e,i,s,n,r){const{geometry:o,_indirectBuffer:a}=t;for(let t=s,a=s+n;t<a;t++)Ms(o,e,i,t,r)}(e,i,s,rs(t,a),os(l,o),n)}else{const o=as(t);Ns(o,r,s,Ls)&&Fs(o,e,i,s,n);const l=ls(t,a);Ns(l,r,s,Ls)&&Fs(l,e,i,s,n)}}const Vs=new s.Vector3,js=["x","y","z"];function Hs(t,e,i,s){ds.setBuffer(t._roots[e]);const n=Zs(0,t,i,s);return ds.clearBuffer(),n}function Zs(t,e,i,s){const{float32Array:n,uint16Array:r,uint32Array:o}=ds;let a=2*t;if(ns(a,r)){return function(t,e,i,s,n){const{geometry:r,_indirectBuffer:o}=t;let a=1/0,l=null;for(let t=s,o=s+n;t<o;t++){let s;s=Ms(r,e,i,t),s&&s.distance<a&&(l=s,a=s.distance)}return l}(e,i,s,rs(t,o),os(a,r))}{const r=hs(t,o),a=js[r],l=s.direction[a]>=0;let h,c;l?(h=as(t),c=ls(t,o)):(h=ls(t,o),c=as(t));const d=Ns(h,n,s,Vs)?Zs(h,e,i,s):null;if(d){const t=d.point[a];if(l?t<=n[c+r]:t>=n[c+r+3])return d}const u=Ns(c,n,s,Vs)?Zs(c,e,i,s):null;return d&&u?d.distance<=u.distance?d:u:d||u||null}}const $s=new s.Box3,Ws=new Ji,Ys=new Ji,Gs=new s.Matrix4,Xs=new ts,qs=new ts;function Qs(t,e,i,s){ds.setBuffer(t._roots[e]);const n=Ks(0,t,i,s);return ds.clearBuffer(),n}function Ks(t,e,i,s,n=null){const{float32Array:r,uint16Array:o,uint32Array:a}=ds;let l=2*t;null===n&&(i.boundingBox||i.computeBoundingBox(),Xs.set(i.boundingBox.min,i.boundingBox.max,s),n=Xs);if(!ns(l,o)){const o=t+8,l=a[t+6];Di(o,r,$s);if(n.intersectsBox($s)&&Ks(o,e,i,s,n))return!0;Di(l,r,$s);return!!(n.intersectsBox($s)&&Ks(l,e,i,s,n))}{const n=e.geometry,h=n.index,c=n.attributes.position,d=i.index,u=i.attributes.position,p=rs(t,a),f=os(l,o);if(Gs.copy(s).invert(),i.boundsTree){Di(t,r,qs),qs.matrix.copy(Gs),qs.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:t=>qs.intersectsBox(t),intersectsTriangle:t=>{t.a.applyMatrix4(s),t.b.applyMatrix4(s),t.c.applyMatrix4(s),t.needsUpdate=!0;for(let e=3*p,i=3*(f+p);e<i;e+=3)if(Ds(Ys,e,h,c),Ys.needsUpdate=!0,t.intersectsTriangle(Ys))return!0;return!1}})}for(let t=3*p,e=3*(f+p);t<e;t+=3){Ds(Ws,t,h,c),Ws.a.applyMatrix4(Gs),Ws.b.applyMatrix4(Gs),Ws.c.applyMatrix4(Gs),Ws.needsUpdate=!0;for(let t=0,e=d.count;t<e;t+=3)if(Ds(Ys,t,d,u),Ys.needsUpdate=!0,Ws.intersectsTriangle(Ys))return!0}}}const Js=new s.Matrix4,tn=new ts,en=new ts,sn=new s.Vector3,nn=new s.Vector3,rn=new s.Vector3,on=new s.Vector3;function an(t,e,i,s={},n={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),tn.set(e.boundingBox.min,e.boundingBox.max,i),tn.needsUpdate=!0;const a=t.geometry,l=a.attributes.position,h=a.index,c=e.attributes.position,d=e.index,u=ss.getPrimitive(),p=ss.getPrimitive();let f=sn,m=nn,g=null,_=null;n&&(g=rn,_=on);let y=1/0,w=null,v=null;return Js.copy(i).invert(),en.matrix.copy(Js),t.shapecast({boundsTraverseOrder:t=>tn.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o&&(e&&(en.min.copy(t.min),en.max.copy(t.max),en.needsUpdate=!0),!0),intersectsRange:(t,s)=>{if(e.boundsTree){return e.boundsTree.shapecast({boundsTraverseOrder:t=>en.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o,intersectsRange:(e,n)=>{for(let o=e,a=e+n;o<a;o++){Ds(p,3*o,d,c),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let e=t,i=t+s;e<i;e++){Ds(u,3*e,h,l),u.needsUpdate=!0;const t=u.distanceToTriangle(p,f,g);if(t<y&&(m.copy(f),_&&_.copy(g),y=t,w=e,v=o),t<r)return!0}}}})}for(let n=0,o=Oi(e);n<o;n++){Ds(p,3*n,d,c),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let e=t,i=t+s;e<i;e++){Ds(u,3*e,h,l),u.needsUpdate=!0;const t=u.distanceToTriangle(p,f,g);if(t<y&&(m.copy(f),_&&_.copy(g),y=t,w=e,v=n),t<r)return!0}}}}),ss.releasePrimitive(u),ss.releasePrimitive(p),y===1/0?null:(s.point?s.point.copy(m):s.point=m.clone(),s.distance=y,s.faceIndex=w,n&&(n.point?n.point.copy(_):n.point=_.clone(),n.point.applyMatrix4(Js),m.applyMatrix4(Js),n.distance=m.sub(n.point).length(),n.faceIndex=v),s)}function ln(t,e=null){e&&Array.isArray(e)&&(e=new Set(e));const i=t.geometry,s=i.index?i.index.array:null,n=i.attributes.position;let r,o,a,l,h=0;const c=t._roots;for(let t=0,e=c.length;t<e;t++)r=c[t],o=new Uint32Array(r),a=new Uint16Array(r),l=new Float32Array(r),d(0,h),h+=r.byteLength;function d(i,r,h=!1){const c=2*i;if(a[c+15]===Ei){const e=o[i+6];let r=1/0,h=1/0,d=1/0,u=-1/0,p=-1/0,f=-1/0;for(let i=e,o=e+a[c+14];i<o;i++){const e=3*t.resolveTriangleIndex(i);for(let t=0;t<3;t++){let i=e+t;i=s?s[i]:i;const o=n.getX(i),a=n.getY(i),l=n.getZ(i);o<r&&(r=o),o>u&&(u=o),a<h&&(h=a),a>p&&(p=a),l<d&&(d=l),l>f&&(f=l)}}return(l[i+0]!==r||l[i+1]!==h||l[i+2]!==d||l[i+3]!==u||l[i+4]!==p||l[i+5]!==f)&&(l[i+0]=r,l[i+1]=h,l[i+2]=d,l[i+3]=u,l[i+4]=p,l[i+5]=f,!0)}{const t=i+8,s=o[i+6],n=t+r,a=s+r;let c=h,u=!1,p=!1;e?c||(u=e.has(n),p=e.has(a),c=!u&&!p):(u=!0,p=!0);const f=c||p;let m=!1;(c||u)&&(m=d(t,r,c));let g=!1;f&&(g=d(s,r,c));const _=m||g;if(_)for(let e=0;e<3;e++){const n=t+e,r=s+e,o=l[n],a=l[n+3],h=l[r],c=l[r+3];l[i+e]=o<h?o:h,l[i+e+3]=a>c?a:c}return _}}}const hn=new s.Vector3;function cn(t,e,i,s,n){ds.setBuffer(t._roots[e]),dn(0,t,i,s,n),ds.clearBuffer()}function dn(t,e,i,s,n){const{float32Array:r,uint16Array:o,uint32Array:a}=ds,l=2*t;if(ns(l,o)){!function(t,e,i,s,n,r){const{geometry:o,_indirectBuffer:a}=t;for(let t=s,l=s+n;t<l;t++)Ms(o,e,i,a?a[t]:t,r)}(e,i,s,rs(t,a),os(l,o),n)}else{const o=as(t);Ns(o,r,s,hn)&&dn(o,e,i,s,n);const l=ls(t,a);Ns(l,r,s,hn)&&dn(l,e,i,s,n)}}const un=new s.Vector3,pn=["x","y","z"];function fn(t,e,i,s){ds.setBuffer(t._roots[e]);const n=mn(0,t,i,s);return ds.clearBuffer(),n}function mn(t,e,i,s){const{float32Array:n,uint16Array:r,uint32Array:o}=ds;let a=2*t;if(ns(a,r)){return function(t,e,i,s,n){const{geometry:r,_indirectBuffer:o}=t;let a=1/0,l=null;for(let t=s,h=s+n;t<h;t++){let s;s=Ms(r,e,i,o?o[t]:t),s&&s.distance<a&&(l=s,a=s.distance)}return l}(e,i,s,rs(t,o),os(a,r))}{const r=hs(t,o),a=pn[r],l=s.direction[a]>=0;let h,c;l?(h=as(t),c=ls(t,o)):(h=ls(t,o),c=as(t));const d=Ns(h,n,s,un)?mn(h,e,i,s):null;if(d){const t=d.point[a];if(l?t<=n[c+r]:t>=n[c+r+3])return d}const u=Ns(c,n,s,un)?mn(c,e,i,s):null;return d&&u?d.distance<=u.distance?d:u:d||u||null}}const gn=new s.Box3,_n=new Ji,yn=new Ji,wn=new s.Matrix4,vn=new ts,bn=new ts;function xn(t,e,i,s){ds.setBuffer(t._roots[e]);const n=Tn(0,t,i,s);return ds.clearBuffer(),n}function Tn(t,e,i,s,n=null){const{float32Array:r,uint16Array:o,uint32Array:a}=ds;let l=2*t;null===n&&(i.boundingBox||i.computeBoundingBox(),vn.set(i.boundingBox.min,i.boundingBox.max,s),n=vn);if(!ns(l,o)){const o=t+8,l=a[t+6];Di(o,r,gn);if(n.intersectsBox(gn)&&Tn(o,e,i,s,n))return!0;Di(l,r,gn);return!!(n.intersectsBox(gn)&&Tn(l,e,i,s,n))}{const n=e.geometry,h=n.index,c=n.attributes.position,d=i.index,u=i.attributes.position,p=rs(t,a),f=os(l,o);if(wn.copy(s).invert(),i.boundsTree){Di(t,r,bn),bn.matrix.copy(wn),bn.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:t=>bn.intersectsBox(t),intersectsTriangle:t=>{t.a.applyMatrix4(s),t.b.applyMatrix4(s),t.c.applyMatrix4(s),t.needsUpdate=!0;for(let i=p,s=f+p;i<s;i++)if(Ds(yn,3*e.resolveTriangleIndex(i),h,c),yn.needsUpdate=!0,t.intersectsTriangle(yn))return!0;return!1}})}for(let t=p,i=f+p;t<i;t++){const i=e.resolveTriangleIndex(t);Ds(_n,3*i,h,c),_n.a.applyMatrix4(wn),_n.b.applyMatrix4(wn),_n.c.applyMatrix4(wn),_n.needsUpdate=!0;for(let t=0,e=d.count;t<e;t+=3)if(Ds(yn,t,d,u),yn.needsUpdate=!0,_n.intersectsTriangle(yn))return!0}}}const Cn=new s.Matrix4,En=new ts,Sn=new ts,An=new s.Vector3,On=new s.Vector3,Pn=new s.Vector3,In=new s.Vector3;function Mn(t,e,i,s={},n={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),En.set(e.boundingBox.min,e.boundingBox.max,i),En.needsUpdate=!0;const a=t.geometry,l=a.attributes.position,h=a.index,c=e.attributes.position,d=e.index,u=ss.getPrimitive(),p=ss.getPrimitive();let f=An,m=On,g=null,_=null;n&&(g=Pn,_=In);let y=1/0,w=null,v=null;return Cn.copy(i).invert(),Sn.matrix.copy(Cn),t.shapecast({boundsTraverseOrder:t=>En.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o&&(e&&(Sn.min.copy(t.min),Sn.max.copy(t.max),Sn.needsUpdate=!0),!0),intersectsRange:(s,n)=>{if(e.boundsTree){const a=e.boundsTree;return a.shapecast({boundsTraverseOrder:t=>Sn.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o,intersectsRange:(e,o)=>{for(let b=e,x=e+o;b<x;b++){const e=a.resolveTriangleIndex(b);Ds(p,3*e,d,c),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let e=s,i=s+n;e<i;e++){const i=t.resolveTriangleIndex(e);Ds(u,3*i,h,l),u.needsUpdate=!0;const s=u.distanceToTriangle(p,f,g);if(s<y&&(m.copy(f),_&&_.copy(g),y=s,w=e,v=b),s<r)return!0}}}})}for(let o=0,a=Oi(e);o<a;o++){Ds(p,3*o,d,c),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let e=s,i=s+n;e<i;e++){const i=t.resolveTriangleIndex(e);Ds(u,3*i,h,l),u.needsUpdate=!0;const s=u.distanceToTriangle(p,f,g);if(s<y&&(m.copy(f),_&&_.copy(g),y=s,w=e,v=o),s<r)return!0}}}}),ss.releasePrimitive(u),ss.releasePrimitive(p),y===1/0?null:(s.point?s.point.copy(m):s.point=m.clone(),s.distance=y,s.faceIndex=w,n&&(n.point?n.point.copy(_):n.point=_.clone(),n.point.applyMatrix4(Cn),m.applyMatrix4(Cn),n.distance=m.sub(n.point).length(),n.faceIndex=v),s)}const Dn=new ds.constructor,kn=new ds.constructor,zn=new es(()=>new s.Box3),Bn=new s.Box3,Nn=new s.Box3,Un=new s.Box3,Ln=new s.Box3;let Rn=!1;function Fn(t,e,i,s,n,r=0,o=0,a=0,l=0,h=null,c=!1){let d,u;c?(d=kn,u=Dn):(d=Dn,u=kn);const p=d.float32Array,f=d.uint32Array,m=d.uint16Array,g=u.float32Array,_=u.uint32Array,y=u.uint16Array,w=2*e,v=ns(2*t,m),b=ns(w,y);let x=!1;if(b&&v)x=c?n(rs(e,_),os(2*e,y),rs(t,f),os(2*t,m),l,o+e,a,r+t):n(rs(t,f),os(2*t,m),rs(e,_),os(2*e,y),a,r+t,l,o+e);else if(b){const h=zn.getPrimitive();Di(e,g,h),h.applyMatrix4(i);const d=as(t),u=ls(t,f);Di(d,p,Bn),Di(u,p,Nn);const m=h.intersectsBox(Bn),_=h.intersectsBox(Nn);x=m&&Fn(e,d,s,i,n,o,r,l,a+1,h,!c)||_&&Fn(e,u,s,i,n,o,r,l,a+1,h,!c),zn.releasePrimitive(h)}else{const d=as(e),u=ls(e,_);Di(d,g,Un),Di(u,g,Ln);const m=h.intersectsBox(Un),y=h.intersectsBox(Ln);if(m&&y)x=Fn(t,d,i,s,n,r,o,a,l+1,h,c)||Fn(t,u,i,s,n,r,o,a,l+1,h,c);else if(m)if(v)x=Fn(t,d,i,s,n,r,o,a,l+1,h,c);else{const e=zn.getPrimitive();e.copy(Un).applyMatrix4(i);const h=as(t),u=ls(t,f);Di(h,p,Bn),Di(u,p,Nn);const m=e.intersectsBox(Bn),g=e.intersectsBox(Nn);x=m&&Fn(d,h,s,i,n,o,r,l,a+1,e,!c)||g&&Fn(d,u,s,i,n,o,r,l,a+1,e,!c),zn.releasePrimitive(e)}else if(y)if(v)x=Fn(t,u,i,s,n,r,o,a,l+1,h,c);else{const e=zn.getPrimitive();e.copy(Ln).applyMatrix4(i);const h=as(t),d=ls(t,f);Di(h,p,Bn),Di(d,p,Nn);const m=e.intersectsBox(Bn),g=e.intersectsBox(Nn);x=m&&Fn(u,h,s,i,n,o,r,l,a+1,e,!c)||g&&Fn(u,d,s,i,n,o,r,l,a+1,e,!c),zn.releasePrimitive(e)}}return x}const Vn=new ts,jn=new s.Box3;class Hn{static serialize(t,e={}){e={cloneBuffers:!0,...e};const i=t.geometry,s=t._roots,n=t._indirectBuffer,r=i.getIndex();let o;return o=e.cloneBuffers?{roots:s.map(t=>t.slice()),index:r.array.slice(),indirectBuffer:n?n.slice():null}:{roots:s,index:r.array,indirectBuffer:n},o}static deserialize(t,e,i={}){i={setIndex:!0,indirect:Boolean(t.indirectBuffer),...i};const{index:n,roots:r,indirectBuffer:o}=t,a=new Hn(e,{...i,[Ai]:!0});if(a._roots=r,a._indirectBuffer=o||null,i.setIndex){const i=e.getIndex();if(null===i){const i=new s.BufferAttribute(t.index,1,!1);e.setIndex(i)}else i.array!==n&&(i.array.set(n),i.needsUpdate=!0)}return a}get indirect(){return!!this._indirectBuffer}constructor(t,e={}){if(!t.isBufferGeometry)throw new Error("MeshBVH: Only BufferGeometries are supported.");if(t.index&&t.index.isInterleavedBufferAttribute)throw new Error("MeshBVH: InterleavedBufferAttribute is not supported for the index attribute.");if((e=Object.assign({strategy:0,maxDepth:40,maxLeafTris:10,verbose:!0,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,[Ai]:!1},e)).useSharedArrayBuffer&&"undefined"==typeof SharedArrayBuffer)throw new Error("MeshBVH: SharedArrayBuffer is not available.");this.geometry=t,this._roots=null,this._indirectBuffer=null,e[Ai]||(Yi(this,e),!t.boundingBox&&e.setBoundingBox&&(t.boundingBox=this.getBoundingBox(new s.Box3)));const{_indirectBuffer:i}=this;this.resolveTriangleIndex=e.indirect?t=>i[t]:t=>t}refit(t=null){return(this.indirect?ln:zs)(this,t)}traverse(t,e=0){const i=this._roots[e],s=new Uint32Array(i),n=new Uint16Array(i);!function e(r,o=0){const a=2*r,l=n[a+15]===Ei;if(l){const e=s[r+6],h=n[a+14];t(o,l,new Float32Array(i,4*r,6),e,h)}else{const n=r+8,a=s[r+6],h=s[r+7];t(o,l,new Float32Array(i,4*r,6),h)||(e(n,o+1),e(a,o+1))}}(0)}raycast(t,e=s.FrontSide){const i=this._roots,n=this.geometry,r=[],o=e.isMaterial,a=Array.isArray(e),l=n.groups,h=o?e.side:e,c=this.indirect?cn:Rs;for(let s=0,n=i.length;s<n;s++){const i=a?e[l[s].materialIndex].side:h,n=r.length;if(c(this,s,i,t,r),a){const t=l[s].materialIndex;for(let e=n,i=r.length;e<i;e++)r[e].face.materialIndex=t}}return r}raycastFirst(t,e=s.FrontSide){const i=this._roots,n=this.geometry,r=e.isMaterial,o=Array.isArray(e);let a=null;const l=n.groups,h=r?e.side:e,c=this.indirect?fn:Hs;for(let s=0,n=i.length;s<n;s++){const i=c(this,s,o?e[l[s].materialIndex].side:h,t);null!=i&&(null==a||i.distance<a.distance)&&(a=i,o&&(i.face.materialIndex=l[s].materialIndex))}return a}intersectsGeometry(t,e){let i=!1;const s=this._roots,n=this.indirect?xn:Qs;for(let r=0,o=s.length;r<o&&(i=n(this,r,t,e),!i);r++);return i}shapecast(t){const e=ss.getPrimitive(),i=this.indirect?Us:ks;let{boundsTraverseOrder:s,intersectsBounds:n,intersectsRange:r,intersectsTriangle:o}=t;if(r&&o){const t=r;r=(s,n,r,a,l)=>!!t(s,n,r,a,l)||i(s,n,this,o,r,a,e)}else r||(r=o?(t,s,n,r)=>i(t,s,this,o,n,r,e):(t,e,i)=>i);let a=!1,l=0;const h=this._roots;for(let t=0,e=h.length;t<e;t++){const e=h[t];if(a=gs(this,t,n,r,s,l),a)break;l+=e.byteLength}return ss.releasePrimitive(e),a}bvhcast(t,e,i){let{intersectsRanges:n,intersectsTriangles:r}=i;const o=ss.getPrimitive(),a=this.geometry.index,l=this.geometry.attributes.position,h=this.indirect?t=>{const e=this.resolveTriangleIndex(t);Ds(o,3*e,a,l)}:t=>{Ds(o,3*t,a,l)},c=ss.getPrimitive(),d=t.geometry.index,u=t.geometry.attributes.position,p=t.indirect?e=>{const i=t.resolveTriangleIndex(e);Ds(c,3*i,d,u)}:t=>{Ds(c,3*t,d,u)};if(r){const t=(t,i,s,n,a,l,d,u)=>{for(let f=s,m=s+n;f<m;f++){p(f),c.a.applyMatrix4(e),c.b.applyMatrix4(e),c.c.applyMatrix4(e),c.needsUpdate=!0;for(let e=t,s=t+i;e<s;e++)if(h(e),o.needsUpdate=!0,r(o,c,e,f,a,l,d,u))return!0}return!1};if(n){const e=n;n=function(i,s,n,r,o,a,l,h){return!!e(i,s,n,r,o,a,l,h)||t(i,s,n,r,o,a,l,h)}}else n=t}return function(t,e,i,n){if(Rn)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Rn=!0;const r=t._roots,o=e._roots;let a,l=0,h=0;const c=(new s.Matrix4).copy(i).invert();for(let t=0,e=r.length;t<e;t++){Dn.setBuffer(r[t]),h=0;const e=zn.getPrimitive();Di(cs(0),Dn.float32Array,e),e.applyMatrix4(c);for(let s=0,r=o.length;s<r&&(kn.setBuffer(o[t]),a=Fn(0,0,i,c,n,l,h,0,0,e),kn.clearBuffer(),h+=o[s].length,!a);s++);if(zn.releasePrimitive(e),Dn.clearBuffer(),l+=r[t].length,a)break}return Rn=!1,a}(this,t,e,n)}intersectsBox(t,e){return Vn.set(t.min,t.max,e),Vn.needsUpdate=!0,this.shapecast({intersectsBounds:t=>Vn.intersectsBox(t),intersectsTriangle:t=>Vn.intersectsTriangle(t)})}intersectsSphere(t){return this.shapecast({intersectsBounds:e=>t.intersectsBox(e),intersectsTriangle:e=>e.intersectsSphere(t)})}closestPointToGeometry(t,e,i={},s={},n=0,r=1/0){return(this.indirect?Mn:an)(this,t,e,i,s,n,r)}closestPointToPoint(t,e={},i=0,s=1/0){return function(t,e,i={},s=0,n=1/0){const r=s*s,o=n*n;let a=1/0,l=null;if(t.shapecast({boundsTraverseOrder:t=>(ys.copy(e).clamp(t.min,t.max),ys.distanceToSquared(e)),intersectsBounds:(t,e,i)=>i<a&&i<o,intersectsTriangle:(t,i)=>{t.closestPointToPoint(e,ys);const s=e.distanceToSquared(ys);return s<a&&(ws.copy(ys),a=s,l=i),s<r}}),a===1/0)return null;const h=Math.sqrt(a);return i.point?i.point.copy(ws):i.point=ws.clone(),i.distance=h,i.faceIndex=l,i}(this,t,e,i,s)}getBoundingBox(t){t.makeEmpty();return this._roots.forEach(e=>{Di(0,new Float32Array(e),jn),t.union(jn)}),t}}function Zn(t,e,i){return null===t?null:(t.point.applyMatrix4(e.matrixWorld),t.distance=t.point.distanceTo(i.ray.origin),t.object=e,t.distance<i.near||t.distance>i.far?null:t)}const $n=new s.Ray,Wn=new s.Matrix4,Yn=s.Mesh.prototype.raycast;function Gn(t,e){if(this.geometry.boundsTree){if(void 0===this.material)return;Wn.copy(this.matrixWorld).invert(),$n.copy(t.ray).applyMatrix4(Wn);const i=this.geometry.boundsTree;if(!0===t.firstHitOnly){const s=Zn(i.raycastFirst($n,this.material),this,t);s&&e.push(s)}else{const s=i.raycast($n,this.material);for(let i=0,n=s.length;i<n;i++){const n=Zn(s[i],this,t);n&&e.push(n)}}}else Yn.call(this,t,e)}function Xn(t){return this.boundsTree=new Hn(this,t),this.boundsTree}function qn(){this.boundsTree=null}const Qn=class t{constructor(){e(this,"onDisposed",new h),e(this,"list",new i.DataMap),e(this,"enabled",!1),e(this,"_clock"),e(this,"onInit",new h),e(this,"update",()=>{if(!this.enabled)return;const t=this._clock.getDelta();for(const[e,i]of this.list)i.enabled&&i.isUpdateable()&&i.update(t);requestAnimationFrame(this.update)}),this._clock=new a.Clock,t.setupBVH()}add(t,e){if(this.list.has(t))throw new Error("You're trying to add a component that already exists in the components instance. Use Components.get() instead.");v.validate(t),this.list.set(t,e)}get(t){var e;const i=t.uuid;if(!this.list.has(i)){const s=new t(this);return(null==(e=s.isDisposeable)?void 0:e.call(s))&&s.onDisposed.add(()=>this.list.delete(i)),this.list.has(i)||this.add(i,s),s}return this.list.get(i)}init(){this.enabled=!0;for(const[t,e]of this.list.entries())e.enabled=!0;this._clock.start(),this.update(),this.onInit.trigger()}dispose(){let t;this.enabled=!1;for(const[e,i]of this.list)i.enabled=!1,e!==qt.uuid?i.isDisposeable()&&i.dispose():t=i;null==t||t.dispose(),this._clock.stop(),this.onDisposed.trigger()}static setupBVH(){a.BufferGeometry.prototype.computeBoundsTree=Xn,a.BufferGeometry.prototype.disposeBoundsTree=qn,a.Mesh.prototype.raycast=Gn}};e(Qn,"release","2.4.3");let Kn=Qn;class Jn{constructor(t){e(this,"enabled",!1),e(this,"id","FirstPerson"),this.camera=t}set(t){if(this.enabled=t,t){if("Perspective"!==this.camera.projection.current)return void this.camera.set("Orbit");this.setupFirstPersonCamera()}}setupFirstPersonCamera(){const t=this.camera.controls,e=new a.Vector3;t.distance--,t.getPosition(e),t.minDistance=1,t.maxDistance=1,t.distance=1,t.moveTo(e.x,e.y,e.z),t.truckSpeed=50,t.mouseButtons.wheel=gi.ACTION.DOLLY,t.touches.two=gi.ACTION.TOUCH_ZOOM_TRUCK}}class tr{constructor(t){e(this,"enabled",!0),e(this,"id","Orbit"),this.camera=t,this.activateOrbitControls()}set(t){this.enabled=t,t&&this.activateOrbitControls()}activateOrbitControls(){const t=this.camera.controls;t.minDistance=1,t.maxDistance=300;const e=new a.Vector3;t.getPosition(e);const i=e.length();t.distance=i,t.truckSpeed=2;const{rotation:s}=this.camera.three,n=new a.Vector3(0,0,-1).applyEuler(s),r=e.addScaledVector(n,i);t.moveTo(r.x,r.y,r.z)}}class er{constructor(t){e(this,"enabled",!1),e(this,"id","Plan"),e(this,"mouseAction1"),e(this,"mouseAction2"),e(this,"mouseInitialized",!1),e(this,"defaultAzimuthSpeed"),e(this,"defaultPolarSpeed"),this.camera=t,this.defaultAzimuthSpeed=t.controls.azimuthRotateSpeed,this.defaultPolarSpeed=t.controls.polarRotateSpeed}set(t){this.enabled=t;const e=this.camera.controls;e.azimuthRotateSpeed=t?0:this.defaultAzimuthSpeed,e.polarRotateSpeed=t?0:this.defaultPolarSpeed,this.mouseInitialized||(this.mouseAction1=e.touches.one,this.mouseAction2=e.touches.two,this.mouseInitialized=!0),t?(e.mouseButtons.left=gi.ACTION.TRUCK,e.touches.one=gi.ACTION.TOUCH_TRUCK,e.touches.two=gi.ACTION.TOUCH_ZOOM):(e.mouseButtons.left=gi.ACTION.ROTATE,e.touches.one=this.mouseAction1,e.touches.two=this.mouseAction2)}}class ir{constructor(t){e(this,"onChanged",new h),e(this,"current","Perspective"),e(this,"camera"),e(this,"matchOrthoDistanceEnabled",!1),e(this,"_component"),e(this,"_previousDistance",-1),this._component=t,this.camera=t.three}async set(t){this.current!==t&&("Orthographic"===t?this.setOrthoCamera():await this.setPerspectiveCamera(),this.onChanged.trigger(this.camera))}async toggle(){const t="Perspective"===this.current?"Orthographic":"Perspective";await this.set(t)}setOrthoCamera(){if(null===this._component.mode)return;if("FirstPerson"===this._component.mode.id)return;this._previousDistance=this._component.controls.distance,this._component.controls.distance=200;const t=this.getPerspectiveDims();if(!t)return;const{width:e,height:i}=t;this.setupOrthoCamera(i,e),this.camera=this._component.threeOrtho,this.current="Orthographic"}getPerspectiveDims(){const t=this._component.currentWorld;if(!t||!t.renderer)return null;const e=new a.Vector3;this._component.threePersp.getWorldDirection(e);const i=new a.Vector3;this._component.controls.getTarget(i);const s=i.clone().sub(this._component.threePersp.position).dot(e),n=t.renderer.getSize(),r=n.x/n.y,o=this._component.threePersp,l=2*s*Math.atan(o.fov*(Math.PI/180)/2);return{width:l*r,height:l}}setupOrthoCamera(t,e){this._component.controls.mouseButtons.wheel=gi.ACTION.ZOOM,this._component.controls.mouseButtons.middle=gi.ACTION.ZOOM;const i=this._component.threePersp,s=this._component.threeOrtho;s.zoom=1,s.left=e/-2,s.right=e/2,s.top=t/2,s.bottom=t/-2,s.updateProjectionMatrix(),s.position.copy(i.position),s.quaternion.copy(i.quaternion),this._component.controls.camera=s}getDistance(){const t=this._component.threePersp,e=this._component.threeOrtho;return(e.top-e.bottom)/e.zoom/(2*Math.atan(t.fov*(Math.PI/180)/2))}async setPerspectiveCamera(){this._component.controls.mouseButtons.wheel=gi.ACTION.DOLLY,this._component.controls.mouseButtons.middle=gi.ACTION.DOLLY;const t=this._component.threePersp,e=this._component.threeOrtho;t.position.copy(e.position),t.quaternion.copy(e.quaternion),this._component.controls.mouseButtons.wheel=gi.ACTION.DOLLY,this.matchOrthoDistanceEnabled?this._component.controls.distance=this.getDistance():this._component.controls.distance=this._previousDistance,await this._component.controls.zoomTo(1),t.updateProjectionMatrix(),this._component.controls.camera=t,this.camera=t,this.current="Perspective"}}class sr extends _i{constructor(t){super(t),e(this,"projection"),e(this,"threeOrtho"),e(this,"threePersp"),e(this,"_userInputButtons",{}),e(this,"_frustumSize",50),e(this,"_navigationModes",new Map),e(this,"_mode",null),e(this,"previousSize",null),this.threePersp=this.three,this.threeOrtho=this.newOrthoCamera(),this.projection=new ir(this),this.onAspectUpdated.add(()=>{this.setOrthoPerspCameraAspect()}),this.projection.onChanged.add(t=>{this.three=t,this.updateAspect()}),this.worlds.onItemSet.add(()=>{this._navigationModes.clear(),this._navigationModes.set("Orbit",new tr(this)),this._navigationModes.set("FirstPerson",new Jn(this)),this._navigationModes.set("Plan",new er(this)),this._mode=this._navigationModes.get("Orbit"),this.mode.set(!0,{preventTargetAdjustment:!0}),this.currentWorld&&this.currentWorld.renderer&&(this.previousSize=this.currentWorld.renderer.getSize().clone())}),this.worlds.onItemDeleted.add(()=>{this._navigationModes.clear()})}get mode(){if(!this._mode)throw new Error("Mode not found, camera not initialized");return this._mode}dispose(){super.dispose(),this.threeOrtho.removeFromParent()}set(t){if(null!==this.mode&&this.mode.id!==t){if(this.mode.set(!1),!this._navigationModes.has(t))throw new Error("The specified mode does not exist!");this._mode=this._navigationModes.get(t),this.mode.set(!0)}}async fit(t,e=1.5){if(!this.enabled)return;const i=Number.MAX_VALUE,s=Number.MIN_VALUE,n=new a.Vector3(i,i,i),r=new a.Vector3(s,s,s);for(const e of t){const t=(new a.Box3).setFromObject(e);t.min.x<n.x&&(n.x=t.min.x),t.min.y<n.y&&(n.y=t.min.y),t.min.z<n.z&&(n.z=t.min.z),t.max.x>r.x&&(r.x=t.max.x),t.max.y>r.y&&(r.y=t.max.y),t.max.z>r.z&&(r.z=t.max.z)}const o=new a.Box3(n,r),l=this.components.get(qt);if(l.initialized)for(const[,t]of l.list){const e=t.box;e.min.x<n.x&&(n.x=e.min.x),e.min.y<n.y&&(n.y=e.min.y),e.min.z<n.z&&(n.z=e.min.z),e.max.x>r.x&&(r.x=e.max.x),e.max.y>r.y&&(r.y=e.max.y),e.max.z>r.z&&(r.z=e.max.z)}const h=new a.Vector3;o.getSize(h);const c=new a.Vector3;o.getCenter(c);const d=Math.max(h.x,h.y,h.z)*e,u=new a.Sphere(c,d);await this.controls.fitToSphere(u,!0)}setUserInput(t){t?this.enableUserInput():this.disableUserInput()}addCustomNavigationMode(t){this._navigationModes.set(t.id,t)}disableUserInput(){this._userInputButtons.left=this.controls.mouseButtons.left,this._userInputButtons.right=this.controls.mouseButtons.right,this._userInputButtons.middle=this.controls.mouseButtons.middle,this._userInputButtons.wheel=this.controls.mouseButtons.wheel,this.controls.mouseButtons.left=0,this.controls.mouseButtons.right=0,this.controls.mouseButtons.middle=0,this.controls.mouseButtons.wheel=0}enableUserInput(){0!==Object.keys(this._userInputButtons).length&&(this.controls.mouseButtons.left=this._userInputButtons.left,this.controls.mouseButtons.right=this._userInputButtons.right,this.controls.mouseButtons.middle=this._userInputButtons.middle,this.controls.mouseButtons.wheel=this._userInputButtons.wheel)}newOrthoCamera(){const t=window.innerWidth/window.innerHeight;return new a.OrthographicCamera(this._frustumSize*t/-2,this._frustumSize*t/2,this._frustumSize/2,this._frustumSize/-2,.1,1e3)}setOrthoPerspCameraAspect(){if(!this.currentWorld||!this.currentWorld.renderer)return;if(!this.previousSize)return;const t=this.currentWorld.renderer.getSize(),e=this.threeOrtho.top,i=this.threeOrtho.right,s=e*(t.y/this.previousSize.y),n=i*(t.x/this.previousSize.x);this.threeOrtho.left=-n,this.threeOrtho.right=n,this.threeOrtho.top=s,this.threeOrtho.bottom=-s,this.threeOrtho.updateProjectionMatrix(),this.previousSize.copy(t)}}function nr(t){throw new Error('Could not dynamically require "'+t+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var rr={exports:{}};
1
+ "use strict";var e=Object.defineProperty,t=(t,s,i)=>(((t,s,i)=>{s in t?e(t,s,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[s]=i})(t,"symbol"!=typeof s?s+"":s,i),i);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("@thatopen/fragments"),i=require("three"),r=require("web-ifc"),n=require("camera-controls");function o(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const s in e)if("default"!==s){const i=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,i.get?i:{enumerable:!0,get:()=>e[s]})}return t.default=e,Object.freeze(t)}const a=o(s),l=o(i),h=o(r);class u{constructor(){t(this,"enabled",!0),t(this,"trigger",e=>{if(!this.enabled)return;const t=this.handlers.slice(0);for(const s of t)s(e)}),t(this,"handlers",[])}add(e){this.handlers.push(e)}remove(e){this.handlers=this.handlers.filter(t=>t!==e)}reset(){this.handlers.length=0}}class c{constructor(e){t(this,"isDisposeable",()=>"dispose"in this&&"onDisposed"in this),t(this,"isResizeable",()=>"resize"in this&&"getSize"in this),t(this,"isUpdateable",()=>"onAfterUpdate"in this&&"onBeforeUpdate"in this&&"update"in this),t(this,"isHideable",()=>"visible"in this),t(this,"isConfigurable",()=>"setup"in this&&"config"in this&&"onSetup"in this),t(this,"isSerializable",()=>"import"in this&&"export"in this),this.components=e}}class d extends c{}class p extends c{constructor(e){super(e),t(this,"worlds",new s.DataMap),t(this,"onWorldChanged",new u),t(this,"_currentWorld",null),this.onWorldChanged.add(({world:e,action:t})=>{"removed"===t&&this.worlds.delete(e.uuid)})}set currentWorld(e){this._currentWorld=e}get currentWorld(){return this._currentWorld}}class m extends p{constructor(){super(...arguments),t(this,"hasCameraControls",()=>"controls"in this)}}class f extends p{constructor(){super(...arguments),t(this,"onAfterUpdate",new u),t(this,"onBeforeUpdate",new u),t(this,"onDisposed",new u),t(this,"onResize",new u),t(this,"onClippingPlanesUpdated",new u),t(this,"clippingPlanes",[])}updateClippingPlanes(){this.onClippingPlanesUpdated.trigger()}setPlane(e,t,s){t.isLocal=s;const i=this.clippingPlanes.indexOf(t);e&&-1===i?this.clippingPlanes.push(t):!e&&i>-1&&this.clippingPlanes.splice(i,1),this.three.clippingPlanes=this.clippingPlanes.filter(e=>!e.isLocal)}}const g=class e extends d{constructor(s){super(s),t(this,"_disposedComponents",new Set),t(this,"enabled",!0),s.add(e.uuid,this)}get(){return this._disposedComponents}destroy(e,t=!0,s=!0){e.removeFromParent();const i=e;i.dispose&&i.dispose(),this.disposeGeometryAndMaterials(e,t),s&&i.children&&i.children.length&&this.disposeChildren(i),e.children.length=0}disposeGeometry(e){e.boundsTree&&e.disposeBoundsTree&&e.disposeBoundsTree(),e.dispose()}disposeGeometryAndMaterials(t,s){const i=t;i.geometry&&this.disposeGeometry(i.geometry),s&&i.material&&e.disposeMaterial(i),i.material=[],i.geometry=null}disposeChildren(e){for(const t of e.children)this.destroy(t)}static disposeMaterial(e){if(e.material)if(Array.isArray(e.material))for(const t of e.material)t.dispose();else e.material.dispose()}};t(g,"uuid","76e9cd8e-ad8f-4753-9ef6-cbc60f7247fe");let y=g;class x extends p{constructor(e){super(e),t(this,"onDisposed",new u),t(this,"directionalLights",new Map),t(this,"ambientLights",new Map)}dispose(){const e=this.components.get(y);for(const t of this.three.children){const s=t;s.geometry&&e.destroy(s)}this.deleteAllLights(),this.three.children=[],this.onDisposed.trigger(),this.onDisposed.reset()}deleteAllLights(){for(const[,e]of this.directionalLights)e.removeFromParent(),e.target.removeFromParent(),e.dispose();this.directionalLights.clear();for(const[,e]of this.ambientLights)e.removeFromParent(),e.dispose();this.ambientLights.clear()}}class b extends Set{constructor(e){super(e),t(this,"onItemAdded",new u),t(this,"onItemDeleted",new u),t(this,"onCleared",new u),t(this,"guard",()=>!0)}clear(){super.clear(),this.onCleared.trigger()}add(...e){for(const t of e){if(this.has(t))continue;this.guard(t)&&(super.add(t),this.onItemAdded||(this.onItemAdded=new u),this.onItemAdded.trigger(t))}return this}delete(e){const t=super.delete(e);return t&&this.onItemDeleted.trigger(),t}dispose(){this.clear(),this.onItemAdded.reset(),this.onItemDeleted.reset(),this.onCleared.reset()}}const _=class e{static create(){const t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=4294967295*Math.random()|0,r=4294967295*Math.random()|0;return`${e._lut[255&t]+e._lut[t>>8&255]+e._lut[t>>16&255]+e._lut[t>>24&255]}-${e._lut[255&s]}${e._lut[s>>8&255]}-${e._lut[s>>16&15|64]}${e._lut[s>>24&255]}-${e._lut[63&i|128]}${e._lut[i>>8&255]}-${e._lut[i>>16&255]}${e._lut[i>>24&255]}${e._lut[255&r]}${e._lut[r>>8&255]}${e._lut[r>>16&255]}${e._lut[r>>24&255]}`.toLowerCase()}static validate(t){if(!e._pattern.test(t))throw new Error(`${t} is not a valid UUID v4.\n\n- If you're the tool creator, you can take one from https://www.uuidgenerator.net/.\n\n- If you're using a platform tool, verify the uuid isn't misspelled or contact the tool creator.`)}};t(_,"_pattern",/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/),t(_,"_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"]);let w=_;const v=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",T=new RegExp("^"+("["+v+"]["+(v+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040")+"]*")+"$");function S(e,t){const s=[];let i=t.exec(e);for(;i;){const r=[];r.startIndex=t.lastIndex-i[0].length;const n=i.length;for(let e=0;e<n;e++)r.push(i[e]);s.push(r),i=t.exec(e)}return s}const M=function(e){const t=T.exec(e);return!(null==t)};const A={allowBooleanAttributes:!1,unpairedTags:[]};function N(e){return" "===e||"\t"===e||"\n"===e||"\r"===e}function E(e,t){const s=t;for(;t<e.length;t++)if("?"==e[t]||" "==e[t]){const i=e.substr(s,t-s);if(t>5&&"xml"===i)return F("InvalidXml","XML declaration allowed only at the start of the document.",z(e,t));if("?"==e[t]&&">"==e[t+1]){t++;break}continue}return t}function C(e,t){if(e.length>t+5&&"-"===e[t+1]&&"-"===e[t+2]){for(t+=3;t<e.length;t++)if("-"===e[t]&&"-"===e[t+1]&&">"===e[t+2]){t+=2;break}}else if(e.length>t+8&&"D"===e[t+1]&&"O"===e[t+2]&&"C"===e[t+3]&&"T"===e[t+4]&&"Y"===e[t+5]&&"P"===e[t+6]&&"E"===e[t+7]){let s=1;for(t+=8;t<e.length;t++)if("<"===e[t])s++;else if(">"===e[t]&&(s--,0===s))break}else if(e.length>t+9&&"["===e[t+1]&&"C"===e[t+2]&&"D"===e[t+3]&&"A"===e[t+4]&&"T"===e[t+5]&&"A"===e[t+6]&&"["===e[t+7])for(t+=8;t<e.length;t++)if("]"===e[t]&&"]"===e[t+1]&&">"===e[t+2]){t+=2;break}return t}const R='"',P="'";function B(e,t){let s="",i="",r=!1;for(;t<e.length;t++){if(e[t]===R||e[t]===P)""===i?i=e[t]:i!==e[t]||(i="");else if(">"===e[t]&&""===i){r=!0;break}s+=e[t]}return""===i&&{value:s,index:t,tagClosed:r}}const I=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function D(e,t){const s=S(e,I),i={};for(let e=0;e<s.length;e++){if(0===s[e][1].length)return F("InvalidAttr","Attribute '"+s[e][2]+"' has no space in starting.",k(s[e]));if(void 0!==s[e][3]&&void 0===s[e][4])return F("InvalidAttr","Attribute '"+s[e][2]+"' is without value.",k(s[e]));if(void 0===s[e][3]&&!t.allowBooleanAttributes)return F("InvalidAttr","boolean attribute '"+s[e][2]+"' is not allowed.",k(s[e]));const r=s[e][2];if(!O(r))return F("InvalidAttr","Attribute '"+r+"' is an invalid name.",k(s[e]));if(i.hasOwnProperty(r))return F("InvalidAttr","Attribute '"+r+"' is repeated.",k(s[e]));i[r]=1}return!0}function L(e,t){if(";"===e[++t])return-1;if("#"===e[t])return function(e,t){let s=/\d/;for("x"===e[t]&&(t++,s=/[\da-fA-F]/);t<e.length;t++){if(";"===e[t])return t;if(!e[t].match(s))break}return-1}(e,++t);let s=0;for(;t<e.length;t++,s++)if(!(e[t].match(/\w/)&&s<20)){if(";"===e[t])break;return-1}return t}function F(e,t,s){return{err:{code:e,msg:t,line:s.line||s,col:s.col}}}function O(e){return M(e)}function V(e){return M(e)}function z(e,t){const s=e.substring(0,t).split(/\r?\n/);return{line:s.length,col:s[s.length-1].length+1}}function k(e){return e.startIndex+e[1].length}const U={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,t,s){return e},captureMetaData:!1};function G(e){return"boolean"==typeof e?{enabled:e,maxEntitySize:1e4,maxExpansionDepth:10,maxTotalExpansions:1e3,maxExpandedLength:1e5,allowedTags:null,tagFilter:null}:"object"==typeof e&&null!==e?{enabled:!1!==e.enabled,maxEntitySize:e.maxEntitySize??1e4,maxExpansionDepth:e.maxExpansionDepth??10,maxTotalExpansions:e.maxTotalExpansions??1e3,maxExpandedLength:e.maxExpandedLength??1e5,allowedTags:e.allowedTags??null,tagFilter:e.tagFilter??null}:G(!0)}const j=function(e){const t=Object.assign({},U,e);return t.processEntities=G(t.processEntities),t};let $;$="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class W{constructor(e){this.tagname=e,this.child=[],this[":@"]={}}add(e,t){"__proto__"===e&&(e="#__proto__"),this.child.push({[e]:t})}addChild(e,t){"__proto__"===e.tagname&&(e.tagname="#__proto__"),e[":@"]&&Object.keys(e[":@"]).length>0?this.child.push({[e.tagname]:e.child,":@":e[":@"]}):this.child.push({[e.tagname]:e.child}),void 0!==t&&(this.child[this.child.length-1][$]={startIndex:t})}static getMetaDataSymbol(){return $}}class H{constructor(e){this.suppressValidationErr=!e,this.options=e}readDocType(e,t){const s={};if("O"!==e[t+3]||"C"!==e[t+4]||"T"!==e[t+5]||"Y"!==e[t+6]||"P"!==e[t+7]||"E"!==e[t+8])throw new Error("Invalid Tag instead of DOCTYPE");{t+=9;let i=1,r=!1,n=!1,o="";for(;t<e.length;t++)if("<"!==e[t]||n)if(">"===e[t]){if(n?"-"===e[t-1]&&"-"===e[t-2]&&(n=!1,i--):i--,0===i)break}else"["===e[t]?r=!0:o+=e[t];else{if(r&&X(e,"!ENTITY",t)){let i,r;if(t+=7,[i,r,t]=this.readEntityExp(e,t+1,this.suppressValidationErr),-1===r.indexOf("&")){const e=i.replace(/[.\-+*:]/g,"\\.");s[i]={regx:RegExp(`&${e};`,"g"),val:r}}}else if(r&&X(e,"!ELEMENT",t)){t+=8;const{index:s}=this.readElementExp(e,t+1);t=s}else if(r&&X(e,"!ATTLIST",t))t+=8;else if(r&&X(e,"!NOTATION",t)){t+=9;const{index:s}=this.readNotationExp(e,t+1,this.suppressValidationErr);t=s}else{if(!X(e,"!--",t))throw new Error("Invalid DOCTYPE");n=!0}i++,o=""}if(0!==i)throw new Error("Unclosed DOCTYPE")}return{entities:s,i:t}}readEntityExp(e,t){t=q(e,t);let s="";for(;t<e.length&&!/\s/.test(e[t])&&'"'!==e[t]&&"'"!==e[t];)s+=e[t],t++;if(Y(s),t=q(e,t),!this.suppressValidationErr){if("SYSTEM"===e.substring(t,t+6).toUpperCase())throw new Error("External entities are not supported");if("%"===e[t])throw new Error("Parameter entities are not supported")}let i="";if([t,i]=this.readIdentifierVal(e,t,"entity"),!1!==this.options.enabled&&this.options.maxEntitySize&&i.length>this.options.maxEntitySize)throw new Error(`Entity "${s}" size (${i.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return[s,i,--t]}readNotationExp(e,t){t=q(e,t);let s="";for(;t<e.length&&!/\s/.test(e[t]);)s+=e[t],t++;!this.suppressValidationErr&&Y(s),t=q(e,t);const i=e.substring(t,t+6).toUpperCase();if(!this.suppressValidationErr&&"SYSTEM"!==i&&"PUBLIC"!==i)throw new Error(`Expected SYSTEM or PUBLIC, found "${i}"`);t+=i.length,t=q(e,t);let r=null,n=null;if("PUBLIC"===i)[t,r]=this.readIdentifierVal(e,t,"publicIdentifier"),'"'!==e[t=q(e,t)]&&"'"!==e[t]||([t,n]=this.readIdentifierVal(e,t,"systemIdentifier"));else if("SYSTEM"===i&&([t,n]=this.readIdentifierVal(e,t,"systemIdentifier"),!this.suppressValidationErr&&!n))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:s,publicIdentifier:r,systemIdentifier:n,index:--t}}readIdentifierVal(e,t,s){let i="";const r=e[t];if('"'!==r&&"'"!==r)throw new Error(`Expected quoted string, found "${r}"`);for(t++;t<e.length&&e[t]!==r;)i+=e[t],t++;if(e[t]!==r)throw new Error(`Unterminated ${s} value`);return[++t,i]}readElementExp(e,t){t=q(e,t);let s="";for(;t<e.length&&!/\s/.test(e[t]);)s+=e[t],t++;if(!this.suppressValidationErr&&!M(s))throw new Error(`Invalid element name: "${s}"`);let i="";if("E"===e[t=q(e,t)]&&X(e,"MPTY",t))t+=4;else if("A"===e[t]&&X(e,"NY",t))t+=2;else if("("===e[t]){for(t++;t<e.length&&")"!==e[t];)i+=e[t],t++;if(")"!==e[t])throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error(`Invalid Element Expression, found "${e[t]}"`);return{elementName:s,contentModel:i.trim(),index:t}}readAttlistExp(e,t){t=q(e,t);let s="";for(;t<e.length&&!/\s/.test(e[t]);)s+=e[t],t++;Y(s),t=q(e,t);let i="";for(;t<e.length&&!/\s/.test(e[t]);)i+=e[t],t++;if(!Y(i))throw new Error(`Invalid attribute name: "${i}"`);t=q(e,t);let r="";if("NOTATION"===e.substring(t,t+8).toUpperCase()){if(r="NOTATION","("!==e[t=q(e,t+=8)])throw new Error(`Expected '(', found "${e[t]}"`);t++;let s=[];for(;t<e.length&&")"!==e[t];){let i="";for(;t<e.length&&"|"!==e[t]&&")"!==e[t];)i+=e[t],t++;if(i=i.trim(),!Y(i))throw new Error(`Invalid notation name: "${i}"`);s.push(i),"|"===e[t]&&(t++,t=q(e,t))}if(")"!==e[t])throw new Error("Unterminated list of notations");t++,r+=" ("+s.join("|")+")"}else{for(;t<e.length&&!/\s/.test(e[t]);)r+=e[t],t++;const s=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!s.includes(r.toUpperCase()))throw new Error(`Invalid attribute type: "${r}"`)}t=q(e,t);let n="";return"#REQUIRED"===e.substring(t,t+8).toUpperCase()?(n="#REQUIRED",t+=8):"#IMPLIED"===e.substring(t,t+7).toUpperCase()?(n="#IMPLIED",t+=7):[t,n]=this.readIdentifierVal(e,t,"ATTLIST"),{elementName:s,attributeName:i,attributeType:r,defaultValue:n,index:t}}}const q=(e,t)=>{for(;t<e.length&&/\s/.test(e[t]);)t++;return t};function X(e,t,s){for(let i=0;i<t.length;i++)if(t[i]!==e[s+i+1])return!1;return!0}function Y(e){if(M(e))return e;throw new Error(`Invalid entity name ${e}`)}const Z=/^[-+]?0x[a-fA-F0-9]+$/,Q=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,K={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function J(e,t={}){if(t=Object.assign({},K,t),!e||"string"!=typeof e)return e;let s=e.trim();if(void 0!==t.skipLike&&t.skipLike.test(s))return e;if("0"===e)return 0;if(t.hex&&Z.test(s))return function(e,t){if(parseInt)return parseInt(e,t);if(Number.parseInt)return Number.parseInt(e,t);if(window&&window.parseInt)return window.parseInt(e,t);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(s,16);if(s.includes("e")||s.includes("E"))return function(e,t,s){if(!s.eNotation)return e;const i=t.match(ee);if(i){let r=i[1]||"";const n=-1===i[3].indexOf("e")?"E":"e",o=i[2],a=r?e[o.length+1]===n:e[o.length]===n;return o.length>1&&a?e:1!==o.length||!i[3].startsWith(`.${n}`)&&i[3][0]!==n?s.leadingZeros&&!a?(t=(i[1]||"")+i[3],Number(t)):e:Number(t)}return e}(e,s,t);{const i=Q.exec(s);if(i){const r=i[1]||"",n=i[2];let o=function(e){if(e&&-1!==e.indexOf("."))return"."===(e=e.replace(/0+$/,""))?e="0":"."===e[0]?e="0"+e:"."===e[e.length-1]&&(e=e.substring(0,e.length-1)),e;return e}(i[3]);const a=r?"."===e[n.length+1]:"."===e[n.length];if(!t.leadingZeros&&(n.length>1||1===n.length&&!a))return e;{const i=Number(s),a=String(i);if(0===i)return i;if(-1!==a.search(/[eE]/))return t.eNotation?i:e;if(-1!==s.indexOf("."))return"0"===a||a===o||a===`${r}${o}`?i:e;let l=n?o:s;return n?l===a||r+l===a?i:e:l===a||l===r+a?i:e}}return e}}const ee=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function te(e){return"function"==typeof e?e:Array.isArray(e)?t=>{for(const s of e){if("string"==typeof s&&t===s)return!0;if(s instanceof RegExp&&s.test(t))return!0}}:()=>!1}class se{constructor(e){if(this.options=e,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,t)=>ye(t,10,"&#")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,t)=>ye(t,16,"&#x")}},this.addExternalEntities=ie,this.parseXml=le,this.parseTextData=re,this.resolveNameSpace=ne,this.buildAttributesMap=ae,this.isItStopNode=de,this.replaceEntitiesValue=ue,this.readStopNodeData=fe,this.saveTextToParentTag=ce,this.addChild=he,this.ignoreAttributesFn=te(this.options.ignoreAttributes),this.entityExpansionCount=0,this.currentExpandedLength=0,this.options.stopNodes&&this.options.stopNodes.length>0){this.stopNodesExact=new Set,this.stopNodesWildcard=new Set;for(let e=0;e<this.options.stopNodes.length;e++){const t=this.options.stopNodes[e];"string"==typeof t&&(t.startsWith("*.")?this.stopNodesWildcard.add(t.substring(2)):this.stopNodesExact.add(t))}}}}function ie(e){const t=Object.keys(e);for(let s=0;s<t.length;s++){const i=t[s],r=i.replace(/[.\-+*:]/g,"\\.");this.lastEntities[i]={regex:new RegExp("&"+r+";","g"),val:e[i]}}}function re(e,t,s,i,r,n,o){if(void 0!==e&&(this.options.trimValues&&!i&&(e=e.trim()),e.length>0)){o||(e=this.replaceEntitiesValue(e,t,s));const i=this.options.tagValueProcessor(t,e,s,r,n);if(null==i)return e;if(typeof i!=typeof e||i!==e)return i;if(this.options.trimValues)return ge(e,this.options.parseTagValue,this.options.numberParseOptions);return e.trim()===e?ge(e,this.options.parseTagValue,this.options.numberParseOptions):e}}function ne(e){if(this.options.removeNSPrefix){const t=e.split(":"),s="/"===e.charAt(0)?"/":"";if("xmlns"===t[0])return"";2===t.length&&(e=s+t[1])}return e}const oe=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function ae(e,t,s){if(!0!==this.options.ignoreAttributes&&"string"==typeof e){const i=S(e,oe),r=i.length,n={};for(let e=0;e<r;e++){const r=this.resolveNameSpace(i[e][1]);if(this.ignoreAttributesFn(r,t))continue;let o=i[e][4],a=this.options.attributeNamePrefix+r;if(r.length)if(this.options.transformAttributeName&&(a=this.options.transformAttributeName(a)),"__proto__"===a&&(a="#__proto__"),void 0!==o){this.options.trimValues&&(o=o.trim()),o=this.replaceEntitiesValue(o,s,t);const e=this.options.attributeValueProcessor(r,o,t);n[a]=null==e?o:typeof e!=typeof o||e!==o?e:ge(o,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(n[a]=!0)}if(!Object.keys(n).length)return;if(this.options.attributesGroupName){const e={};return e[this.options.attributesGroupName]=n,e}return n}}const le=function(e){e=e.replace(/\r\n?/g,"\n");const t=new W("!xml");let s=t,i="",r="";this.entityExpansionCount=0,this.currentExpandedLength=0;const n=new H(this.options.processEntities);for(let o=0;o<e.length;o++){if("<"===e[o])if("/"===e[o+1]){const t=pe(e,">",o,"Closing Tag is not closed.");let n=e.substring(o+2,t).trim();if(this.options.removeNSPrefix){const e=n.indexOf(":");-1!==e&&(n=n.substr(e+1))}this.options.transformTagName&&(n=this.options.transformTagName(n)),s&&(i=this.saveTextToParentTag(i,s,r));const a=r.substring(r.lastIndexOf(".")+1);if(n&&-1!==this.options.unpairedTags.indexOf(n))throw new Error(`Unpaired tag can not be used as closing tag: </${n}>`);let l=0;a&&-1!==this.options.unpairedTags.indexOf(a)?(l=r.lastIndexOf(".",r.lastIndexOf(".")-1),this.tagsNodeStack.pop()):l=r.lastIndexOf("."),r=r.substring(0,l),s=this.tagsNodeStack.pop(),i="",o=t}else if("?"===e[o+1]){let t=me(e,o,!1,"?>");if(!t)throw new Error("Pi Tag is not closed.");if(i=this.saveTextToParentTag(i,s,r),this.options.ignoreDeclaration&&"?xml"===t.tagName||this.options.ignorePiTags);else{const e=new W(t.tagName);e.add(this.options.textNodeName,""),t.tagName!==t.tagExp&&t.attrExpPresent&&(e[":@"]=this.buildAttributesMap(t.tagExp,r,t.tagName)),this.addChild(s,e,r,o)}o=t.closeIndex+1}else if("!--"===e.substr(o+1,3)){const t=pe(e,"--\x3e",o+4,"Comment is not closed.");if(this.options.commentPropName){const n=e.substring(o+4,t-2);i=this.saveTextToParentTag(i,s,r),s.add(this.options.commentPropName,[{[this.options.textNodeName]:n}])}o=t}else if("!D"===e.substr(o+1,2)){const t=n.readDocType(e,o);this.docTypeEntities=t.entities,o=t.i}else if("!["===e.substr(o+1,2)){const t=pe(e,"]]>",o,"CDATA is not closed.")-2,n=e.substring(o+9,t);i=this.saveTextToParentTag(i,s,r);let a=this.parseTextData(n,s.tagname,r,!0,!1,!0,!0);null==a&&(a=""),this.options.cdataPropName?s.add(this.options.cdataPropName,[{[this.options.textNodeName]:n}]):s.add(this.options.textNodeName,a),o=t+2}else{let n=me(e,o,this.options.removeNSPrefix),a=n.tagName;const l=n.rawTagName;let h=n.tagExp,u=n.attrExpPresent,c=n.closeIndex;if(this.options.transformTagName){const e=this.options.transformTagName(a);h===a&&(h=e),a=e}s&&i&&"!xml"!==s.tagname&&(i=this.saveTextToParentTag(i,s,r,!1));const d=s;d&&-1!==this.options.unpairedTags.indexOf(d.tagname)&&(s=this.tagsNodeStack.pop(),r=r.substring(0,r.lastIndexOf("."))),a!==t.tagname&&(r+=r?"."+a:a);const p=o;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,r,a)){let t="";if(h.length>0&&h.lastIndexOf("/")===h.length-1)"/"===a[a.length-1]?(a=a.substr(0,a.length-1),r=r.substr(0,r.length-1),h=a):h=h.substr(0,h.length-1),o=n.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(a))o=n.closeIndex;else{const s=this.readStopNodeData(e,l,c+1);if(!s)throw new Error(`Unexpected end of ${l}`);o=s.i,t=s.tagContent}const i=new W(a);a!==h&&u&&(i[":@"]=this.buildAttributesMap(h,r,a)),t&&(t=this.parseTextData(t,a,r,!0,u,!0,!0)),r=r.substr(0,r.lastIndexOf(".")),i.add(this.options.textNodeName,t),this.addChild(s,i,r,p)}else{if(h.length>0&&h.lastIndexOf("/")===h.length-1){if("/"===a[a.length-1]?(a=a.substr(0,a.length-1),r=r.substr(0,r.length-1),h=a):h=h.substr(0,h.length-1),this.options.transformTagName){const e=this.options.transformTagName(a);h===a&&(h=e),a=e}const e=new W(a);a!==h&&u&&(e[":@"]=this.buildAttributesMap(h,r,a)),this.addChild(s,e,r,p),r=r.substr(0,r.lastIndexOf("."))}else{const e=new W(a);this.tagsNodeStack.push(s),a!==h&&u&&(e[":@"]=this.buildAttributesMap(h,r,a)),this.addChild(s,e,r,p),s=e}i="",o=c}}else i+=e[o]}return t.child};function he(e,t,s,i){this.options.captureMetaData||(i=void 0);const r=this.options.updateTag(t.tagname,s,t[":@"]);!1===r||("string"==typeof r?(t.tagname=r,e.addChild(t,i)):e.addChild(t,i))}const ue=function(e,t,s){if(-1===e.indexOf("&"))return e;const i=this.options.processEntities;if(!i.enabled)return e;if(i.allowedTags&&!i.allowedTags.includes(t))return e;if(i.tagFilter&&!i.tagFilter(t,s))return e;for(let t in this.docTypeEntities){const s=this.docTypeEntities[t],r=e.match(s.regx);if(r){if(this.entityExpansionCount+=r.length,i.maxTotalExpansions&&this.entityExpansionCount>i.maxTotalExpansions)throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${i.maxTotalExpansions}`);const t=e.length;if(e=e.replace(s.regx,s.val),i.maxExpandedLength&&(this.currentExpandedLength+=e.length-t,this.currentExpandedLength>i.maxExpandedLength))throw new Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${i.maxExpandedLength}`)}}if(-1===e.indexOf("&"))return e;for(let t in this.lastEntities){const s=this.lastEntities[t];e=e.replace(s.regex,s.val)}if(-1===e.indexOf("&"))return e;if(this.options.htmlEntities)for(let t in this.htmlEntities){const s=this.htmlEntities[t];e=e.replace(s.regex,s.val)}return e=e.replace(this.ampEntity.regex,this.ampEntity.val)};function ce(e,t,s,i){return e&&(void 0===i&&(i=0===t.child.length),void 0!==(e=this.parseTextData(e,t.tagname,s,!1,!!t[":@"]&&0!==Object.keys(t[":@"]).length,i))&&""!==e&&t.add(this.options.textNodeName,e),e=""),e}function de(e,t,s,i){return!(!t||!t.has(i))||!(!e||!e.has(s))}function pe(e,t,s,i){const r=e.indexOf(t,s);if(-1===r)throw new Error(i);return r+t.length-1}function me(e,t,s,i=">"){const r=function(e,t,s=">"){let i,r="";for(let n=t;n<e.length;n++){let t=e[n];if(i)t===i&&(i="");else if('"'===t||"'"===t)i=t;else if(t===s[0]){if(!s[1])return{data:r,index:n};if(e[n+1]===s[1])return{data:r,index:n}}else"\t"===t&&(t=" ");r+=t}}(e,t+1,i);if(!r)return;let n=r.data;const o=r.index,a=n.search(/\s/);let l=n,h=!0;-1!==a&&(l=n.substring(0,a),n=n.substring(a+1).trimStart());const u=l;if(s){const e=l.indexOf(":");-1!==e&&(l=l.substr(e+1),h=l!==r.data.substr(e+1))}return{tagName:l,tagExp:n,closeIndex:o,attrExpPresent:h,rawTagName:u}}function fe(e,t,s){const i=s;let r=1;for(;s<e.length;s++)if("<"===e[s])if("/"===e[s+1]){const n=pe(e,">",s,`${t} is not closed`);if(e.substring(s+2,n).trim()===t&&(r--,0===r))return{tagContent:e.substring(i,s),i:n};s=n}else if("?"===e[s+1]){s=pe(e,"?>",s+1,"StopNode is not closed.")}else if("!--"===e.substr(s+1,3)){s=pe(e,"--\x3e",s+3,"StopNode is not closed.")}else if("!["===e.substr(s+1,2)){s=pe(e,"]]>",s,"StopNode is not closed.")-2}else{const i=me(e,s,">");if(i){(i&&i.tagName)===t&&"/"!==i.tagExp[i.tagExp.length-1]&&r++,s=i.closeIndex}}}function ge(e,t,s){if(t&&"string"==typeof e){const t=e.trim();return"true"===t||"false"!==t&&J(e,s)}return void 0!==e?e:""}function ye(e,t,s){const i=Number.parseInt(e,t);return i>=0&&i<=1114111?String.fromCodePoint(i):s+e+";"}const xe=W.getMetaDataSymbol();function be(e,t){return _e(e,t)}function _e(e,t,s){let i;const r={};for(let n=0;n<e.length;n++){const o=e[n],a=we(o);let l="";if(l=void 0===s?a:s+"."+a,a===t.textNodeName)void 0===i?i=o[a]:i+=""+o[a];else{if(void 0===a)continue;if(o[a]){let e=_e(o[a],t,l);const s=Te(e,t);void 0!==o[xe]&&(e[xe]=o[xe]),o[":@"]?ve(e,o[":@"],l,t):1!==Object.keys(e).length||void 0===e[t.textNodeName]||t.alwaysCreateTextNode?0===Object.keys(e).length&&(t.alwaysCreateTextNode?e[t.textNodeName]="":e=""):e=e[t.textNodeName],void 0!==r[a]&&r.hasOwnProperty(a)?(Array.isArray(r[a])||(r[a]=[r[a]]),r[a].push(e)):t.isArray(a,l,s)?r[a]=[e]:r[a]=e}}}return"string"==typeof i?i.length>0&&(r[t.textNodeName]=i):void 0!==i&&(r[t.textNodeName]=i),r}function we(e){const t=Object.keys(e);for(let e=0;e<t.length;e++){const s=t[e];if(":@"!==s)return s}}function ve(e,t,s,i){if(t){const r=Object.keys(t),n=r.length;for(let o=0;o<n;o++){const n=r[o];i.isArray(n,s+"."+n,!0,!0)?e[n]=[t[n]]:e[n]=t[n]}}}function Te(e,t){const{textNodeName:s}=t,i=Object.keys(e).length;return 0===i||!(1!==i||!e[s]&&"boolean"!=typeof e[s]&&0!==e[s])}class Se{constructor(e){this.externalEntities={},this.options=j(e)}parse(e,t){if("string"!=typeof e&&e.toString)e=e.toString();else if("string"!=typeof e)throw new Error("XML data is accepted in String or Bytes[] form.");if(t){!0===t&&(t={});const s=function(e,t){t=Object.assign({},A,t);const s=[];let i=!1,r=!1;"\ufeff"===e[0]&&(e=e.substr(1));for(let n=0;n<e.length;n++)if("<"===e[n]&&"?"===e[n+1]){if(n+=2,n=E(e,n),n.err)return n}else{if("<"!==e[n]){if(N(e[n]))continue;return F("InvalidChar","char '"+e[n]+"' is not expected.",z(e,n))}{let o=n;if(n++,"!"===e[n]){n=C(e,n);continue}{let a=!1;"/"===e[n]&&(a=!0,n++);let l="";for(;n<e.length&&">"!==e[n]&&" "!==e[n]&&"\t"!==e[n]&&"\n"!==e[n]&&"\r"!==e[n];n++)l+=e[n];if(l=l.trim(),"/"===l[l.length-1]&&(l=l.substring(0,l.length-1),n--),!V(l)){let t;return t=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",F("InvalidTag",t,z(e,n))}const h=B(e,n);if(!1===h)return F("InvalidAttr","Attributes for '"+l+"' have open quote.",z(e,n));let u=h.value;if(n=h.index,"/"===u[u.length-1]){const s=n-u.length;u=u.substring(0,u.length-1);const r=D(u,t);if(!0!==r)return F(r.err.code,r.err.msg,z(e,s+r.err.line));i=!0}else if(a){if(!h.tagClosed)return F("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",z(e,n));if(u.trim().length>0)return F("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",z(e,o));if(0===s.length)return F("InvalidTag","Closing tag '"+l+"' has not been opened.",z(e,o));{const t=s.pop();if(l!==t.tagName){let s=z(e,t.tagStartPos);return F("InvalidTag","Expected closing tag '"+t.tagName+"' (opened in line "+s.line+", col "+s.col+") instead of closing tag '"+l+"'.",z(e,o))}0==s.length&&(r=!0)}}else{const a=D(u,t);if(!0!==a)return F(a.err.code,a.err.msg,z(e,n-u.length+a.err.line));if(!0===r)return F("InvalidXml","Multiple possible root nodes found.",z(e,n));-1!==t.unpairedTags.indexOf(l)||s.push({tagName:l,tagStartPos:o}),i=!0}for(n++;n<e.length;n++)if("<"===e[n]){if("!"===e[n+1]){n++,n=C(e,n);continue}if("?"!==e[n+1])break;if(n=E(e,++n),n.err)return n}else if("&"===e[n]){const t=L(e,n);if(-1==t)return F("InvalidChar","char '&' is not expected.",z(e,n));n=t}else if(!0===r&&!N(e[n]))return F("InvalidXml","Extra text at the end",z(e,n));"<"===e[n]&&n--}}}return i?1==s.length?F("InvalidTag","Unclosed tag '"+s[0].tagName+"'.",z(e,s[0].tagStartPos)):!(s.length>0)||F("InvalidXml","Invalid '"+JSON.stringify(s.map(e=>e.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):F("InvalidXml","Start tag expected.",1)}(e,t);if(!0!==s)throw Error(`${s.err.msg}:${s.err.line}:${s.err.col}`)}const s=new se(this.options);s.addExternalEntities(this.externalEntities);const i=s.parseXml(e);return this.options.preserveOrder||void 0===i?i:be(i,this.options)}addEntity(e,t){if(-1!==t.indexOf("&"))throw new Error("Entity value can't have '&'");if(-1!==e.indexOf("&")||-1!==e.indexOf(";"))throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if("&"===t)throw new Error("An entity with value '&' is not permitted");this.externalEntities[e]=t}static getMetaDataSymbol(){return W.getMetaDataSymbol()}}function Me(e,t){let s="";return t.format&&t.indentBy.length>0&&(s="\n"),Ae(e,t,"",s)}function Ae(e,t,s,i){let r="",n=!1;for(let o=0;o<e.length;o++){const a=e[o],l=Ne(a);if(void 0===l)continue;let h="";if(h=0===s.length?l:`${s}.${l}`,l===t.textNodeName){let e=a[l];Ce(h,t)||(e=t.tagValueProcessor(l,e),e=Re(e,t)),n&&(r+=i),r+=e,n=!1;continue}if(l===t.cdataPropName){n&&(r+=i),r+=`<![CDATA[${a[l][0][t.textNodeName]}]]>`,n=!1;continue}if(l===t.commentPropName){r+=i+`\x3c!--${a[l][0][t.textNodeName]}--\x3e`,n=!0;continue}if("?"===l[0]){const e=Ee(a[":@"],t),s="?xml"===l?"":i;let o=a[l][0][t.textNodeName];o=0!==o.length?" "+o:"",r+=s+`<${l}${o}${e}?>`,n=!0;continue}let u=i;""!==u&&(u+=t.indentBy);const c=i+`<${l}${Ee(a[":@"],t)}`,d=Ae(a[l],t,h,u);-1!==t.unpairedTags.indexOf(l)?t.suppressUnpairedNode?r+=c+">":r+=c+"/>":d&&0!==d.length||!t.suppressEmptyNode?d&&d.endsWith(">")?r+=c+`>${d}${i}</${l}>`:(r+=c+">",d&&""!==i&&(d.includes("/>")||d.includes("</"))?r+=i+t.indentBy+d+i:r+=d,r+=`</${l}>`):r+=c+"/>",n=!0}return r}function Ne(e){const t=Object.keys(e);for(let s=0;s<t.length;s++){const i=t[s];if(e.hasOwnProperty(i)&&":@"!==i)return i}}function Ee(e,t){let s="";if(e&&!t.ignoreAttributes)for(let i in e){if(!e.hasOwnProperty(i))continue;let r=t.attributeValueProcessor(i,e[i]);r=Re(r,t),!0===r&&t.suppressBooleanAttributes?s+=` ${i.substr(t.attributeNamePrefix.length)}`:s+=` ${i.substr(t.attributeNamePrefix.length)}="${r}"`}return s}function Ce(e,t){let s=(e=e.substr(0,e.length-t.textNodeName.length-1)).substr(e.lastIndexOf(".")+1);for(let i in t.stopNodes)if(t.stopNodes[i]===e||t.stopNodes[i]==="*."+s)return!0;return!1}function Re(e,t){if(e&&e.length>0&&t.processEntities)for(let s=0;s<t.entities.length;s++){const i=t.entities[s];e=e.replace(i.regex,i.val)}return e}const Pe={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function Be(e){this.options=Object.assign({},Pe,e),!0===this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=te(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=Le),this.processTextOrObjNode=Ie,this.options.format?(this.indentate=De,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function Ie(e,t,s,i){const r=this.j2x(e,s+1,i.concat(t));return void 0!==e[this.options.textNodeName]&&1===Object.keys(e).length?this.buildTextValNode(e[this.options.textNodeName],t,r.attrStr,s):this.buildObjectNode(r.val,t,r.attrStr,s)}function De(e){return this.options.indentBy.repeat(e)}function Le(e){return!(!e.startsWith(this.options.attributeNamePrefix)||e===this.options.textNodeName)&&e.substr(this.attrPrefixLen)}Be.prototype.build=function(e){return this.options.preserveOrder?Me(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0,[]).val)},Be.prototype.j2x=function(e,t,s){let i="",r="";const n=s.join(".");for(let o in e)if(Object.prototype.hasOwnProperty.call(e,o))if(void 0===e[o])this.isAttribute(o)&&(r+="");else if(null===e[o])this.isAttribute(o)||o===this.options.cdataPropName?r+="":"?"===o[0]?r+=this.indentate(t)+"<"+o+"?"+this.tagEndChar:r+=this.indentate(t)+"<"+o+"/"+this.tagEndChar;else if(e[o]instanceof Date)r+=this.buildTextValNode(e[o],o,"",t);else if("object"!=typeof e[o]){const s=this.isAttribute(o);if(s&&!this.ignoreAttributesFn(s,n))i+=this.buildAttrPairStr(s,""+e[o]);else if(!s)if(o===this.options.textNodeName){let t=this.options.tagValueProcessor(o,""+e[o]);r+=this.replaceEntitiesValue(t)}else r+=this.buildTextValNode(e[o],o,"",t)}else if(Array.isArray(e[o])){const i=e[o].length;let n="",a="";for(let l=0;l<i;l++){const i=e[o][l];if(void 0===i);else if(null===i)"?"===o[0]?r+=this.indentate(t)+"<"+o+"?"+this.tagEndChar:r+=this.indentate(t)+"<"+o+"/"+this.tagEndChar;else if("object"==typeof i)if(this.options.oneListGroup){const e=this.j2x(i,t+1,s.concat(o));n+=e.val,this.options.attributesGroupName&&i.hasOwnProperty(this.options.attributesGroupName)&&(a+=e.attrStr)}else n+=this.processTextOrObjNode(i,o,t,s);else if(this.options.oneListGroup){let e=this.options.tagValueProcessor(o,i);e=this.replaceEntitiesValue(e),n+=e}else n+=this.buildTextValNode(i,o,"",t)}this.options.oneListGroup&&(n=this.buildObjectNode(n,o,a,t)),r+=n}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){const t=Object.keys(e[o]),s=t.length;for(let r=0;r<s;r++)i+=this.buildAttrPairStr(t[r],""+e[o][t[r]])}else r+=this.processTextOrObjNode(e[o],o,t,s);return{attrStr:i,val:r}},Be.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,""+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&"true"===t?" "+e:" "+e+'="'+t+'"'},Be.prototype.buildObjectNode=function(e,t,s,i){if(""===e)return"?"===t[0]?this.indentate(i)+"<"+t+s+"?"+this.tagEndChar:this.indentate(i)+"<"+t+s+this.closeTag(t)+this.tagEndChar;{let r="</"+t+this.tagEndChar,n="";return"?"===t[0]&&(n="?",r=""),!s&&""!==s||-1!==e.indexOf("<")?!1!==this.options.commentPropName&&t===this.options.commentPropName&&0===n.length?this.indentate(i)+`\x3c!--${e}--\x3e`+this.newLine:this.indentate(i)+"<"+t+s+n+this.tagEndChar+e+this.indentate(i)+r:this.indentate(i)+"<"+t+s+n+">"+e+r}},Be.prototype.closeTag=function(e){let t="";return-1!==this.options.unpairedTags.indexOf(e)?this.options.suppressUnpairedNode||(t="/"):t=this.options.suppressEmptyNode?"/":`></${e}`,t},Be.prototype.buildTextValNode=function(e,t,s,i){if(!1!==this.options.cdataPropName&&t===this.options.cdataPropName)return this.indentate(i)+`<![CDATA[${e}]]>`+this.newLine;if(!1!==this.options.commentPropName&&t===this.options.commentPropName)return this.indentate(i)+`\x3c!--${e}--\x3e`+this.newLine;if("?"===t[0])return this.indentate(i)+"<"+t+s+"?"+this.tagEndChar;{let r=this.options.tagValueProcessor(t,e);return r=this.replaceEntitiesValue(r),""===r?this.indentate(i)+"<"+t+s+this.closeTag(t)+this.tagEndChar:this.indentate(i)+"<"+t+s+">"+r+"</"+t+this.tagEndChar}},Be.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){const s=this.options.entities[t];e=e.replace(s.regex,s.val)}return e};class Fe{}t(Fe,"parser",new Se({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0})),t(Fe,"builder",new Be({attributeNamePrefix:"$",ignoreAttributes:!1,suppressBooleanAttributes:!1}));class Oe{static join(e){const t={};for(const s of e)for(const e in s)if(t[e])for(const i of s[e])t[e].add(i);else t[e]=new Set(s[e]);return t}static intersect(e){if(0===e.length)return{};let t=Oe.clone(e[0]);for(let s=1;s<e.length;s++){const i=e[s],r={};for(const e in t)if(i[e]){const s=new Set;for(const r of t[e])i[e].has(r)&&s.add(r);s.size>0&&(r[e]=s)}t=r}return t}static clone(e){const t={};for(const s in e)t[s]=new Set(e[s]);return t}static remove(e,t,s=!1){s&&(e=Oe.clone(e));for(const s in t)if(e[s]){for(const i of t[s])e[s].delete(i);0===e[s].size&&delete e[s]}}static add(e,t,s=!1){s&&(e=Oe.clone(e));for(const s in t)if(e[s])for(const i of t[s])e[s].add(i);else e[s]=new Set(t[s])}static append(e,t,...s){let i=e[t];i||(i=new Set,e[t]=i);for(const e of s)i.add(e)}static isEqual(e,t){const s=Object.keys(e),i=Object.keys(t);if(s.length!==i.length)return!1;for(const i of s){if(!t[i])return!1;if(e[i].size!==t[i].size)return!1;for(const s of e[i])if(!t[i].has(s))return!1}return!0}static isEmpty(e){return 0===Object.values(e).reduce((e,t)=>e+t.size,0)}static toRaw(e){const t={};for(const s in e)t[s]=Array.from(e[s]);return t}static fromRaw(e){const t={};for(const s in e)t[s]=new Set(e[s]);return t}}let Ve=class extends Map{constructor(e){super(e),t(this,"onItemSet",new u),t(this,"onItemUpdated",new u),t(this,"onItemDeleted",new u),t(this,"onCleared",new u),t(this,"guard",()=>!0)}clear(){super.clear(),this.onCleared.trigger()}set(e,t){const s=this.has(e);if(!(this.guard??(()=>!0))(e,t))return this;const i=super.set(e,t);return s?(this.onItemUpdated||(this.onItemUpdated=new u),this.onItemUpdated.trigger({key:e,value:t})):(this.onItemSet||(this.onItemSet=new u),this.onItemSet.trigger({key:e,value:t})),i}add(e){const t=w.create();return this.set(t,e),t}delete(e){const t=super.delete(e);return t&&this.onItemDeleted.trigger(e),t}dispose(){this.clear(),this.onItemSet.reset(),this.onItemDeleted.reset(),this.onCleared.reset()}};class ze{static isEntry(e){return new Set(["Boolean","Color","Text","Number","Select","Vector3","TextSet","None"]).has(e.type)}static copySchema(e,t={}){for(const s in e){const i=e[s];this.isEntry(i)?t[s]=this.copyEntry(i):(t[s]={},this.copySchema(i,t[s]))}return t}static copyEntry(e){if("Boolean"===e.type){const t=e;return{type:t.type,value:t.value}}if("Color"===e.type){const t=e;return{type:t.type,value:t.value.clone()}}if("Text"===e.type){const t=e;return{type:t.type,value:t.value}}if("Number"===e.type){const t=e;return{type:t.type,value:t.value,min:t.min,max:t.max,interpolable:t.interpolable}}if("Select"===e.type){const t=e;return{type:t.type,value:t.value,multiple:t.multiple,options:new Set(t.options)}}if("Vector3"===e.type){const t=e;return{type:t.type,value:t.value.clone()}}if("TextSet"===e.type){const t=e;return{type:t.type,value:new Set(t.value)}}if("None"===e.type){const t=e;return{type:t.type,value:t.value}}throw new Error("Invalid entry!")}}class ke{constructor(e,s,i,r){t(this,"_component"),t(this,"name"),t(this,"uuid"),this._component=e,this.name=i,this.uuid=r??w.create();s.get(Ge).list.set(this.uuid,this)}get controls(){return ze.copySchema(this._config)}set(e){for(const t in e)if(t in this){this[t]=e[t].value}}export(e=this._config,t={}){for(const s in e){const i=e[s];if(ze.isEntry(i))if("Color"===i.type){const{r:e,g:r,b:n}=i.value;t[s]={...i,value:{r:e,g:r,b:n}}}else if("Vector3"===i.type){const{x:e,y:r,z:n}=i.value;t[s]={...i,value:{x:e,y:r,z:n}}}else if("TextSet"===i.type){const e=Array.from(i.value);t[s]={...i,value:e}}else if("Select"===i.type){const e=Array.from(i.options);t[s]={...i,options:e}}else t[s]={...i};else t[s]={},this.export(i,t[s])}return t}import(e,t={},s=!0){for(const s in e){const i=e[s];if(ze.isEntry(i))if("Color"===i.type){const{r:e,g:r,b:n}=i.value;t[s]={...i,value:new l.Color(e,r,n)}}else if("Vector3"===i.type){const{x:e,y:r,z:n}=i.value;t[s]={...i,value:new l.Vector3(e,r,n)}}else"TextSet"===i.type?t[s]={...i,value:new Set(i.value)}:"Select"===i.type?t[s]={...i,options:new Set(i.options)}:t[s]={...i};else t[s]={},this.import(i,t[s],!1)}s&&this.set(t)}}const Ue=class e extends d{constructor(i){super(i),t(this,"list",new s.DataMap),t(this,"enabled",!0),i.add(e.uuid,this)}};t(Ue,"uuid","b8c764e0-6b24-4e77-9a32-35fa728ee5b4");let Ge=Ue;class je{constructor(e){t(this,"_event"),t(this,"_position",new l.Vector2),t(this,"onDisposed",new u),t(this,"updateMouseInfo",e=>{this._event=e}),this.dom=e,this.setupEvents(!0)}get position(){return this.updatePosition(!1),this._position.clone()}get rawPosition(){return this.updatePosition(!0),this._position.clone()}dispose(){this.setupEvents(!1),this.onDisposed.trigger(),this.onDisposed.reset()}updatePosition(e){if(this._event){const t=this.dom.getBoundingClientRect();this._position.x=this.getPositionX(t,this._event,e),this._position.y=this.getPositionY(t,this._event,e)}}getPositionY(e,t,s){const i=this.getDataObject(t);return s?i.clientY:-(i.clientY-e.top)/(e.bottom-e.top)*2+1}getPositionX(e,t,s){const i=this.getDataObject(t);return s?i.clientX:(i.clientX-e.left)/(e.right-e.left)*2-1}getDataObject(e){return e instanceof MouseEvent?e:e.touches[0]}setupEvents(e){e?(this.dom.addEventListener("pointermove",this.updateMouseInfo),this.dom.addEventListener("touchstart",this.updateMouseInfo)):(this.dom.removeEventListener("pointermove",this.updateMouseInfo),this.dom.removeEventListener("touchstart",this.updateMouseInfo))}}const $e=1.25,We=32,He=Math.pow(2,-24),qe=Symbol("SKIP_GENERATION"),Xe={strategy:0,maxDepth:40,maxLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[qe]:!1};function Ye(e,t,s){return s.min.x=t[e],s.min.y=t[e+1],s.min.z=t[e+2],s.max.x=t[e+3],s.max.y=t[e+4],s.max.z=t[e+5],s}function Ze(e){let t=-1,s=-1/0;for(let i=0;i<3;i++){const r=e[i+3]-e[i];r>s&&(s=r,t=i)}return t}function Qe(e,t){t.set(e)}function Ke(e,t,s){let i,r;for(let n=0;n<3;n++){const o=n+3;i=e[n],r=t[n],s[n]=i<r?i:r,i=e[o],r=t[o],s[o]=i>r?i:r}}function Je(e,t,s){for(let i=0;i<3;i++){const r=t[e+2*i],n=t[e+2*i+1],o=r-n,a=r+n;o<s[i]&&(s[i]=o),a>s[i+3]&&(s[i+3]=a)}}function et(e){const t=e[3]-e[0],s=e[4]-e[1],i=e[5]-e[2];return 2*(t*s+s*i+i*t)}function tt(e,t){return 65535===t[e+15]}function st(e,t){return t[e+6]}function it(e,t){return t[e+14]}function rt(e){return e+8}function nt(e,t){return e+8*t[e+6]}function ot(e,t){return t[e+7]}function at(e){return e}function lt(e,t,s,i,r){let n=1/0,o=1/0,a=1/0,l=-1/0,h=-1/0,u=-1/0,c=1/0,d=1/0,p=1/0,m=-1/0,f=-1/0,g=-1/0;const y=e.offset||0;for(let i=6*(t-y),r=6*(t+s-y);i<r;i+=6){const t=e[i+0],s=e[i+1],r=t-s,y=t+s;r<n&&(n=r),y>l&&(l=y),t<c&&(c=t),t>m&&(m=t);const x=e[i+2],b=e[i+3],_=x-b,w=x+b;_<o&&(o=_),w>h&&(h=w),x<d&&(d=x),x>f&&(f=x);const v=e[i+4],T=e[i+5],S=v-T,M=v+T;S<a&&(a=S),M>u&&(u=M),v<p&&(p=v),v>g&&(g=v)}i[0]=n,i[1]=o,i[2]=a,i[3]=l,i[4]=h,i[5]=u,r[0]=c,r[1]=d,r[2]=p,r[3]=m,r[4]=f,r[5]=g}const ht=32,ut=(e,t)=>e.candidate-t.candidate,ct=new Array(ht).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),dt=new Float32Array(6);class pt{constructor(){this.boundingData=new Float32Array(6)}}let mt,ft,gt,yt;const xt=Math.pow(2,32);function bt(e){return"count"in e?1:1+bt(e.left)+bt(e.right)}function _t(e,t,s){return mt=new Float32Array(s),ft=new Uint32Array(s),gt=new Uint16Array(s),yt=new Uint8Array(s),wt(e,t)}function wt(e,t){const s=e/4,i=e/2,r="count"in t,n=t.boundingData;for(let e=0;e<6;e++)mt[s+e]=n[e];if(r)return t.buffer?(yt.set(new Uint8Array(t.buffer),e),e+t.buffer.byteLength):(ft[s+6]=t.offset,gt[i+14]=t.count,gt[i+15]=65535,e+We);{const{left:i,right:r,splitAxis:n}=t;let o=wt(e+We,i);const a=o/We-e/We;if(a>xt)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return ft[s+6]=a,ft[s+7]=n,wt(o,r)}}function vt(e,t,s,i,r,n){const{maxDepth:o,verbose:a,maxLeafSize:l,strategy:h,onProgress:u}=r,c=e.primitiveBuffer,d=e.primitiveBufferStride,p=new Float32Array(6);let m=!1;const f=new pt;return lt(t,s,i,f.boundingData,p),function e(s,i,r,n=null,u=0){!m&&u>=o&&(m=!0,a&&console.warn(`BVH: Max depth of ${o} reached when generating BVH. Consider increasing maxDepth.`));if(r<=l||u>=o)return g(i+r),s.offset=i,s.count=r,s;const f=function(e,t,s,i,r,n){let o=-1,a=0;if(0===n)o=Ze(t),-1!==o&&(a=(t[o]+t[o+3])/2);else if(1===n)o=Ze(e),-1!==o&&(a=function(e,t,s,i){let r=0;const n=e.offset;for(let o=t,a=t+s;o<a;o++)r+=e[6*(o-n)+2*i];return r/s}(s,i,r,o));else if(2===n){const n=et(e);let l=$e*r;const h=s.offset||0,u=6*(i-h),c=6*(i+r-h);for(let e=0;e<3;e++){const i=t[e],h=(t[e+3]-i)/ht;if(r<8){const t=[...ct];t.length=r;let i=0;for(let r=u;r<c;r+=6,i++){const n=t[i];n.candidate=s[r+2*e],n.count=0;const{bounds:o,leftCacheBounds:a,rightCacheBounds:l}=n;for(let e=0;e<3;e++)l[e]=1/0,l[e+3]=-1/0,a[e]=1/0,a[e+3]=-1/0,o[e]=1/0,o[e+3]=-1/0;Je(r,s,o)}t.sort(ut);let h=r;for(let e=0;e<h;e++){const s=t[e];for(;e+1<h&&t[e+1].candidate===s.candidate;)t.splice(e+1,1),h--}for(let i=u;i<c;i+=6){const r=s[i+2*e];for(let e=0;e<h;e++){const n=t[e];r>=n.candidate?Je(i,s,n.rightCacheBounds):(Je(i,s,n.leftCacheBounds),n.count++)}}for(let s=0;s<h;s++){const i=t[s],h=i.count,u=r-i.count,c=i.leftCacheBounds,d=i.rightCacheBounds;let p=0;0!==h&&(p=et(c)/n);let m=0;0!==u&&(m=et(d)/n);const f=1+$e*(p*h+m*u);f<l&&(o=e,l=f,a=i.candidate)}}else{for(let e=0;e<ht;e++){const t=ct[e];t.count=0,t.candidate=i+h+e*h;const s=t.bounds;for(let e=0;e<3;e++)s[e]=1/0,s[e+3]=-1/0}for(let t=u;t<c;t+=6){let r=~~((s[t+2*e]-i)/h);r>=ht&&(r=31);const n=ct[r];n.count++,Je(t,s,n.bounds)}const t=ct[31];Qe(t.bounds,t.rightCacheBounds);for(let e=30;e>=0;e--){const t=ct[e],s=ct[e+1];Ke(t.bounds,s.rightCacheBounds,t.rightCacheBounds)}let d=0;for(let t=0;t<31;t++){const s=ct[t],i=s.count,h=s.bounds,u=ct[t+1].rightCacheBounds;0!==i&&(0===d?Qe(h,dt):Ke(h,dt,dt)),d+=i;let c=0,p=0;0!==d&&(c=et(dt)/n);const m=r-d;0!==m&&(p=et(u)/n);const f=1+$e*(c*d+p*m);f<l&&(o=e,l=f,a=s.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${n} used.`);return{axis:o,pos:a}}(s.boundingData,n,t,i,r,h);if(-1===f.axis)return g(i+r),s.offset=i,s.count=r,s;const y=function(e,t,s,i,r,n){let o=i,a=i+r-1;const l=n.pos,h=2*n.axis,u=s.offset||0;for(;;){for(;o<=a&&s[6*(o-u)+h]<l;)o++;for(;o<=a&&s[6*(a-u)+h]>=l;)a--;if(!(o<a))return o;for(let s=0;s<t;s++){let i=e[o*t+s];e[o*t+s]=e[a*t+s],e[a*t+s]=i}for(let e=0;e<6;e++){const t=o-u,i=a-u,r=s[6*t+e];s[6*t+e]=s[6*i+e],s[6*i+e]=r}o++,a--}}(c,d,t,i,r,f);if(y===i||y===i+r)g(i+r),s.offset=i,s.count=r;else{s.splitAxis=f.axis;const n=new pt,o=i,a=y-i;s.left=n,lt(t,o,a,n.boundingData,p),e(n,o,a,p,u+1);const l=new pt,h=y,c=r-a;s.right=l,lt(t,h,c,l.boundingData,p),e(l,h,c,p,u+1)}return s}(f,s,i,p),f;function g(e){u&&u((e-n.offset)/n.count)}}function Tt(e,t){const s=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=e.getRootRanges(t.range),r=i[0],n=i[i.length-1],o={offset:r.offset,count:n.offset+n.count-r.offset},a=new Float32Array(6*o.count);a.offset=o.offset,e.computePrimitiveBounds(o.offset,o.count,a),e._roots=i.map(i=>{const r=vt(e,a,i.offset,i.count,t,o),n=bt(r),l=new s(We*n);return _t(0,r,l),l})}class St{constructor(e){this._getNewPrimitive=e,this._primitives=[]}getPrimitive(){const e=this._primitives;return 0===e.length?this._getNewPrimitive():e.pop()}releasePrimitive(e){this._primitives.push(e)}}class Mt{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const e=[];let t=null;this.setBuffer=s=>{t&&e.push(t),t=s,this.float32Array=new Float32Array(s),this.uint16Array=new Uint16Array(s),this.uint32Array=new Uint32Array(s)},this.clearBuffer=()=>{t=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,0!==e.length&&this.setBuffer(e.pop())}}}const At=new Mt;let Nt,Et;const Ct=[],Rt=new St(()=>new i.Box3);function Pt(e,t,s,i,r,n){Nt=Rt.getPrimitive(),Et=Rt.getPrimitive(),Ct.push(Nt,Et),At.setBuffer(e._roots[t]);const o=Bt(0,e.geometry,s,i,r,n);At.clearBuffer(),Rt.releasePrimitive(Nt),Rt.releasePrimitive(Et),Ct.pop(),Ct.pop();const a=Ct.length;return a>0&&(Et=Ct[a-1],Nt=Ct[a-2]),o}function Bt(e,t,s,i,r=null,n=0,o=0){const{float32Array:a,uint16Array:l,uint32Array:h}=At;let u=2*e;if(tt(u,l)){const t=st(e,h),s=it(u,l);return Ye(e,a,Nt),i(t,s,!1,o,n+e/8,Nt)}{let u=function(e){const{uint16Array:t,uint32Array:s}=At;let i=2*e;for(;!tt(i,t);)i=2*(e=rt(e));return st(e,s)},c=function(e){const{uint16Array:t,uint32Array:s}=At;let i=2*e;for(;!tt(i,t);)i=2*(e=nt(e,s));return st(e,s)+it(i,t)};const d=rt(e),p=nt(e,h);let m,f,g,y,x=d,b=p;if(r&&(g=Nt,y=Et,Ye(x,a,g),Ye(b,a,y),m=r(g),f=r(y),f<m)){x=p,b=d;const e=m;m=f,f=e,g=y}g||(g=Nt,Ye(x,a,g));const _=s(g,tt(2*x,l),m,o+1,n+x/8);let w;if(2===_){const e=u(x);w=i(e,c(x)-e,!0,o+1,n+x/8,g)}else w=_&&Bt(x,t,s,i,r,n,o+1);if(w)return!0;y=Et,Ye(b,a,y);const v=s(y,tt(2*b,l),f,o+1,n+b/8);let T;if(2===v){const e=u(b);T=i(e,c(b)-e,!0,o+1,n+b/8,y)}else T=v&&Bt(b,t,s,i,r,n,o+1);return!!T}}const It=new At.constructor,Dt=new At.constructor,Lt=new St(()=>new i.Box3),Ft=new i.Box3,Ot=new i.Box3,Vt=new i.Box3,zt=new i.Box3;let kt=!1;function Ut(e,t,s,i,r,n=0,o=0,a=0,l=0,h=null,u=!1){let c,d;u?(c=Dt,d=It):(c=It,d=Dt);const p=c.float32Array,m=c.uint32Array,f=c.uint16Array,g=d.float32Array,y=d.uint32Array,x=d.uint16Array,b=2*t,_=tt(2*e,f),w=tt(b,x);let v=!1;if(w&&_)v=u?r(st(t,y),it(2*t,x),st(e,m),it(2*e,f),l,o+t/8,a,n+e/8):r(st(e,m),it(2*e,f),st(t,y),it(2*t,x),a,n+e/8,l,o+t/8);else if(w){const h=Lt.getPrimitive();Ye(t,g,h),h.applyMatrix4(s);const c=rt(e),d=nt(e,m);Ye(c,p,Ft),Ye(d,p,Ot);const f=h.intersectsBox(Ft),y=h.intersectsBox(Ot);v=f&&Ut(t,c,i,s,r,o,n,l,a+1,h,!u)||y&&Ut(t,d,i,s,r,o,n,l,a+1,h,!u),Lt.releasePrimitive(h)}else{const c=rt(t),d=nt(t,y);Ye(c,g,Vt),Ye(d,g,zt);const f=h.intersectsBox(Vt),x=h.intersectsBox(zt);if(f&&x)v=Ut(e,c,s,i,r,n,o,a,l+1,h,u)||Ut(e,d,s,i,r,n,o,a,l+1,h,u);else if(f)if(_)v=Ut(e,c,s,i,r,n,o,a,l+1,h,u);else{const t=Lt.getPrimitive();t.copy(Vt).applyMatrix4(s);const h=rt(e),d=nt(e,m);Ye(h,p,Ft),Ye(d,p,Ot);const f=t.intersectsBox(Ft),g=t.intersectsBox(Ot);v=f&&Ut(c,h,i,s,r,o,n,l,a+1,t,!u)||g&&Ut(c,d,i,s,r,o,n,l,a+1,t,!u),Lt.releasePrimitive(t)}else if(x)if(_)v=Ut(e,d,s,i,r,n,o,a,l+1,h,u);else{const t=Lt.getPrimitive();t.copy(zt).applyMatrix4(s);const h=rt(e),c=nt(e,m);Ye(h,p,Ft),Ye(c,p,Ot);const f=t.intersectsBox(Ft),g=t.intersectsBox(Ot);v=f&&Ut(d,h,i,s,r,o,n,l,a+1,t,!u)||g&&Ut(d,c,i,s,r,o,n,l,a+1,t,!u),Lt.releasePrimitive(t)}}return v}const Gt=new i.Box3,jt=new Float32Array(6);class $t{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(e){Tt(this,e={...Xe,...e})}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(e,t,s,i){let r=1/0,n=1/0,o=1/0,a=-1/0,l=-1/0,h=-1/0;for(let s=e,i=e+t;s<i;s++){this.writePrimitiveBounds(s,jt,0);const[e,t,i,u,c,d]=jt;e<r&&(r=e),u>a&&(a=u),t<n&&(n=t),c>l&&(l=c),i<o&&(o=i),d>h&&(h=d)}return s[i+0]=r,s[i+1]=n,s[i+2]=o,s[i+3]=a,s[i+4]=l,s[i+5]=h,s}computePrimitiveBounds(e,t,s){const i=s.offset||0;for(let r=e,n=e+t;r<n;r++){this.writePrimitiveBounds(r,jt,0);const[e,t,n,o,a,l]=jt,h=(e+o)/2,u=(t+a)/2,c=(n+l)/2,d=(o-e)/2,p=(a-t)/2,m=(l-n)/2,f=6*(r-i);s[f+0]=h,s[f+1]=d+(Math.abs(h)+d)*He,s[f+2]=u,s[f+3]=p+(Math.abs(u)+p)*He,s[f+4]=c,s[f+5]=m+(Math.abs(c)+m)*He}return s}shiftPrimitiveOffsets(e){const t=this._indirectBuffer;if(t)for(let s=0,i=t.length;s<i;s++)t[s]+=e;else{const t=this._roots;for(let s=0;s<t.length;s++){const i=t[s],r=new Uint32Array(i),n=new Uint16Array(i),o=i.byteLength/We;for(let t=0;t<o;t++){const s=8*t;tt(2*s,n)&&(r[s+6]+=e)}}}}traverse(e,t=0){const s=this._roots[t],i=new Uint32Array(s),r=new Uint16Array(s);!function t(n,o=0){const a=2*n,l=tt(a,r);if(l){const t=i[n+6],h=r[a+14];e(o,l,new Float32Array(s,4*n,6),t,h)}else{const r=rt(n),a=nt(n,i),h=ot(n,i);e(o,l,new Float32Array(s,4*n,6),h)||(t(r,o+1),t(a,o+1))}}(0)}refit(){const e=this._roots;for(let t=0,s=e.length;t<s;t++){const s=e[t],i=new Uint32Array(s),r=new Uint16Array(s),n=new Float32Array(s);for(let e=s.byteLength/We-1;e>=0;e--){const t=8*e,s=2*t;if(tt(s,r)){const e=st(t,i),o=it(s,r);this.writePrimitiveRangeBounds(e,o,jt,0),n.set(jt,t)}else{const e=rt(t),s=nt(t,i);for(let i=0;i<3;i++){const r=n[e+i],o=n[e+i+3],a=n[s+i],l=n[s+i+3];n[t+i]=r<a?r:a,n[t+i+3]=o>l?o:l}}}}}getBoundingBox(e){e.makeEmpty();return this._roots.forEach(t=>{Ye(0,new Float32Array(t),Gt),e.union(Gt)}),e}shapecast(e){let{boundsTraverseOrder:t,intersectsBounds:s,intersectsRange:i,intersectsPrimitive:r,scratchPrimitive:n,iterate:o}=e;if(i&&r){const e=i;i=(t,s,i,a,l)=>!!e(t,s,i,a,l)||o(t,s,this,r,i,a,n)}else i||(i=r?(e,t,s,i)=>o(e,t,this,r,s,i,n):(e,t,s)=>s);let a=!1,l=0;const h=this._roots;for(let e=0,r=h.length;e<r;e++){const r=h[e];if(a=Pt(this,e,s,i,t,l),a)break;l+=r.byteLength/We}return a}bvhcast(e,t,s){let{intersectsRanges:r}=s;return function(e,t,s,r){if(kt)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");kt=!0;const n=e._roots,o=t._roots;let a,l=0,h=0;const u=(new i.Matrix4).copy(s).invert();for(let e=0,t=n.length;e<t;e++){It.setBuffer(n[e]),h=0;const t=Lt.getPrimitive();Ye(at(0),It.float32Array,t),t.applyMatrix4(u);for(let e=0,i=o.length;e<i&&(Dt.setBuffer(o[e]),a=Ut(0,0,s,u,r,l,h,0,0,t),Dt.clearBuffer(),h+=o[e].byteLength/We,!a);e++);if(Lt.releasePrimitive(t),It.clearBuffer(),l+=n[e].byteLength/We,a)break}return kt=!1,a}(this,e,t,r)}}function Wt(e){return e.index?e.index.count:e.attributes.position.count}function Ht(e){return Wt(e)/3}function qt(e,t){if(!e.index){const s=e.attributes.position.count,r=function(e,t=ArrayBuffer){return e>65535?new Uint32Array(new t(4*e)):new Uint16Array(new t(2*e))}(s,t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer);e.setIndex(new i.BufferAttribute(r,1));for(let e=0;e<s;e++)r[e]=e}}function Xt(e,t,s){const i=function(e,t,s){const i=Wt(e)/s,r=t||e.drawRange,n=r.start/s,o=(r.start+r.count)/s,a=Math.max(0,n),l=Math.min(i,o)-a;return{offset:Math.floor(a),count:Math.floor(l)}}(e,t,s),r=function(e,t){return e.groups.map(e=>({offset:e.start/t,count:e.count/t}))}(e,s);if(!r.length)return[i];const n=[],o=i.offset,a=i.offset+i.count,l=Wt(e)/s,h=[];for(const e of r){const{offset:t,count:s}=e,i=t,r=t+(isFinite(s)?s:l-t);i<a&&r>o&&(h.push({pos:Math.max(o,i),isStart:!0}),h.push({pos:Math.min(a,r),isStart:!1}))}h.sort((e,t)=>e.pos!==t.pos?e.pos-t.pos:"end"===e.type?-1:1);let u=0,c=null;for(const e of h){const t=e.pos;0!==u&&t!==c&&n.push({offset:c,count:t-c}),u+=e.isStart?1:-1,c=t}return n}class Yt extends $t{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(e){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(e){}constructor(e,t={}){if(!e.isBufferGeometry)throw new Error("BVH: Only BufferGeometries are supported.");if(e.index&&e.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.");if(t.useSharedArrayBuffer&&"undefined"==typeof SharedArrayBuffer)throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=e,this.resolvePrimitiveIndex=t.indirect?e=>this._indirectBuffer[e]:e=>e,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,(t={...Xe,...t})[qe]||this.init(t)}init(e){const{geometry:t,primitiveStride:s}=this;if(e.indirect){const i=function(e,t){const s=e[e.length-1],i=s.offset+s.count>65536,r=e.reduce((e,t)=>e+t.count,0),n=i?4:2,o=t?new SharedArrayBuffer(r*n):new ArrayBuffer(r*n),a=i?new Uint32Array(o):new Uint16Array(o);let l=0;for(let t=0;t<e.length;t++){const{offset:s,count:i}=e[t];for(let e=0;e<i;e++)a[l+e]=s+e;l+=i}return a}(Xt(t,e.range,s),e.useSharedArrayBuffer);this._indirectBuffer=i}else qt(t,e);super.init(e),!t.boundingBox&&e.setBoundingBox&&(t.boundingBox=this.getBoundingBox(new i.Box3))}getRootRanges(e){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:Xt(this.geometry,e,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class Zt{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let s=1/0,i=-1/0;for(let r=0,n=e.length;r<n;r++){const n=e[r][t];s=n<s?n:s,i=n>i?n:i}this.min=s,this.max=i}setFromPoints(e,t){let s=1/0,i=-1/0;for(let r=0,n=t.length;r<n;r++){const n=t[r],o=e.dot(n);s=o<s?o:s,i=o>i?o:i}this.min=s,this.max=i}isSeparated(e){return this.min>e.max||e.min>this.max}}Zt.prototype.setFromBox=function(){const e=new i.Vector3;return function(t,s){const i=s.min,r=s.max;let n=1/0,o=-1/0;for(let s=0;s<=1;s++)for(let a=0;a<=1;a++)for(let l=0;l<=1;l++){e.x=i.x*s+r.x*(1-s),e.y=i.y*a+r.y*(1-a),e.z=i.z*l+r.z*(1-l);const h=t.dot(e);n=Math.min(h,n),o=Math.max(h,o)}this.min=n,this.max=o}}();const Qt=function(){const e=new i.Vector3,t=new i.Vector3,s=new i.Vector3;return function(i,r,n){const o=i.start,a=e,l=r.start,h=t;s.subVectors(o,l),e.subVectors(i.end,i.start),t.subVectors(r.end,r.start);const u=s.dot(h),c=h.dot(a),d=h.dot(h),p=s.dot(a),m=a.dot(a)*d-c*c;let f,g;f=0!==m?(u*c-p*d)/m:0,g=(u+f*c)/d,n.x=f,n.y=g}}(),Kt=function(){const e=new i.Vector2,t=new i.Vector3,s=new i.Vector3;return function(i,r,n,o){Qt(i,r,e);let a=e.x,l=e.y;if(a>=0&&a<=1&&l>=0&&l<=1)return i.at(a,n),void r.at(l,o);if(a>=0&&a<=1)return l<0?r.at(0,o):r.at(1,o),void i.closestPointToPoint(o,!0,n);if(l>=0&&l<=1)return a<0?i.at(0,n):i.at(1,n),void r.closestPointToPoint(n,!0,o);{let e,h;e=a<0?i.start:i.end,h=l<0?r.start:r.end;const u=t,c=s;return i.closestPointToPoint(h,!0,t),r.closestPointToPoint(e,!0,s),u.distanceToSquared(h)<=c.distanceToSquared(e)?(n.copy(u),void o.copy(h)):(n.copy(e),void o.copy(c))}}}(),Jt=function(){const e=new i.Vector3,t=new i.Vector3,s=new i.Plane,r=new i.Line3;return function(i,n){const{radius:o,center:a}=i,{a:l,b:h,c:u}=n;r.start=l,r.end=h;if(r.closestPointToPoint(a,!0,e).distanceTo(a)<=o)return!0;r.start=l,r.end=u;if(r.closestPointToPoint(a,!0,e).distanceTo(a)<=o)return!0;r.start=h,r.end=u;if(r.closestPointToPoint(a,!0,e).distanceTo(a)<=o)return!0;const c=n.getPlane(s);if(Math.abs(c.distanceToPoint(a))<=o){const e=c.projectPoint(a,t);if(n.containsPoint(e))return!0}return!1}}(),es=["x","y","z"],ts=1e-15;function ss(e){return Math.abs(e)<ts}class is extends i.Triangle{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new i.Vector3),this.satBounds=new Array(4).fill().map(()=>new Zt),this.points=[this.a,this.b,this.c],this.plane=new i.Plane,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new i.Line3,this.needsUpdate=!0}intersectsSphere(e){return Jt(e,this)}update(){const e=this.a,t=this.b,s=this.c,i=this.points,r=this.satAxes,n=this.satBounds,o=r[0],a=n[0];this.getNormal(o),a.setFromPoints(o,i);const l=r[1],h=n[1];l.subVectors(e,t),h.setFromPoints(l,i);const u=r[2],c=n[2];u.subVectors(t,s),c.setFromPoints(u,i);const d=r[3],p=n[3];d.subVectors(s,e),p.setFromPoints(d,i);const m=l.length(),f=u.length(),g=d.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,m<ts?f<ts||g<ts?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(s)):f<ts?g<ts?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):g<ts&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(s),this.degenerateSegment.end.copy(t)),this.plane.setFromNormalAndCoplanarPoint(o,e),this.needsUpdate=!1}}is.prototype.closestPointToSegment=function(){const e=new i.Vector3,t=new i.Vector3,s=new i.Line3;return function(i,r=null,n=null){const{start:o,end:a}=i,l=this.points;let h,u=1/0;for(let o=0;o<3;o++){const a=(o+1)%3;s.start.copy(l[o]),s.end.copy(l[a]),Kt(s,i,e,t),h=e.distanceToSquared(t),h<u&&(u=h,r&&r.copy(e),n&&n.copy(t))}return this.closestPointToPoint(o,e),h=o.distanceToSquared(e),h<u&&(u=h,r&&r.copy(e),n&&n.copy(o)),this.closestPointToPoint(a,e),h=a.distanceToSquared(e),h<u&&(u=h,r&&r.copy(e),n&&n.copy(a)),Math.sqrt(u)}}(),is.prototype.intersectsTriangle=function(){const e=new is,t=new Zt,s=new Zt,r=new i.Vector3,n=new i.Vector3,o=new i.Vector3,a=new i.Vector3,l=new i.Line3,h=new i.Line3,u=new i.Vector3,c=new i.Vector2,d=new i.Vector2;function p(e,i,n,o){const l=r;e.isDegenerateIntoPoint||e.isDegenerateIntoSegment?l.copy(i.plane.normal):l.copy(e.plane.normal);const h=e.satBounds,u=e.satAxes;for(let r=1;r<4;r++){const n=h[r],o=u[r];if(t.setFromPoints(o,i.points),n.isSeparated(t))return!1;if(a.copy(l).cross(o),t.setFromPoints(a,e.points),s.setFromPoints(a,i.points),t.isSeparated(s))return!1}const c=i.satBounds,d=i.satAxes;for(let r=1;r<4;r++){const n=c[r],o=d[r];if(t.setFromPoints(o,e.points),n.isSeparated(t))return!1;if(a.crossVectors(l,o),t.setFromPoints(a,e.points),s.setFromPoints(a,i.points),t.isSeparated(s))return!1}return n&&(o||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),n.start.set(0,0,0),n.end.set(0,0,0)),!0}function m(e,t,s,i,r,n,o,a,l,h,u){let c=o/(o-a);h.x=i+(r-i)*c,u.start.subVectors(t,e).multiplyScalar(c).add(e),c=o/(o-l),h.y=i+(n-i)*c,u.end.subVectors(s,e).multiplyScalar(c).add(e)}function f(e,t,s,i,r,n,o,a,l,h,u){if(r>0)m(e.c,e.a,e.b,i,t,s,l,o,a,h,u);else if(n>0)m(e.b,e.a,e.c,s,t,i,a,o,l,h,u);else if(a*l>0||0!=o)m(e.a,e.b,e.c,t,s,i,o,a,l,h,u);else if(0!=a)m(e.b,e.a,e.c,s,t,i,a,o,l,h,u);else{if(0==l)return!0;m(e.c,e.a,e.b,i,t,s,l,o,a,h,u)}return!1}function g(e,t,s,i){const n=t.degenerateSegment,o=e.plane.distanceToPoint(n.start),a=e.plane.distanceToPoint(n.end);return ss(o)?ss(a)?p(e,t,s,i):(s&&(s.start.copy(n.start),s.end.copy(n.start)),e.containsPoint(n.start)):ss(a)?(s&&(s.start.copy(n.end),s.end.copy(n.end)),e.containsPoint(n.end)):null!=e.plane.intersectLine(n,r)&&(s&&(s.start.copy(r),s.end.copy(r)),e.containsPoint(r))}function y(e,t,s){const i=t.a;return!(!ss(e.plane.distanceToPoint(i))||!e.containsPoint(i))&&(s&&(s.start.copy(i),s.end.copy(i)),!0)}function x(e,t,s){const i=e.degenerateSegment,n=t.a;return i.closestPointToPoint(n,!0,r),n.distanceToSquared(r)<1e-30&&(s&&(s.start.copy(n),s.end.copy(n)),!0)}return function(t,s=null,i=!1){this.needsUpdate&&this.update(),t.isExtendedTriangle?t.needsUpdate&&t.update():(e.copy(t),e.update(),t=e);const a=function(e,t,s,i){if(e.isDegenerateIntoSegment){if(t.isDegenerateIntoSegment){const i=e.degenerateSegment,a=t.degenerateSegment,l=n,h=o;i.delta(l),a.delta(h);const u=r.subVectors(a.start,i.start),c=l.x*h.y-l.y*h.x;if(ss(c))return!1;const d=(u.x*h.y-u.y*h.x)/c,p=-(l.x*u.y-l.y*u.x)/c;return!(d<0||d>1||p<0||p>1)&&(!!ss(i.start.z+l.z*d-(a.start.z+h.z*p))&&(s&&(s.start.copy(i.start).addScaledVector(l,d),s.end.copy(i.start).addScaledVector(l,d)),!0))}return t.isDegenerateIntoPoint?x(e,t,s):g(t,e,s,i)}return e.isDegenerateIntoPoint?t.isDegenerateIntoPoint?t.a.distanceToSquared(e.a)<1e-30&&(s&&(s.start.copy(e.a),s.end.copy(e.a)),!0):t.isDegenerateIntoSegment?x(t,e,s):y(t,e,s):t.isDegenerateIntoPoint?y(e,t,s):t.isDegenerateIntoSegment?g(e,t,s,i):void 0}(this,t,s,i);if(void 0!==a)return a;const m=this.plane,b=t.plane;let _=b.distanceToPoint(this.a),w=b.distanceToPoint(this.b),v=b.distanceToPoint(this.c);ss(_)&&(_=0),ss(w)&&(w=0),ss(v)&&(v=0);const T=_*w,S=_*v;if(T>0&&S>0)return!1;let M=m.distanceToPoint(t.a),A=m.distanceToPoint(t.b),N=m.distanceToPoint(t.c);ss(M)&&(M=0),ss(A)&&(A=0),ss(N)&&(N=0);const E=M*A,C=M*N;if(E>0&&C>0)return!1;n.copy(m.normal),o.copy(b.normal);const R=n.cross(o);let P=0,B=Math.abs(R.x);const I=Math.abs(R.y);I>B&&(B=I,P=1);Math.abs(R.z)>B&&(P=2);const D=es[P],L=this.a[D],F=this.b[D],O=this.c[D],V=t.a[D],z=t.b[D],k=t.c[D];if(f(this,L,F,O,T,S,_,w,v,c,l))return p(this,t,s,i);if(f(t,V,z,k,E,C,M,A,N,d,h))return p(this,t,s,i);if(c.y<c.x){const e=c.y;c.y=c.x,c.x=e,u.copy(l.start),l.start.copy(l.end),l.end.copy(u)}if(d.y<d.x){const e=d.y;d.y=d.x,d.x=e,u.copy(h.start),h.start.copy(h.end),h.end.copy(u)}return!(c.y<d.x||d.y<c.x)&&(s&&(d.x>c.x?s.start.copy(h.start):s.start.copy(l.start),d.y<c.y?s.end.copy(h.end):s.end.copy(l.end)),!0)}}(),is.prototype.distanceToPoint=function(){const e=new i.Vector3;return function(t){return this.closestPointToPoint(t,e),t.distanceTo(e)}}(),is.prototype.distanceToTriangle=function(){const e=new i.Vector3,t=new i.Vector3,s=["a","b","c"],r=new i.Line3,n=new i.Line3;return function(i,o=null,a=null){const l=o||a?r:null;if(this.intersectsTriangle(i,l))return(o||a)&&(o&&l.getCenter(o),a&&l.getCenter(a)),0;let h=1/0;for(let t=0;t<3;t++){let r;const n=s[t],l=i[n];this.closestPointToPoint(l,e),r=l.distanceToSquared(e),r<h&&(h=r,o&&o.copy(e),a&&a.copy(l));const u=this[n];i.closestPointToPoint(u,e),r=u.distanceToSquared(e),r<h&&(h=r,o&&o.copy(u),a&&a.copy(e))}for(let l=0;l<3;l++){const u=s[l],c=s[(l+1)%3];r.set(this[u],this[c]);for(let l=0;l<3;l++){const u=s[l],c=s[(l+1)%3];n.set(i[u],i[c]),Kt(r,n,e,t);const d=e.distanceToSquared(t);d<h&&(h=d,o&&o.copy(e),a&&a.copy(t))}}return Math.sqrt(h)}}();class rs{constructor(e,t,s){this.isOrientedBox=!0,this.min=new i.Vector3,this.max=new i.Vector3,this.matrix=new i.Matrix4,this.invMatrix=new i.Matrix4,this.points=new Array(8).fill().map(()=>new i.Vector3),this.satAxes=new Array(3).fill().map(()=>new i.Vector3),this.satBounds=new Array(3).fill().map(()=>new Zt),this.alignedSatBounds=new Array(3).fill().map(()=>new Zt),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),s&&this.matrix.copy(s)}set(e,t,s){this.min.copy(e),this.max.copy(t),this.matrix.copy(s),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}rs.prototype.update=function(){return function(){const e=this.matrix,t=this.min,s=this.max,i=this.points;for(let r=0;r<=1;r++)for(let n=0;n<=1;n++)for(let o=0;o<=1;o++){const a=i[1*r|2*n|4*o];a.x=r?s.x:t.x,a.y=n?s.y:t.y,a.z=o?s.z:t.z,a.applyMatrix4(e)}const r=this.satBounds,n=this.satAxes,o=i[0];for(let e=0;e<3;e++){const t=n[e],s=r[e],a=i[1<<e];t.subVectors(o,a),s.setFromPoints(t,i)}const a=this.alignedSatBounds;a[0].setFromPointsField(i,"x"),a[1].setFromPointsField(i,"y"),a[2].setFromPointsField(i,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}}(),rs.prototype.intersectsBox=function(){const e=new Zt;return function(t){this.needsUpdate&&this.update();const s=t.min,i=t.max,r=this.satBounds,n=this.satAxes,o=this.alignedSatBounds;if(e.min=s.x,e.max=i.x,o[0].isSeparated(e))return!1;if(e.min=s.y,e.max=i.y,o[1].isSeparated(e))return!1;if(e.min=s.z,e.max=i.z,o[2].isSeparated(e))return!1;for(let s=0;s<3;s++){const i=n[s],o=r[s];if(e.setFromBox(i,t),o.isSeparated(e))return!1}return!0}}(),rs.prototype.intersectsTriangle=function(){const e=new is,t=new Array(3),s=new Zt,r=new Zt,n=new i.Vector3;return function(i){this.needsUpdate&&this.update(),i.isExtendedTriangle?i.needsUpdate&&i.update():(e.copy(i),e.update(),i=e);const o=this.satBounds,a=this.satAxes;t[0]=i.a,t[1]=i.b,t[2]=i.c;for(let e=0;e<3;e++){const i=o[e],r=a[e];if(s.setFromPoints(r,t),i.isSeparated(s))return!1}const l=i.satBounds,h=i.satAxes,u=this.points;for(let e=0;e<3;e++){const t=l[e],i=h[e];if(s.setFromPoints(i,u),t.isSeparated(s))return!1}for(let e=0;e<3;e++){const i=a[e];for(let e=0;e<4;e++){const o=h[e];if(n.crossVectors(i,o),s.setFromPoints(n,t),r.setFromPoints(n,u),s.isSeparated(r))return!1}}return!0}}(),rs.prototype.closestPointToPoint=function(){return function(e,t){return this.needsUpdate&&this.update(),t.copy(e).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),t}}(),rs.prototype.distanceToPoint=function(){const e=new i.Vector3;return function(t){return this.closestPointToPoint(t,e),t.distanceTo(e)}}(),rs.prototype.distanceToBox=function(){const e=["x","y","z"],t=new Array(12).fill().map(()=>new i.Line3),s=new Array(12).fill().map(()=>new i.Line3),r=new i.Vector3,n=new i.Vector3;return function(i,o=0,a=null,l=null){if(this.needsUpdate&&this.update(),this.intersectsBox(i))return(a||l)&&(i.getCenter(n),this.closestPointToPoint(n,r),i.closestPointToPoint(r,n),a&&a.copy(r),l&&l.copy(n)),0;const h=o*o,u=i.min,c=i.max,d=this.points;let p=1/0;for(let e=0;e<8;e++){const t=d[e];n.copy(t).clamp(u,c);const s=t.distanceToSquared(n);if(s<p&&(p=s,a&&a.copy(t),l&&l.copy(n),s<h))return Math.sqrt(s)}let m=0;for(let i=0;i<3;i++)for(let r=0;r<=1;r++)for(let n=0;n<=1;n++){const o=(i+1)%3,a=(i+2)%3,l=1<<i|r<<o|n<<a,h=d[r<<o|n<<a],p=d[l];t[m].set(h,p);const f=e[i],g=e[o],y=e[a],x=s[m],b=x.start,_=x.end;b[f]=u[f],b[g]=r?u[g]:c[g],b[y]=n?u[y]:c[g],_[f]=c[f],_[g]=r?u[g]:c[g],_[y]=n?u[y]:c[g],m++}for(let e=0;e<=1;e++)for(let t=0;t<=1;t++)for(let s=0;s<=1;s++){n.x=e?c.x:u.x,n.y=t?c.y:u.y,n.z=s?c.z:u.z,this.closestPointToPoint(n,r);const i=n.distanceToSquared(r);if(i<p&&(p=i,a&&a.copy(r),l&&l.copy(n),i<h))return Math.sqrt(i)}for(let e=0;e<12;e++){const i=t[e];for(let e=0;e<12;e++){const t=s[e];Kt(i,t,r,n);const o=r.distanceToSquared(n);if(o<p&&(p=o,a&&a.copy(r),l&&l.copy(n),o<h))return Math.sqrt(o)}}return Math.sqrt(p)}}();class ns extends St{constructor(){super(()=>new is)}}const os=new ns,as=new i.Vector3,ls=new i.Vector3;const hs=parseInt(i.REVISION)>=169,us=parseInt(i.REVISION)<=161,cs=new i.Vector3,ds=new i.Vector3,ps=new i.Vector3,ms=new i.Vector2,fs=new i.Vector2,gs=new i.Vector2,ys=new i.Vector3,xs=new i.Vector3,bs=new i.Vector3,_s=new i.Vector3;function ws(e,t,s,r,n,o,a,l,h,u,c){cs.fromBufferAttribute(t,o),ds.fromBufferAttribute(t,a),ps.fromBufferAttribute(t,l);const d=function(e,t,s,r,n,o,a,l){let h;if(h=o===i.BackSide?e.intersectTriangle(r,s,t,!0,n):e.intersectTriangle(t,s,r,o!==i.DoubleSide,n),null===h)return null;const u=e.origin.distanceTo(n);return u<a||u>l?null:{distance:u,point:n.clone()}}(e,cs,ds,ps,_s,h,u,c);if(d){if(r){ms.fromBufferAttribute(r,o),fs.fromBufferAttribute(r,a),gs.fromBufferAttribute(r,l),d.uv=new i.Vector2;const e=i.Triangle.getInterpolation(_s,cs,ds,ps,ms,fs,gs,d.uv);hs||(d.uv=e)}if(n){ms.fromBufferAttribute(n,o),fs.fromBufferAttribute(n,a),gs.fromBufferAttribute(n,l),d.uv1=new i.Vector2;const e=i.Triangle.getInterpolation(_s,cs,ds,ps,ms,fs,gs,d.uv1);hs||(d.uv1=e),us&&(d.uv2=d.uv1)}if(s){ys.fromBufferAttribute(s,o),xs.fromBufferAttribute(s,a),bs.fromBufferAttribute(s,l),d.normal=new i.Vector3;const t=i.Triangle.getInterpolation(_s,cs,ds,ps,ys,xs,bs,d.normal);d.normal.dot(e.direction)>0&&d.normal.multiplyScalar(-1),hs||(d.normal=t)}const t={a:o,b:a,c:l,normal:new i.Vector3,materialIndex:0};if(i.Triangle.getNormal(cs,ds,ps,t.normal),d.face=t,d.faceIndex=o,hs){const e=new i.Vector3;i.Triangle.getBarycoord(_s,cs,ds,ps,e),d.barycoord=e}}return d}function vs(e){return e&&e.isMaterial?e.side:e}function Ts(e,t,s,i,r,n,o){const a=3*i;let l=a+0,h=a+1,u=a+2;const{index:c,groups:d}=e;e.index&&(l=c.getX(l),h=c.getX(h),u=c.getX(u));const{position:p,normal:m,uv:f,uv1:g}=e.attributes;if(Array.isArray(t)){const e=3*i;for(let a=0,c=d.length;a<c;a++){const{start:c,count:y,materialIndex:x}=d[a];if(e>=c&&e<c+y){const e=ws(s,p,m,f,g,l,h,u,vs(t[x]),n,o);if(e){if(e.faceIndex=i,e.face.materialIndex=x,!r)return e;r.push(e)}}}}else{const e=ws(s,p,m,f,g,l,h,u,vs(t),n,o);if(e){if(e.faceIndex=i,e.face.materialIndex=0,!r)return e;r.push(e)}}return null}function Ss(e,t,s,i){const r=e.a,n=e.b,o=e.c;let a=t,l=t+1,h=t+2;s&&(a=s.getX(a),l=s.getX(l),h=s.getX(h)),r.x=i.getX(a),r.y=i.getY(a),r.z=i.getZ(a),n.x=i.getX(l),n.y=i.getY(l),n.z=i.getZ(l),o.x=i.getX(h),o.y=i.getY(h),o.z=i.getZ(h)}function Ms(e,t,s,i,r,n,o){const{geometry:a}=s,{index:l}=a,h=a.attributes.position;for(let s=e,a=t+e;s<a;s++){let e;if(e=s,Ss(o,3*e,l,h),o.needsUpdate=!0,i(o,e,r,n))return!0}return!1}function As(e,t=null){t&&Array.isArray(t)&&(t=new Set(t));const s=e.geometry,i=s.index?s.index.array:null,r=s.attributes.position;let n,o,a,l,h=0;const u=e._roots;for(let e=0,t=u.length;e<t;e++)n=u[e],o=new Uint32Array(n),a=new Uint16Array(n),l=new Float32Array(n),c(0,h),h+=n.byteLength;function c(e,s,n=!1){const h=2*e;if(tt(h,a)){const t=st(e,o);let s=1/0,n=1/0,u=1/0,c=-1/0,d=-1/0,p=-1/0;for(let e=3*t,o=3*(t+it(h,a));e<o;e++){let t=i[e];const o=r.getX(t),a=r.getY(t),l=r.getZ(t);o<s&&(s=o),o>c&&(c=o),a<n&&(n=a),a>d&&(d=a),l<u&&(u=l),l>p&&(p=l)}return(l[e+0]!==s||l[e+1]!==n||l[e+2]!==u||l[e+3]!==c||l[e+4]!==d||l[e+5]!==p)&&(l[e+0]=s,l[e+1]=n,l[e+2]=u,l[e+3]=c,l[e+4]=d,l[e+5]=p,!0)}{const i=rt(e),r=nt(e,o);let a=n,h=!1,u=!1;if(t){if(!a){const e=i/8+s/We,n=r/8+s/We;h=t.has(e),u=t.has(n),a=!h&&!u}}else h=!0,u=!0;const d=a||u;let p=!1;(a||h)&&(p=c(i,s,a));let m=!1;d&&(m=c(r,s,a));const f=p||m;if(f)for(let t=0;t<3;t++){const s=i+t,n=r+t,o=l[s],a=l[s+3],h=l[n],u=l[n+3];l[e+t]=o<h?o:h,l[e+t+3]=a>u?a:u}return f}}}function Ns(e,t,s,i,r){let n,o,a,l,h,u;const c=1/s.direction.x,d=1/s.direction.y,p=1/s.direction.z,m=s.origin.x,f=s.origin.y,g=s.origin.z;let y=t[e],x=t[e+3],b=t[e+1],_=t[e+3+1],w=t[e+2],v=t[e+3+2];return c>=0?(n=(y-m)*c,o=(x-m)*c):(n=(x-m)*c,o=(y-m)*c),d>=0?(a=(b-f)*d,l=(_-f)*d):(a=(_-f)*d,l=(b-f)*d),!(n>l||a>o)&&((a>n||isNaN(n))&&(n=a),(l<o||isNaN(o))&&(o=l),p>=0?(h=(w-g)*p,u=(v-g)*p):(h=(v-g)*p,u=(w-g)*p),!(n>u||h>o)&&((h>n||n!=n)&&(n=h),(u<o||o!=o)&&(o=u),n<=r&&o>=i))}function Es(e,t,s,i,r,n,o){const{geometry:a}=s,{index:l}=a,h=a.attributes.position;for(let a=e,u=t+e;a<u;a++){let e;if(e=s.resolveTriangleIndex(a),Ss(o,3*e,l,h),o.needsUpdate=!0,i(o,e,r,n))return!0}return!1}function Cs(e,t,s,i,r,n,o){At.setBuffer(e._roots[t]),Rs(0,e,s,i,r,n,o),At.clearBuffer()}function Rs(e,t,s,i,r,n,o){const{float32Array:a,uint16Array:l,uint32Array:h}=At,u=2*e;if(tt(u,l)){!function(e,t,s,i,r,n,o,a){const{geometry:l,_indirectBuffer:h}=e;for(let e=i,h=i+r;e<h;e++)Ts(l,t,s,e,n,o,a)}(t,s,i,st(e,h),it(u,l),r,n,o)}else{const l=rt(e);Ns(l,a,i,n,o)&&Rs(l,t,s,i,r,n,o);const u=nt(e,h);Ns(u,a,i,n,o)&&Rs(u,t,s,i,r,n,o)}}const Ps=["x","y","z"];function Bs(e,t,s,i,r,n){At.setBuffer(e._roots[t]);const o=Is(0,e,s,i,r,n);return At.clearBuffer(),o}function Is(e,t,s,i,r,n){const{float32Array:o,uint16Array:a,uint32Array:l}=At;let h=2*e;if(tt(h,a)){return function(e,t,s,i,r,n,o){const{geometry:a,_indirectBuffer:l}=e;let h=1/0,u=null;for(let e=i,l=i+r;e<l;e++){let i;i=Ts(a,t,s,e,null,n,o),i&&i.distance<h&&(u=i,h=i.distance)}return u}(t,s,i,st(e,l),it(h,a),r,n)}{const a=ot(e,l),h=Ps[a],u=i.direction[h]>=0;let c,d;u?(c=rt(e),d=nt(e,l)):(c=nt(e,l),d=rt(e));const p=Ns(c,o,i,r,n)?Is(c,t,s,i,r,n):null;if(p){const e=p.point[h];if(u?e<=o[d+a]:e>=o[d+a+3])return p}const m=Ns(d,o,i,r,n)?Is(d,t,s,i,r,n):null;return p&&m?p.distance<=m.distance?p:m:p||m||null}}const Ds=new i.Box3,Ls=new is,Fs=new is,Os=new i.Matrix4,Vs=new rs,zs=new rs;function ks(e,t,s,i){At.setBuffer(e._roots[t]);const r=Us(0,e,s,i);return At.clearBuffer(),r}function Us(e,t,s,i,r=null){const{float32Array:n,uint16Array:o,uint32Array:a}=At;let l=2*e;null===r&&(s.boundingBox||s.computeBoundingBox(),Vs.set(s.boundingBox.min,s.boundingBox.max,i),r=Vs);if(!tt(l,o)){const o=rt(e),l=nt(e,a);Ye(o,n,Ds);if(r.intersectsBox(Ds)&&Us(o,t,s,i,r))return!0;Ye(l,n,Ds);return!!(r.intersectsBox(Ds)&&Us(l,t,s,i,r))}{const r=t.geometry,h=r.index,u=r.attributes.position,c=s.index,d=s.attributes.position,p=st(e,a),m=it(l,o);if(Os.copy(i).invert(),s.boundsTree){Ye(e,n,zs),zs.matrix.copy(Os),zs.needsUpdate=!0;return s.boundsTree.shapecast({intersectsBounds:e=>zs.intersectsBox(e),intersectsTriangle:e=>{e.a.applyMatrix4(i),e.b.applyMatrix4(i),e.c.applyMatrix4(i),e.needsUpdate=!0;for(let t=3*p,s=3*(m+p);t<s;t+=3)if(Ss(Fs,t,h,u),Fs.needsUpdate=!0,e.intersectsTriangle(Fs))return!0;return!1}})}{const e=Ht(s);for(let t=3*p,s=3*(m+p);t<s;t+=3){Ss(Ls,t,h,u),Ls.a.applyMatrix4(Os),Ls.b.applyMatrix4(Os),Ls.c.applyMatrix4(Os),Ls.needsUpdate=!0;for(let t=0,s=3*e;t<s;t+=3)if(Ss(Fs,t,c,d),Fs.needsUpdate=!0,Ls.intersectsTriangle(Fs))return!0}}}}const Gs=new i.Matrix4,js=new rs,$s=new rs,Ws=new i.Vector3,Hs=new i.Vector3,qs=new i.Vector3,Xs=new i.Vector3;function Ys(e,t,s,i={},r={},n=0,o=1/0){t.boundingBox||t.computeBoundingBox(),js.set(t.boundingBox.min,t.boundingBox.max,s),js.needsUpdate=!0;const a=e.geometry,l=a.attributes.position,h=a.index,u=t.attributes.position,c=t.index,d=os.getPrimitive(),p=os.getPrimitive();let m=Ws,f=Hs,g=null,y=null;r&&(g=qs,y=Xs);let x=1/0,b=null,_=null;return Gs.copy(s).invert(),$s.matrix.copy(Gs),e.shapecast({boundsTraverseOrder:e=>js.distanceToBox(e),intersectsBounds:(e,t,s)=>s<x&&s<o&&(t&&($s.min.copy(e.min),$s.max.copy(e.max),$s.needsUpdate=!0),!0),intersectsRange:(e,i)=>{if(t.boundsTree){return t.boundsTree.shapecast({boundsTraverseOrder:e=>$s.distanceToBox(e),intersectsBounds:(e,t,s)=>s<x&&s<o,intersectsRange:(t,r)=>{for(let o=t,a=t+r;o<a;o++){Ss(p,3*o,c,u),p.a.applyMatrix4(s),p.b.applyMatrix4(s),p.c.applyMatrix4(s),p.needsUpdate=!0;for(let t=e,s=e+i;t<s;t++){Ss(d,3*t,h,l),d.needsUpdate=!0;const e=d.distanceToTriangle(p,m,g);if(e<x&&(f.copy(m),y&&y.copy(g),x=e,b=t,_=o),e<n)return!0}}}})}for(let r=0,o=Ht(t);r<o;r++){Ss(p,3*r,c,u),p.a.applyMatrix4(s),p.b.applyMatrix4(s),p.c.applyMatrix4(s),p.needsUpdate=!0;for(let t=e,s=e+i;t<s;t++){Ss(d,3*t,h,l),d.needsUpdate=!0;const e=d.distanceToTriangle(p,m,g);if(e<x&&(f.copy(m),y&&y.copy(g),x=e,b=t,_=r),e<n)return!0}}}}),os.releasePrimitive(d),os.releasePrimitive(p),x===1/0?null:(i.point?i.point.copy(f):i.point=f.clone(),i.distance=x,i.faceIndex=b,r&&(r.point?r.point.copy(y):r.point=y.clone(),r.point.applyMatrix4(Gs),f.applyMatrix4(Gs),r.distance=f.sub(r.point).length(),r.faceIndex=_),i)}function Zs(e,t=null){t&&Array.isArray(t)&&(t=new Set(t));const s=e.geometry,i=s.index?s.index.array:null,r=s.attributes.position;let n,o,a,l,h=0;const u=e._roots;for(let e=0,t=u.length;e<t;e++)n=u[e],o=new Uint32Array(n),a=new Uint16Array(n),l=new Float32Array(n),c(0,h),h+=n.byteLength;function c(s,n,h=!1){const u=2*s;if(tt(u,a)){const t=st(s,o);let n=1/0,h=1/0,c=1/0,d=-1/0,p=-1/0,m=-1/0;for(let s=t,o=t+it(u,a);s<o;s++){const t=3*e.resolveTriangleIndex(s);for(let e=0;e<3;e++){let s=t+e;s=i?i[s]:s;const o=r.getX(s),a=r.getY(s),l=r.getZ(s);o<n&&(n=o),o>d&&(d=o),a<h&&(h=a),a>p&&(p=a),l<c&&(c=l),l>m&&(m=l)}}return(l[s+0]!==n||l[s+1]!==h||l[s+2]!==c||l[s+3]!==d||l[s+4]!==p||l[s+5]!==m)&&(l[s+0]=n,l[s+1]=h,l[s+2]=c,l[s+3]=d,l[s+4]=p,l[s+5]=m,!0)}{const e=rt(s),i=nt(s,o);let r=h,a=!1,u=!1;if(t){if(!r){const s=e/8+n/We,o=i/8+n/We;a=t.has(s),u=t.has(o),r=!a&&!u}}else a=!0,u=!0;const d=r||u;let p=!1;(r||a)&&(p=c(e,n,r));let m=!1;d&&(m=c(i,n,r));const f=p||m;if(f)for(let t=0;t<3;t++){const r=e+t,n=i+t,o=l[r],a=l[r+3],h=l[n],u=l[n+3];l[s+t]=o<h?o:h,l[s+t+3]=a>u?a:u}return f}}}function Qs(e,t,s,i,r,n,o){At.setBuffer(e._roots[t]),Ks(0,e,s,i,r,n,o),At.clearBuffer()}function Ks(e,t,s,i,r,n,o){const{float32Array:a,uint16Array:l,uint32Array:h}=At,u=2*e;if(tt(u,l)){!function(e,t,s,i,r,n,o,a){const{geometry:l,_indirectBuffer:h}=e;for(let e=i,u=i+r;e<u;e++)Ts(l,t,s,h?h[e]:e,n,o,a)}(t,s,i,st(e,h),it(u,l),r,n,o)}else{const l=rt(e);Ns(l,a,i,n,o)&&Ks(l,t,s,i,r,n,o);const u=nt(e,h);Ns(u,a,i,n,o)&&Ks(u,t,s,i,r,n,o)}}const Js=["x","y","z"];function ei(e,t,s,i,r,n){At.setBuffer(e._roots[t]);const o=ti(0,e,s,i,r,n);return At.clearBuffer(),o}function ti(e,t,s,i,r,n){const{float32Array:o,uint16Array:a,uint32Array:l}=At;let h=2*e;if(tt(h,a)){return function(e,t,s,i,r,n,o){const{geometry:a,_indirectBuffer:l}=e;let h=1/0,u=null;for(let e=i,c=i+r;e<c;e++){let i;i=Ts(a,t,s,l?l[e]:e,null,n,o),i&&i.distance<h&&(u=i,h=i.distance)}return u}(t,s,i,st(e,l),it(h,a),r,n)}{const a=ot(e,l),h=Js[a],u=i.direction[h]>=0;let c,d;u?(c=rt(e),d=nt(e,l)):(c=nt(e,l),d=rt(e));const p=Ns(c,o,i,r,n)?ti(c,t,s,i,r,n):null;if(p){const e=p.point[h];if(u?e<=o[d+a]:e>=o[d+a+3])return p}const m=Ns(d,o,i,r,n)?ti(d,t,s,i,r,n):null;return p&&m?p.distance<=m.distance?p:m:p||m||null}}const si=new i.Box3,ii=new is,ri=new is,ni=new i.Matrix4,oi=new rs,ai=new rs;function li(e,t,s,i){At.setBuffer(e._roots[t]);const r=hi(0,e,s,i);return At.clearBuffer(),r}function hi(e,t,s,i,r=null){const{float32Array:n,uint16Array:o,uint32Array:a}=At;let l=2*e;null===r&&(s.boundingBox||s.computeBoundingBox(),oi.set(s.boundingBox.min,s.boundingBox.max,i),r=oi);if(!tt(l,o)){const o=rt(e),l=nt(e,a);Ye(o,n,si);if(r.intersectsBox(si)&&hi(o,t,s,i,r))return!0;Ye(l,n,si);return!!(r.intersectsBox(si)&&hi(l,t,s,i,r))}{const r=t.geometry,h=r.index,u=r.attributes.position,c=s.index,d=s.attributes.position,p=st(e,a),m=it(l,o);if(ni.copy(i).invert(),s.boundsTree){Ye(e,n,ai),ai.matrix.copy(ni),ai.needsUpdate=!0;return s.boundsTree.shapecast({intersectsBounds:e=>ai.intersectsBox(e),intersectsTriangle:e=>{e.a.applyMatrix4(i),e.b.applyMatrix4(i),e.c.applyMatrix4(i),e.needsUpdate=!0;for(let s=p,i=m+p;s<i;s++)if(Ss(ri,3*t.resolveTriangleIndex(s),h,u),ri.needsUpdate=!0,e.intersectsTriangle(ri))return!0;return!1}})}{const e=Ht(s);for(let s=p,i=m+p;s<i;s++){const i=t.resolveTriangleIndex(s);Ss(ii,3*i,h,u),ii.a.applyMatrix4(ni),ii.b.applyMatrix4(ni),ii.c.applyMatrix4(ni),ii.needsUpdate=!0;for(let t=0,s=3*e;t<s;t+=3)if(Ss(ri,t,c,d),ri.needsUpdate=!0,ii.intersectsTriangle(ri))return!0}}}}const ui=new i.Matrix4,ci=new rs,di=new rs,pi=new i.Vector3,mi=new i.Vector3,fi=new i.Vector3,gi=new i.Vector3;function yi(e,t,s,i={},r={},n=0,o=1/0){t.boundingBox||t.computeBoundingBox(),ci.set(t.boundingBox.min,t.boundingBox.max,s),ci.needsUpdate=!0;const a=e.geometry,l=a.attributes.position,h=a.index,u=t.attributes.position,c=t.index,d=os.getPrimitive(),p=os.getPrimitive();let m=pi,f=mi,g=null,y=null;r&&(g=fi,y=gi);let x=1/0,b=null,_=null;return ui.copy(s).invert(),di.matrix.copy(ui),e.shapecast({boundsTraverseOrder:e=>ci.distanceToBox(e),intersectsBounds:(e,t,s)=>s<x&&s<o&&(t&&(di.min.copy(e.min),di.max.copy(e.max),di.needsUpdate=!0),!0),intersectsRange:(i,r)=>{if(t.boundsTree){const a=t.boundsTree;return a.shapecast({boundsTraverseOrder:e=>di.distanceToBox(e),intersectsBounds:(e,t,s)=>s<x&&s<o,intersectsRange:(t,o)=>{for(let w=t,v=t+o;w<v;w++){const t=a.resolveTriangleIndex(w);Ss(p,3*t,c,u),p.a.applyMatrix4(s),p.b.applyMatrix4(s),p.c.applyMatrix4(s),p.needsUpdate=!0;for(let t=i,s=i+r;t<s;t++){const s=e.resolveTriangleIndex(t);Ss(d,3*s,h,l),d.needsUpdate=!0;const i=d.distanceToTriangle(p,m,g);if(i<x&&(f.copy(m),y&&y.copy(g),x=i,b=t,_=w),i<n)return!0}}}})}for(let o=0,a=Ht(t);o<a;o++){Ss(p,3*o,c,u),p.a.applyMatrix4(s),p.b.applyMatrix4(s),p.c.applyMatrix4(s),p.needsUpdate=!0;for(let t=i,s=i+r;t<s;t++){const s=e.resolveTriangleIndex(t);Ss(d,3*s,h,l),d.needsUpdate=!0;const i=d.distanceToTriangle(p,m,g);if(i<x&&(f.copy(m),y&&y.copy(g),x=i,b=t,_=o),i<n)return!0}}}}),os.releasePrimitive(d),os.releasePrimitive(p),x===1/0?null:(i.point?i.point.copy(f):i.point=f.clone(),i.distance=x,i.faceIndex=b,r&&(r.point?r.point.copy(y):r.point=y.clone(),r.point.applyMatrix4(ui),f.applyMatrix4(ui),r.distance=f.sub(r.point).length(),r.faceIndex=_),i)}function xi(e,t,s){return null===e?null:(e.point.applyMatrix4(t.matrixWorld),e.distance=e.point.distanceTo(s.ray.origin),e.object=t,e)}const bi=new rs,_i=new i.Ray,wi=new i.Vector3,vi=new i.Matrix4,Ti=new i.Vector3,Si=["getX","getY","getZ"];class Mi extends Yt{static serialize(e,t={}){t={cloneBuffers:!0,...t};const s=e.geometry,i=e._roots,r=e._indirectBuffer,n=s.getIndex(),o={version:1,roots:null,index:null,indirectBuffer:null};return t.cloneBuffers?(o.roots=i.map(e=>e.slice()),o.index=n?n.array.slice():null,o.indirectBuffer=r?r.slice():null):(o.roots=i,o.index=n?n.array:null,o.indirectBuffer=r),o}static deserialize(e,t,s={}){s={setIndex:!0,indirect:Boolean(e.indirectBuffer),...s};const{index:r,roots:n,indirectBuffer:o}=e;e.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),function(e){for(let t=0;t<e.length;t++){const s=e[t],i=new Uint32Array(s),r=new Uint16Array(s);for(let e=0,t=s.byteLength/We;e<t;e++){const t=8*e;tt(2*t,r)||(i[t+6]=i[t+6]/8-e)}}}(n));const a=new Mi(t,{...s,[qe]:!0});if(a._roots=n,a._indirectBuffer=o||null,s.setIndex){const s=t.getIndex();if(null===s){const s=new i.BufferAttribute(e.index,1,!1);t.setIndex(s)}else s.array!==r&&(s.array.set(r),s.needsUpdate=!0)}return a}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(e,t={}){t.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use maxLeafSize, instead.'),t={...t,maxLeafSize:t.maxLeafTris}),super(e,t)}shiftTriangleOffsets(e){return super.shiftPrimitiveOffsets(e)}writePrimitiveBounds(e,t,s){const i=this.geometry,r=this._indirectBuffer,n=i.attributes.position,o=i.index?i.index.array:null,a=3*(r?r[e]:e);let l=a+0,h=a+1,u=a+2;o&&(l=o[l],h=o[h],u=o[u]);for(let e=0;e<3;e++){const i=n[Si[e]](l),r=n[Si[e]](h),o=n[Si[e]](u);let a=i;r<a&&(a=r),o<a&&(a=o);let c=i;r>c&&(c=r),o>c&&(c=o),t[s+e]=a,t[s+e+3]=c}return t}computePrimitiveBounds(e,t,s){const i=this.geometry,r=this._indirectBuffer,n=i.attributes.position,o=i.index?i.index.array:null,a=n.normalized;if(e<0||t+e-s.offset>s.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const l=n.array,h=n.offset||0;let u=3;n.isInterleavedBufferAttribute&&(u=n.data.stride);const c=["getX","getY","getZ"],d=s.offset;for(let i=e,p=e+t;i<p;i++){const e=3*(r?r[i]:i),t=6*(i-d);let p=e+0,m=e+1,f=e+2;o&&(p=o[p],m=o[m],f=o[f]),a||(p=p*u+h,m=m*u+h,f=f*u+h);for(let e=0;e<3;e++){let i,r,o;a?(i=n[c[e]](p),r=n[c[e]](m),o=n[c[e]](f)):(i=l[p+e],r=l[m+e],o=l[f+e]);let h=i;r<h&&(h=r),o<h&&(h=o);let u=i;r>u&&(u=r),o>u&&(u=o);const d=(u-h)/2,g=2*e;s[t+g+0]=h+d,s[t+g+1]=d+(Math.abs(h)+d)*He}}return s}raycastObject3D(e,t,s=[]){const{material:i}=e;if(void 0===i)return;vi.copy(e.matrixWorld).invert(),_i.copy(t.ray).applyMatrix4(vi),Ti.setFromMatrixScale(e.matrixWorld),wi.copy(_i.direction).multiply(Ti);const r=wi.length(),n=t.near/r,o=t.far/r;if(!0===t.firstHitOnly){let r=this.raycastFirst(_i,i,n,o);r=xi(r,e,t),r&&s.push(r)}else{const r=this.raycast(_i,i,n,o);for(let i=0,n=r.length;i<n;i++){const n=xi(r[i],e,t);n&&s.push(n)}}return s}refit(e=null){return(this.indirect?Zs:As)(this,e)}raycast(e,t=i.FrontSide,s=0,r=1/0){const n=this._roots,o=[],a=this.indirect?Qs:Cs;for(let i=0,l=n.length;i<l;i++)a(this,i,t,e,o,s,r);return o}raycastFirst(e,t=i.FrontSide,s=0,r=1/0){const n=this._roots;let o=null;const a=this.indirect?ei:Bs;for(let i=0,l=n.length;i<l;i++){const n=a(this,i,t,e,s,r);null!=n&&(null==o||n.distance<o.distance)&&(o=n)}return o}intersectsGeometry(e,t){let s=!1;const i=this._roots,r=this.indirect?li:ks;for(let n=0,o=i.length;n<o&&(s=r(this,n,e,t),!s);n++);return s}shapecast(e){const t=os.getPrimitive(),s=super.shapecast({...e,intersectsPrimitive:e.intersectsTriangle,scratchPrimitive:t,iterate:this.indirect?Es:Ms});return os.releasePrimitive(t),s}bvhcast(e,t,s){let{intersectsRanges:i,intersectsTriangles:r}=s;const n=os.getPrimitive(),o=this.geometry.index,a=this.geometry.attributes.position,l=this.indirect?e=>{const t=this.resolveTriangleIndex(e);Ss(n,3*t,o,a)}:e=>{Ss(n,3*e,o,a)},h=os.getPrimitive(),u=e.geometry.index,c=e.geometry.attributes.position,d=e.indirect?t=>{const s=e.resolveTriangleIndex(t);Ss(h,3*s,u,c)}:e=>{Ss(h,3*e,u,c)};if(r){if(!(e instanceof Mi))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const s=(e,s,i,o,a,u,c,p)=>{for(let m=i,f=i+o;m<f;m++){d(m),h.a.applyMatrix4(t),h.b.applyMatrix4(t),h.c.applyMatrix4(t),h.needsUpdate=!0;for(let t=e,i=e+s;t<i;t++)if(l(t),n.needsUpdate=!0,r(n,h,t,m,a,u,c,p))return!0}return!1};if(i){const e=i;i=function(t,i,r,n,o,a,l,h){return!!e(t,i,r,n,o,a,l,h)||s(t,i,r,n,o,a,l,h)}}else i=s}return super.bvhcast(e,t,{intersectsRanges:i})}intersectsBox(e,t){return bi.set(e.min,e.max,t),bi.needsUpdate=!0,this.shapecast({intersectsBounds:e=>bi.intersectsBox(e),intersectsTriangle:e=>bi.intersectsTriangle(e)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,s={},i={},r=0,n=1/0){return(this.indirect?yi:Ys)(this,e,t,s,i,r,n)}closestPointToPoint(e,t={},s=0,i=1/0){return function(e,t,s={},i=0,r=1/0){const n=i*i,o=r*r;let a=1/0,l=null;if(e.shapecast({boundsTraverseOrder:e=>(as.copy(t).clamp(e.min,e.max),as.distanceToSquared(t)),intersectsBounds:(e,t,s)=>s<a&&s<o,intersectsTriangle:(e,s)=>{e.closestPointToPoint(t,as);const i=t.distanceToSquared(as);return i<a&&(ls.copy(as),a=i,l=s),i<n}}),a===1/0)return null;const h=Math.sqrt(a);return s.point?s.point.copy(ls):s.point=ls.clone(),s.distance=h,s.faceIndex=l,s}(this,e,t,s,i)}}const Ai=new i.Matrix4,Ni=new i.Ray,Ei=new St(()=>new i.Line3),Ci=new i.Vector3,Ri=new i.Vector3,Pi=new i.Box3,Bi=["getX","getY","getZ"];class Ii extends Yt{get primitiveStride(){return 2}writePrimitiveBounds(e,t,s){const i=this._indirectBuffer,{geometry:r,primitiveStride:n}=this,o=r.attributes.position,a=r.index,l=a?a.count:o.count;let h=(i?i[e]:e)*n,u=(h+1)%l;a&&(h=a.getX(h),u=a.getX(u));for(let e=0;e<3;e++){const i=o[Bi[e]](h),r=o[Bi[e]](u),n=i<r?i:r,a=i>r?i:r;t[s+e]=n,t[s+e+3]=a}return t}shapecast(e){const t=Ei.getPrimitive(),s=super.shapecast({...e,intersectsPrimitive:e.intersectsLine,scratchPrimitive:t,iterate:Di});return Ei.releasePrimitive(t),s}raycastObject3D(e,t,s=[]){const{matrixWorld:i}=e,{firstHitOnly:r}=t;Ai.copy(i).invert(),Ni.copy(t.ray).applyMatrix4(Ai);const n=t.params.Line.threshold/((e.scale.x+e.scale.y+e.scale.z)/3),o=n*n;let a=null,l=1/0;return this.shapecast({boundsTraverseOrder:e=>e.distanceToPoint(Ni.origin),intersectsBounds:e=>(Pi.copy(e).expandByScalar(Math.abs(n)),Ni.intersectsBox(Pi)?1:0),intersectsLine:(n,h)=>{if(Ni.distanceSqToSegment(n.start,n.end,Ci,Ri)>o)return;Ci.applyMatrix4(e.matrixWorld);const u=t.ray.origin.distanceTo(Ci);u<t.near||u>t.far||r&&u>=l||(l=u,h=this.resolvePrimitiveIndex(h),a={distance:u,point:Ri.clone().applyMatrix4(i),index:h*this.primitiveStride,face:null,faceIndex:null,barycoord:null,object:e},r||s.push(a))}}),r&&a&&s.push(a),s}}function Di(e,t,s,i,r,n,o){const{geometry:a,primitiveStride:l}=s,{index:h}=a,u=a.attributes.position,c=h?h.count:u.count;for(let a=e,d=t+e;a<d;a++){let e=s.resolvePrimitiveIndex(a)*l,t=(e+1)%c;if(h&&(e=h.getX(e),t=h.getX(t)),o.start.fromBufferAttribute(u,e),o.end.fromBufferAttribute(u,t),i(o,a,r,n))return!0}return!1}const Li={Mesh:i.Mesh.prototype.raycast,Line:i.Line.prototype.raycast,LineSegments:i.LineSegments.prototype.raycast,LineLoop:i.LineLoop.prototype.raycast,Points:i.Points.prototype.raycast,BatchedMesh:i.BatchedMesh.prototype.raycast},Fi=new i.Mesh,Oi=[];function Vi(e,t){if(this.isBatchedMesh)zi.call(this,e,t);else{const{geometry:s}=this;if(s.boundsTree)s.boundsTree.raycastObject3D(this,e,t);else{let s;if(this instanceof i.Mesh)s=Li.Mesh;else if(this instanceof i.LineSegments)s=Li.LineSegments;else if(this instanceof i.LineLoop)s=Li.LineLoop;else if(this instanceof i.Line)s=Li.Line;else{if(!(this instanceof i.Points))throw new Error("BVH: Fallback raycast function not found.");s=Li.Points}s.call(this,e,t)}}}function zi(e,t){if(this.boundsTrees){const s=this.boundsTrees,r=this._drawInfo||this._instanceInfo,n=this._drawRanges||this._geometryInfo,o=this.matrixWorld;Fi.material=this.material,Fi.geometry=this.geometry;const a=Fi.geometry.boundsTree,l=Fi.geometry.drawRange;null===Fi.geometry.boundingSphere&&(Fi.geometry.boundingSphere=new i.Sphere);for(let i=0,a=r.length;i<a;i++){if(!this.getVisibleAt(i))continue;const a=r[i].geometryIndex;if(Fi.geometry.boundsTree=s[a],this.getMatrixAt(i,Fi.matrixWorld).premultiply(o),!Fi.geometry.boundsTree){this.getBoundingBoxAt(a,Fi.geometry.boundingBox),this.getBoundingSphereAt(a,Fi.geometry.boundingSphere);const e=n[a];Fi.geometry.setDrawRange(e.start,e.count)}Fi.raycast(e,Oi);for(let e=0,s=Oi.length;e<s;e++){const s=Oi[e];s.object=this,s.batchId=i,t.push(s)}Oi.length=0}Fi.geometry.boundsTree=a,Fi.geometry.drawRange=l,Fi.material=null,Fi.geometry=null}else Li.BatchedMesh.call(this,e,t)}function ki(e={}){const{type:t=Mi}=e;return this.boundsTree=new t(this,e),this.boundsTree}function Ui(){this.boundsTree=null}const Gi=class e extends d{constructor(s){super(s),t(this,"onDisposed",new u),t(this,"onBeforeDispose",new u),t(this,"onFragmentsLoaded",new u),t(this,"baseCoordinationModel",""),t(this,"baseCoordinationMatrix",new l.Matrix4),t(this,"enabled",!0),t(this,"_core"),this.components.add(e.uuid,this)}get initialized(){return!!this._core}get list(){return this.core.models.list}get core(){if(!this._core)throw new Error("FragmentsManager not initialized. Call init() first.");return this._core}get _hasCoordinationModel(){return""!==this.baseCoordinationModel}dispose(){this.onBeforeDispose.trigger(),this._core&&(this.core.dispose(),this._core=void 0),this.baseCoordinationModel="",this.onFragmentsLoaded.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}init(e,t){this._core=new s.FragmentsModels(e,t),this.core.onModelLoaded.add(async()=>{if(this._hasCoordinationModel)return;const e=[...this.list.values()][0];e&&(this.baseCoordinationModel=e.modelId,this.baseCoordinationMatrix=await e.getCoordinationMatrix())}),this.list.onItemDeleted.add(()=>{this.list.size>0||(this.baseCoordinationModel="",this.baseCoordinationMatrix=new l.Matrix4)})}async raycast(e){const t=[];for(const s of this.core.models.list.values())if(e.snappingClasses&&e.snappingClasses.length>0){const i=await s.raycastWithSnapping(e);if(i&&i.length>0)t.push(i[0]);else{const i=await s.raycast(e);i&&t.push(i)}}else{const i=await s.raycast(e);i&&t.push(i)}if(await Promise.all(t),0===t.length)return;let s=t[0],i=s.distance;for(let e=1;e<t.length;e++)t[e].distance<i&&(i=t[e].distance,s=t[e]);return s}async getPositions(e){const t=[],s=async(e,s)=>{const i=await e.getPositions(s);for(const e of i)t.push(e)},i=[];for(const t in e){const r=this.core.models.list.get(t);r&&i.push(s(r,Array.from(e[t])))}return await Promise.all(i),t}async getBBoxes(e){const t=[],s=async(e,s)=>{const i=await e.getBoxes(s);if(i)for(const e of i)t.push(e)},i=[];for(const t in e){const r=this.core.models.list.get(t);r&&i.push(s(r,Array.from(e[t])))}return await Promise.all(i),t}async highlight(e,t){await this.forEachModel(t,"highlight",e)}async getData(e,t){const s={};for(const[i,r]of Object.entries(e)){const e=this.list.get(i);if(!e)continue;if(0===r.size){s[i]=[];continue}const n=await e.getItemsData([...r],t);s[i]=n}return s}async resetHighlight(e){await this.forEachModel(e,"resetHighlight")}async forEachModel(e,t,...s){const i={};if(e)for(const t in e){const s=e[t];i[t]=Array.from(s)}else for(const e of this.core.models.list.keys())i[e]=void 0;const r=[];for(const e in i){const n=this.core.models.list.get(e);if(n){const o=i[e],a=n[t](o,...s);r.push(a)}}await Promise.all(r)}async guidsToModelIdMap(e){const t={};for(const[s,i]of this.list){const r=(await i.getLocalIdsByGuids([...e])).filter(e=>null!==e);t[s]=new Set(r)}return t}async modelIdMapToGuids(e){const t=[];for(const[s,i]of Object.entries(e)){const e=this.list.get(s);if(!e)continue;const r=(await e.getGuidsByLocalIds([...i])).filter(e=>null!==e);t.push(...r)}return t}applyBaseCoordinateSystem(e,t){const s=new l.Matrix4;return t&&s.copy(t.clone()).invert(),s.multiply(this.baseCoordinationMatrix),e.applyMatrix4(s),s}};t(Gi,"uuid","fef46874-46a3-461b-8c44-2922ab77c806");let ji=Gi;function $i(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16}class Wi{constructor(e,t={}){const{pixelsPerMeter:s=.1}=t;this.pixelsPerMeter=s,this.renderer=e}async cull(e){e=function(e){const t=new Set;return e.traverse(e=>{e.isMesh&&t.add(e)}),Array.from(t)}(e);const{renderer:t,pixelsPerMeter:s}=this,r=new i.Vector3,n=new i.OrthographicCamera,o=new i.Box3,a=new i.WebGLRenderTarget(1,1);o.makeEmpty(),e.forEach(e=>{o.expandByObject(e)}),o.getSize(r);const l=Math.min(t.capabilities.maxTextureSize,8192),h=Math.ceil(r.x/s),u=Math.ceil(r.z/s),c=Math.ceil(h/l),d=Math.ceil(u/l);a.setSize(Math.ceil(h/c),Math.ceil(u/d)),n.rotation.x=-Math.PI/2,n.far=o.max.y-o.min.y+n.near,n.position.y=o.max.y+n.near;const p=new i.Scene,m=new Map,f=new Map,g=[];for(let t=0;t<e.length;t++){const s=e[t];m.set(s,s.material),f.set(s,s.parent);const i=new Hi;i.objectId=t,g.push(i),s.material=i,p.add(s)}const y=t.getClearColor(new i.Color),x=t.getClearAlpha(),b=t.getRenderTarget(),_=t.autoClear;t.autoClear=!0,t.setClearColor(0,0),t.setRenderTarget(a);const w=new Uint8Array(a.width*a.height*4),v=new Set,T=r.x/c,S=r.z/d;for(let s=0;s<c;s++)for(let i=0;i<d;i++){const r=o.min.x+T*s,l=r+T,h=o.min.z+S*i,u=(r+l)/2,c=(h+(h+S))/2;n.position.set(u,o.max.y,c);const d=T/2,m=S/2;n.left=-d,n.right=d,n.top=m,n.bottom=-m,n.updateProjectionMatrix(),t.render(p,n);const f=await t.readRenderTargetPixelsAsync(a,0,0,a.width,a.height,w);for(let t=0,s=f.length;t<s;t+=4){if(0===f[t+3])continue;const s=$i(f,t);v.add(e[s])}}for(const t of e){t.material=m.get(t);const e=f.get(t);e?e.add(t):p.remove(t)}t.setClearColor(y,x),t.setRenderTarget(b),t.autoClear=_;for(const e of g)e.dispose();return a.dispose(),Array.from(v)}}class Hi extends i.ShaderMaterial{get objectId(){return this._objectId}set objectId(e){var t,s;this._objectId=e,t=e,(s=this.uniforms.objectId.value).x=(255&t)/255,s.y=(t>>8&255)/255,s.z=(t>>16&255)/255,s.w=1}constructor(e){super({glslVersion:i.GLSL3,blending:i.NoBlending,uniforms:{objectId:{value:new i.Vector4}},vertexShader:"\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\t\t\t\tlayout(location = 0) out vec4 out_id;\n\t\t\t\tuniform vec4 objectId;\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tout_id = objectId;\n\n\t\t\t\t}\n\t\t\t"}),this._objectId=0,this.setValues(e)}}const qi=1e-16,Xi=new i.Vector3(0,1,0),Yi=new i.Vector3;function Zi(e){return e.delta(Yi).normalize(),Math.abs(Yi.dot(Xi))>=1-qi}function Qi(e,t){const{start:s,end:i}=t,r=e.points;let n=!1,o=!1;for(let e=0;e<3;e++){const t=r[e];if(!n&&s.distanceToSquared(t)<=qi&&(n=!0),!o&&i.distanceToSquared(t)<=qi&&(o=!0),n&&o)return!0}return n&&o}const Ki=new i.Line3;function Ji(e,t,s=!1,i=[]){let r=[[0,1]];for(let e=0,s=t.length;e<s;e++){const s=r[e],i=t[e];s[1]=i[0],r.push([i[1],1])}s&&([t,r]=[r,t]);for(let t=0,s=r.length;t<s;t++){const{start:s,end:n}=e;Ki.start.lerpVectors(s,n,r[t][0]),Ki.end.lerpVectors(s,n,r[t][1]),i.push(new Float32Array([Ki.start.x,Ki.start.y,Ki.start.z,Ki.end.x,Ki.end.y,Ki.end.z]))}return i}const er=new i.Vector3(0,1,0),tr=new i.Vector3,sr=new i.Vector3,ir=new i.Vector3,rr=new i.Triangle;function*nr(e,t=[],s={}){const{projectionDirection:r=er,thresholdAngle:n=1,iterationTime:o=30}=s,a=Math.pow(10,4),l=Math.cos(i.MathUtils.DEG2RAD*n),h=e.getIndex(),u=e.getAttribute("position"),c=h?h.count:u.count,d=[0,0,0],p=["a","b","c"],m=new Array(3),f={};let g=performance.now();for(let e=0;e<c;e+=3){performance.now()-g>o&&(yield,g=performance.now()),h?(d[0]=h.getX(e),d[1]=h.getX(e+1),d[2]=h.getX(e+2)):(d[0]=e,d[1]=e+1,d[2]=e+2);const{a:s,b:n,c:c}=rr;if(s.fromBufferAttribute(u,d[0]),n.fromBufferAttribute(u,d[1]),c.fromBufferAttribute(u,d[2]),rr.getNormal(ir),m[0]=`${Math.round(s.x*a)},${Math.round(s.y*a)},${Math.round(s.z*a)}`,m[1]=`${Math.round(n.x*a)},${Math.round(n.y*a)},${Math.round(n.z*a)}`,m[2]=`${Math.round(c.x*a)},${Math.round(c.y*a)},${Math.round(c.z*a)}`,m[0]!==m[1]&&m[1]!==m[2]&&m[2]!==m[0])for(let e=0;e<3;e++){const s=(e+1)%3,n=m[e],o=m[s],a=rr[p[e]],h=rr[p[s]],u=`${n}_${o}`,c=`${o}_${n}`;if(c in f&&f[c]){const e=f[c].normal,s=ir.dot(e)<=l;let n=!1;if(null!==r){let t=r.dot(ir);t=Math.abs(t)<1e-10?0:t;let s=r.dot(e);s=Math.abs(s)<1e-10?0:s,n=Math.sign(t)!==Math.sign(s)}if(s||n){const e=new i.Line3;e.start.copy(a),e.end.copy(h),t.push(e)}f[c]=null}else u in f||(f[u]={index0:d[e],index1:d[s],normal:ir.clone()})}}for(const e in f)if(f[e]){const{index0:s,index1:r}=f[e];tr.fromBufferAttribute(u,s),sr.fromBufferAttribute(u,r);const n=new i.Line3;n.start.copy(tr),n.end.copy(sr),t.push(n)}return t}const or=new i.Line3;function ar(e,t,s,i=[]){return e.bvhcast(t,s,{intersectsTriangles:(e,t)=>!function(e,t){const s=["a","b","c"];let i=0;for(let r=0;r<3;r++)for(let n=0;n<3;n++){lr(e[s[r]],t[s[n]])&&i++}return i>=2}(e,t)&&(e.needsUpdate&&e.update(),t.needsUpdate&&t.update(),!(Math.abs(e.plane.normal.dot(t.plane.normal))>.999999)&&void(!e.intersectsTriangle(t,or,!0)||Qi(e,or)||Qi(t,or)||i.push(or.clone())))}),i}function lr(e,t){return e.distanceTo(t)<1e-10}function hr(e){ur(e);let t=[];return e.traverse(e=>{e.geometry&&e.visible&&t.push(e)}),t}const ur=e=>{if(void 0===e)return;const t=[...e.children];for(const s of t)void 0===s?e.children.splice(e.children.indexOf(s),1):ur(s)},cr=new i.Matrix4,dr=new i.Matrix4;class pr{constructor(){this.projectionDirection=new i.Vector3(0,1,0),this.thresholdAngle=50,this.iterationTime=30}getEdges(...e){const t=this.iterationTime;this.iterationTime=1/0;const s=this.getEdgesGenerator(...e).next().value;return this.iterationTime=t,s}*getEdgesGenerator(e,t=[],s=null){const{projectionDirection:r,thresholdAngle:n,iterationTime:o}=this;if(e.isObject3D){const a=hr(e);let l=null;r&&(l=new i.Vector3);let h=performance.now();for(let e=0;e<a.length;e++){h-performance.now()>o&&(yield);const i=a[e];l&&(dr.copy(i.matrixWorld).invert(),l.copy(r).transformDirection(dr).normalize());const u=yield*nr(i.geometry,[],{projectionDirection:l,thresholdAngle:n,iterationTime:o});mr(u,i.matrixWorld);for(let e=0;e<u.length;e++)t.push(u[e]);if(null!==s)for(let e=0;e<u.length;e++)s.push(i)}return t}return yield*nr(e,t,{projectionDirection:r,thresholdAngle:n,iterationTime:o})}getIntersectionEdges(...e){const t=this.iterationTime;this.iterationTime=1/0;const s=this.getIntersectionEdgesGenerator(...e).next().value;return this.iterationTime=t,s}*getIntersectionEdgesGenerator(e,t=[],s=null){const{iterationTime:i}=this;if(e.isObject3D){const r=hr(e),n=new Map;let o=performance.now();for(let e=0;e<r.length;e++){performance.now()-o>i&&(yield,o=performance.now());const t=r[e].geometry;if(!n.has(t)){const e=t.boundsTree||new Mi(t,{maxLeafSize:1});n.set(t,e)}}o=performance.now();for(let e=0;e<r.length;e++)for(let a=e;a<r.length;a++){performance.now()-o>i&&(yield,o=performance.now());const l=r[e],h=r[a],u=n.get(l.geometry),c=n.get(h.geometry);cr.copy(l.matrixWorld).invert().multiply(h.matrixWorld);const d=ar(u,c,cr,[]);mr(d,l.matrixWorld);for(let e=0;e<d.length;e++)t.push(d[e]);if(null!==s)for(let e=0;e<d.length;e++)s.push(l)}return t}{let s;return e.isBufferGeometry?s=e.boundsTree||new Mi(e,{maxLeafSize:1}):(s=e,e=s.geometry),cr.identity(),ar(s,s,cr,t)}}}function mr(e,t,s=1e-6){for(let i=0;i<e.length;i++){const r=e[i];r.applyMatrix4(t),r.start.y+=s,r.end.y+=s}}class fr extends $t{get lines(){return this.primitiveBuffer}constructor(e,t){super(t),this.primitiveBuffer=e,this.primitiveBufferStride=1,this.heightOffset=t.heightOffset??1e3,this.init(t)}writePrimitiveBounds(e,t,s){const{primitiveBuffer:i,heightOffset:r}=this,{start:n,end:o}=i[e];t[s+0]=Math.min(n.x,o.x),t[s+1]=Math.min(n.y,o.y),t[s+2]=Math.min(n.z,o.z),t[s+3]=Math.max(n.x,o.x),t[s+4]=Math.max(n.y,o.y)+r,t[s+5]=Math.max(n.z,o.z)}getRootRanges(){return[{offset:0,count:this.primitiveBuffer.length}]}}const gr=new i.Vector3(0,1,0),yr=new i.Plane,xr=new i.Vector3,br=new i.Vector3;function _r(e,t,s){e.needsUpdate&&e.update(),yr.copy(e.plane),yr.normal.dot(gr)<0&&(yr.normal.multiplyScalar(-1),yr.constant*=-1);const r=yr.distanceToPoint(t.start),n=yr.distanceToPoint(t.end),o=Math.abs(r)<1e-16,a=r<0,l=n<0;if(t.delta(br).normalize(),Math.abs(yr.normal.dot(br))<1e-16)return!(o||!a)&&(s.copy(t),!0);if(a&&l)return s.copy(t),!0;if(!a&&!l)return!1;{const e=i.MathUtils.mapLinear(0,r,n,0,1);if(t.at(e,xr),a)return s.start.copy(t.start),s.end.copy(xr),!0;if(l)return s.end.copy(t.end),s.start.copy(xr),!0}return!1}const wr=new i.Plane,vr=new i.Vector3,Tr=new i.Vector3,Sr=new is,Mr=new i.Line3,Ar=new i.Line3,Nr=new i.Vector3,Er=new i.Vector3,Cr=new i.Vector3;function Rr(e,t,s=new i.Line3){if(Sr.copy(t),Sr.a.y=0,Sr.b.y=0,Sr.c.y=0,Sr.update(),Mr.copy(e),Mr.start.y=0,Mr.end.y=0,Sr.getArea()<=1e-16)return null;const r=Mr.distance();Mr.delta(Nr).divideScalar(r),Er.copy(Nr).cross(Sr.plane.normal).normalize(),wr.setFromNormalAndCoplanarPoint(Er,Mr.start);let n=0;const{points:o}=Sr;for(let e=0;e<3;e++){const t=o[e],s=o[(e+1)%3],i=wr.distanceToPoint(t),r=wr.distanceToPoint(s),a=Math.abs(i)<1e-16,l=Math.abs(r)<1e-16;let h=!1;if(!a&&!l&&i*r<0){const e=i/(i-r);vr.lerpVectors(t,s,e),h=!0}if((h&&!l||a)&&(a&&!h&&vr.copy(t),0===n?Ar.start.copy(vr):Ar.end.copy(vr),n++,2===n))break}if(2===n){if(Ar.delta(Cr).normalize(),Nr.dot(Cr)<0){const e=Ar.start;Ar.start=Ar.end,Ar.end=e}const t=0,i=Tr.subVectors(Mr.end,Mr.start).dot(Nr),n=Tr.subVectors(Ar.start,Mr.start).dot(Nr),o=Tr.subVectors(Ar.end,Mr.start).dot(Nr);return i<=n||o<=t?null:(e.at(Math.max(t,n)/r,s.start),e.at(Math.min(i,o)/r,s.end),s)}return null}const Pr=new i.Vector3,Br=new i.Vector3,Ir=new i.Vector3;function Dr(e,t,s){const i=function(e,t){e.delta(Pr),Br.subVectors(t.start,e.start),Ir.subVectors(t.end,e.start);const s=Pr.length();let i=Br.length()/s,r=Ir.length()/s;if(i=Math.min(Math.max(i,0),1),r=Math.min(Math.max(r,0),1),Math.abs(i-r)<=1e-16)return null;return[i,r]}(e,t);return!!i&&(Lr(i,s),!0)}function Lr(e,t){let[s,i]=e,r=0,n=t.length;for(;r<n;){const e=r+n>>>1;t[e][0]<=s?r=e+1:n=e}let o=Math.max(0,r-1),a=0;for(let e=o,r=t.length;e<r;e++){const[r,n]=t[e];if(s<=n&&i>=r)s=Math.min(r,s),i=Math.max(n,i),a++;else{if(!(s>=r))break;o=e+1}}t.splice(o,a,[s,i])}const Fr=new i.Vector3(0,1,0),Or=new i.Line3,Vr=new i.Line3,zr=new is;function kr(e,t,s,r,n=null){const{geometry:o,matrixWorld:a,material:l}=s,h=l.side,u=a.determinant()<0,c=e.lines;e.bvhcast(t,a,{intersectsRanges:(e,t,s,l)=>{n&&(n.candidates+=t*l);for(let d=s,p=l+s;d<p;d++){let s=3*d+0,l=3*d+1,p=3*d+2;o.index&&(s=o.index.getX(s),l=o.index.getX(l),p=o.index.getX(p));const{a:m,b:f,c:g}=zr;if(m.fromBufferAttribute(o.attributes.position,s).applyMatrix4(a),f.fromBufferAttribute(o.attributes.position,l).applyMatrix4(a),g.fromBufferAttribute(o.attributes.position,p).applyMatrix4(a),zr.needsUpdate=!0,zr.update(),h!==i.DoubleSide){if(zr.plane.normal.dot(Fr)!==u===(h===i.BackSide)){n&&(n.backFaceCulled+=t);continue}}const y=Math.max(m.y,f.y,g.y),x=Math.min(m.y,f.y,g.y),b=zr.plane.normal;let _=b.x,w=b.y,v=b.z,T=zr.plane.constant;w<0&&(_=-_,w=-w,v=-v,T=-T);for(let s=e,i=t+e;s<i;s++){const e=c[s],t=Math.min(e.start.y,e.end.y),i=Math.max(e.start.y,e.end.y);if(y<=t){n&&n.yBoundsCulled++;continue}const o=e.end.x-e.start.x,a=e.end.z-e.start.z,l=o*o+a*a;if(l>1e-20){const t=1/Math.sqrt(l),s=o*t,i=a*t,r=-i,h=s,u=m.x-e.start.x,c=m.z-e.start.z,d=f.x-e.start.x,p=f.z-e.start.z,y=g.x-e.start.x,x=g.z-e.start.z,b=u*s+c*i,_=d*s+p*i,w=y*s+x*i,v=1/t,T=Math.min(b,_,w);if(Math.max(b,_,w)<0||T>v){n&&n.xzBoundsCulled++;continue}const S=u*r+c*h,M=d*r+p*h,A=y*r+x*h,N=Math.min(S,M,A),E=Math.max(S,M,A);if(N>0||E<0){n&&n.xzBoundsCulled++;continue}}const h=_*e.start.x+w*e.start.y+v*e.start.z+T,u=_*e.end.x+w*e.end.y+v*e.end.z+T;if(h>=0&&u>=0)n&&n.planeTrimCulled++;else if(Qi(zr,e))n&&n.triangleEdgeCulled++;else{if(i<x)Or.copy(e);else if(!_r(zr,e,Or)){n&&n.planeTrimCulled++;continue}Or.distance()<1e-10?n&&n.distThresholdCulled++:Rr(Or,zr,Vr)?(n&&n.used++,Dr(e,Vr,r[s])):n&&n.noOverlapCulled++}}}}})}zr.update=()=>{zr.plane.setFromCoplanarPoints(...zr.points)};let Ur=!1;const Gr={},jr={};let $r=null,Wr=0,Hr=0;const qr={get enabled(){return Ur},set enabled(e){Ur=e},reset(){for(const e in Gr)delete Gr[e];for(const e in jr)delete jr[e];$r=null,Wr=0,Hr=0},setStat(e,t){jr[e]=t},startTotal(){Ur&&(Hr=performance.now())},startStep(e){Ur&&(null!==$r&&this.endStep(),$r=e,Wr=performance.now())},endStep(){if(!Ur||null===$r)return;const e=performance.now()-Wr;Gr[$r]=e,$r=null},printSummary(){if(!Ur)return;null!==$r&&this.endStep();const e=performance.now()-Hr;console.log("\n=== Projection Summary ==="),console.log(`Total time: ${e.toFixed(1)}ms\n`);for(const[t,s]of Object.entries(Gr)){const i=(s/e*100).toFixed(1);console.log(` ${t}: ${s.toFixed(1)}ms (${i}%)`)}if(Object.keys(jr).length>0){console.log("\n--- Stats ---");for(const[e,t]of Object.entries(jr))console.log(` ${e}: ${t}`)}console.log("")}},Xr="182",Yr=100,Zr=101,Qr=102,Kr=200,Jr=201,en=202,tn=203,sn=204,rn=205,nn=206,on=207,an=208,ln=209,hn=210,un=301,cn=302,dn=1e3,pn=1001,mn=1002,fn=1003,gn=1004,yn=1005,xn=1006,bn=1007,_n=1008,wn=1009,vn=1010,Tn=1011,Sn=1012,Mn=1013,An=1014,Nn=1015,En=1016,Cn=1017,Rn=1018,Pn=1020,Bn=35902,In=35899,Dn=1022,Ln=1023,Fn=1026,On=1027,Vn=1028,zn=1029,kn=1030,Un=1031,Gn=1033,jn=33776,$n=33777,Wn=33778,Hn=33779,qn=35840,Xn=35841,Yn=35842,Zn=35843,Qn=36196,Kn=37492,Jn=37496,eo=37488,to=37489,so=37490,io=37491,ro=37808,no=37809,oo=37810,ao=37811,lo=37812,ho=37813,uo=37814,co=37815,po=37816,mo=37817,fo=37818,go=37819,yo=37820,xo=37821,bo=36492,_o=36283,wo=36284,vo=36285,To=36286,So="",Mo="srgb",Ao="srgb-linear",No="linear",Eo="srgb",Co=7680,Ro=512,Po=513,Bo=514,Io=515,Do=516,Lo=517,Fo=518,Oo=519,Vo=35044,zo=35048,ko=2e3,Uo=2001,Go="compute",jo="render";
2
+ /**
3
+ * @license
4
+ * Copyright 2010-2025 Three.js Authors
5
+ * SPDX-License-Identifier: MIT
6
+ */function $o(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function Wo(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Ho(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}const qo={};function Xo(...e){const t="THREE."+e.shift();console.log(t,...e)}function Yo(...e){const t="THREE."+e.shift();console.warn(t,...e)}function Zo(...e){const t="THREE."+e.shift();console.error(t,...e)}function Qo(...e){const t=e.join(" ");t in qo||(qo[t]=!0,Yo(...e))}class Ko{addEventListener(e,t){void 0===this._listeners&&(this._listeners={});const s=this._listeners;void 0===s[e]&&(s[e]=[]),-1===s[e].indexOf(t)&&s[e].push(t)}hasEventListener(e,t){const s=this._listeners;return void 0!==s&&(void 0!==s[e]&&-1!==s[e].indexOf(t))}removeEventListener(e,t){const s=this._listeners;if(void 0===s)return;const i=s[e];if(void 0!==i){const e=i.indexOf(t);-1!==e&&i.splice(e,1)}}dispatchEvent(e){const t=this._listeners;if(void 0===t)return;const s=t[e.type];if(void 0!==s){e.target=this;const t=s.slice(0);for(let s=0,i=t.length;s<i;s++)t[s].call(this,e);e.target=null}}}const Jo=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let ea=1234567;const ta=Math.PI/180,sa=180/Math.PI;function ia(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(Jo[255&e]+Jo[e>>8&255]+Jo[e>>16&255]+Jo[e>>24&255]+"-"+Jo[255&t]+Jo[t>>8&255]+"-"+Jo[t>>16&15|64]+Jo[t>>24&255]+"-"+Jo[63&s|128]+Jo[s>>8&255]+"-"+Jo[s>>16&255]+Jo[s>>24&255]+Jo[255&i]+Jo[i>>8&255]+Jo[i>>16&255]+Jo[i>>24&255]).toLowerCase()}function ra(e,t,s){return Math.max(t,Math.min(s,e))}function na(e,t){return(e%t+t)%t}function oa(e,t,s){return(1-s)*e+s*t}function aa(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw new Error("Invalid component type.")}}function la(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(4294967295*e);case Uint16Array:return Math.round(65535*e);case Uint8Array:return Math.round(255*e);case Int32Array:return Math.round(2147483647*e);case Int16Array:return Math.round(32767*e);case Int8Array:return Math.round(127*e);default:throw new Error("Invalid component type.")}}const ha={DEG2RAD:ta,RAD2DEG:sa,generateUUID:ia,clamp:ra,euclideanModulo:na,mapLinear:function(e,t,s,i,r){return i+(e-t)*(r-i)/(s-t)},inverseLerp:function(e,t,s){return e!==t?(s-e)/(t-e):0},lerp:oa,damp:function(e,t,s,i){return oa(e,t,1-Math.exp(-s*i))},pingpong:function(e,t=1){return t-Math.abs(na(e,2*t)-t)},smoothstep:function(e,t,s){return e<=t?0:e>=s?1:(e=(e-t)/(s-t))*e*(3-2*e)},smootherstep:function(e,t,s){return e<=t?0:e>=s?1:(e=(e-t)/(s-t))*e*e*(e*(6*e-15)+10)},randInt:function(e,t){return e+Math.floor(Math.random()*(t-e+1))},randFloat:function(e,t){return e+Math.random()*(t-e)},randFloatSpread:function(e){return e*(.5-Math.random())},seededRandom:function(e){void 0!==e&&(ea=e);let t=ea+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296},degToRad:function(e){return e*ta},radToDeg:function(e){return e*sa},isPowerOfTwo:function(e){return!(e&e-1)&&0!==e},ceilPowerOfTwo:function(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))},floorPowerOfTwo:function(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))},setQuaternionFromProperEuler:function(e,t,s,i,r){const n=Math.cos,o=Math.sin,a=n(s/2),l=o(s/2),h=n((t+i)/2),u=o((t+i)/2),c=n((t-i)/2),d=o((t-i)/2),p=n((i-t)/2),m=o((i-t)/2);switch(r){case"XYX":e.set(a*u,l*c,l*d,a*h);break;case"YZY":e.set(l*d,a*u,l*c,a*h);break;case"ZXZ":e.set(l*c,l*d,a*u,a*h);break;case"XZX":e.set(a*u,l*m,l*p,a*h);break;case"YXY":e.set(l*p,a*u,l*m,a*h);break;case"ZYZ":e.set(l*m,l*p,a*u,a*h);break;default:Yo("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:la,denormalize:aa};class ua{constructor(e=0,t=0){ua.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,s=this.y,i=e.elements;return this.x=i[0]*t+i[3]*s+i[6],this.y=i[1]*t+i[4]*s+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=ra(this.x,e.x,t.x),this.y=ra(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=ra(this.x,e,t),this.y=ra(this.y,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(ra(s,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.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(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(ra(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y;return t*t+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const s=Math.cos(t),i=Math.sin(t),r=this.x-e.x,n=this.y-e.y;return this.x=r*s-n*i+e.x,this.y=r*i+n*s+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class ca{constructor(e=0,t=0,s=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=s,this._w=i}static slerpFlat(e,t,s,i,r,n,o){let a=s[i+0],l=s[i+1],h=s[i+2],u=s[i+3],c=r[n+0],d=r[n+1],p=r[n+2],m=r[n+3];if(o<=0)return e[t+0]=a,e[t+1]=l,e[t+2]=h,void(e[t+3]=u);if(o>=1)return e[t+0]=c,e[t+1]=d,e[t+2]=p,void(e[t+3]=m);if(u!==m||a!==c||l!==d||h!==p){let e=a*c+l*d+h*p+u*m;e<0&&(c=-c,d=-d,p=-p,m=-m,e=-e);let t=1-o;if(e<.9995){const s=Math.acos(e),i=Math.sin(s);t=Math.sin(t*s)/i,a=a*t+c*(o=Math.sin(o*s)/i),l=l*t+d*o,h=h*t+p*o,u=u*t+m*o}else{a=a*t+c*o,l=l*t+d*o,h=h*t+p*o,u=u*t+m*o;const e=1/Math.sqrt(a*a+l*l+h*h+u*u);a*=e,l*=e,h*=e,u*=e}}e[t]=a,e[t+1]=l,e[t+2]=h,e[t+3]=u}static multiplyQuaternionsFlat(e,t,s,i,r,n){const o=s[i],a=s[i+1],l=s[i+2],h=s[i+3],u=r[n],c=r[n+1],d=r[n+2],p=r[n+3];return e[t]=o*p+h*u+a*d-l*c,e[t+1]=a*p+h*c+l*u-o*d,e[t+2]=l*p+h*d+o*c-a*u,e[t+3]=h*p-o*u-a*c-l*d,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,s,i){return this._x=e,this._y=t,this._z=s,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const s=e._x,i=e._y,r=e._z,n=e._order,o=Math.cos,a=Math.sin,l=o(s/2),h=o(i/2),u=o(r/2),c=a(s/2),d=a(i/2),p=a(r/2);switch(n){case"XYZ":this._x=c*h*u+l*d*p,this._y=l*d*u-c*h*p,this._z=l*h*p+c*d*u,this._w=l*h*u-c*d*p;break;case"YXZ":this._x=c*h*u+l*d*p,this._y=l*d*u-c*h*p,this._z=l*h*p-c*d*u,this._w=l*h*u+c*d*p;break;case"ZXY":this._x=c*h*u-l*d*p,this._y=l*d*u+c*h*p,this._z=l*h*p+c*d*u,this._w=l*h*u-c*d*p;break;case"ZYX":this._x=c*h*u-l*d*p,this._y=l*d*u+c*h*p,this._z=l*h*p-c*d*u,this._w=l*h*u+c*d*p;break;case"YZX":this._x=c*h*u+l*d*p,this._y=l*d*u+c*h*p,this._z=l*h*p-c*d*u,this._w=l*h*u-c*d*p;break;case"XZY":this._x=c*h*u-l*d*p,this._y=l*d*u-c*h*p,this._z=l*h*p+c*d*u,this._w=l*h*u+c*d*p;break;default:Yo("Quaternion: .setFromEuler() encountered an unknown order: "+n)}return!0===t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const s=t/2,i=Math.sin(s);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(s),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,s=t[0],i=t[4],r=t[8],n=t[1],o=t[5],a=t[9],l=t[2],h=t[6],u=t[10],c=s+o+u;if(c>0){const e=.5/Math.sqrt(c+1);this._w=.25/e,this._x=(h-a)*e,this._y=(r-l)*e,this._z=(n-i)*e}else if(s>o&&s>u){const e=2*Math.sqrt(1+s-o-u);this._w=(h-a)/e,this._x=.25*e,this._y=(i+n)/e,this._z=(r+l)/e}else if(o>u){const e=2*Math.sqrt(1+o-s-u);this._w=(r-l)/e,this._x=(i+n)/e,this._y=.25*e,this._z=(a+h)/e}else{const e=2*Math.sqrt(1+u-s-o);this._w=(n-i)/e,this._x=(r+l)/e,this._y=(a+h)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let s=e.dot(t)+1;return s<1e-8?(s=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=s):(this._x=0,this._y=-e.z,this._z=e.y,this._w=s)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=s),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(ra(this.dot(e),-1,1)))}rotateTowards(e,t){const s=this.angleTo(e);if(0===s)return this;const i=Math.min(1,t/s);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return 0===e?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const s=e._x,i=e._y,r=e._z,n=e._w,o=t._x,a=t._y,l=t._z,h=t._w;return this._x=s*h+n*o+i*l-r*a,this._y=i*h+n*a+r*o-s*l,this._z=r*h+n*l+s*a-i*o,this._w=n*h-s*o-i*a-r*l,this._onChangeCallback(),this}slerp(e,t){if(t<=0)return this;if(t>=1)return this.copy(e);let s=e._x,i=e._y,r=e._z,n=e._w,o=this.dot(e);o<0&&(s=-s,i=-i,r=-r,n=-n,o=-o);let a=1-t;if(o<.9995){const e=Math.acos(o),l=Math.sin(e);a=Math.sin(a*e)/l,t=Math.sin(t*e)/l,this._x=this._x*a+s*t,this._y=this._y*a+i*t,this._z=this._z*a+r*t,this._w=this._w*a+n*t,this._onChangeCallback()}else this._x=this._x*a+s*t,this._y=this._y*a+i*t,this._z=this._z*a+r*t,this._w=this._w*a+n*t,this.normalize();return this}slerpQuaternions(e,t,s){return this.copy(e).slerp(t,s)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),s=Math.random(),i=Math.sqrt(1-s),r=Math.sqrt(s);return this.set(i*Math.sin(e),i*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class da{constructor(e=0,t=0,s=0){da.prototype.isVector3=!0,this.x=e,this.y=t,this.z=s}set(e,t,s){return void 0===s&&(s=this.z),this.x=e,this.y=t,this.z=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(ma.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(ma.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,s=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*s+r[6]*i,this.y=r[1]*t+r[4]*s+r[7]*i,this.z=r[2]*t+r[5]*s+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,s=this.y,i=this.z,r=e.elements,n=1/(r[3]*t+r[7]*s+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*s+r[8]*i+r[12])*n,this.y=(r[1]*t+r[5]*s+r[9]*i+r[13])*n,this.z=(r[2]*t+r[6]*s+r[10]*i+r[14])*n,this}applyQuaternion(e){const t=this.x,s=this.y,i=this.z,r=e.x,n=e.y,o=e.z,a=e.w,l=2*(n*i-o*s),h=2*(o*t-r*i),u=2*(r*s-n*t);return this.x=t+a*l+n*u-o*h,this.y=s+a*h+o*l-r*u,this.z=i+a*u+r*h-n*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,s=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*s+r[8]*i,this.y=r[1]*t+r[5]*s+r[9]*i,this.z=r[2]*t+r[6]*s+r[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=ra(this.x,e.x,t.x),this.y=ra(this.y,e.y,t.y),this.z=ra(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=ra(this.x,e,t),this.y=ra(this.y,e,t),this.z=ra(this.z,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(ra(s,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const s=e.x,i=e.y,r=e.z,n=t.x,o=t.y,a=t.z;return this.x=i*a-r*o,this.y=r*n-s*a,this.z=s*o-i*n,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const s=e.dot(this)/t;return this.copy(e).multiplyScalar(s)}projectOnPlane(e){return pa.copy(this).projectOnVector(e),this.sub(pa)}reflect(e){return this.sub(pa.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(ra(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y,i=this.z-e.z;return t*t+s*s+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,s){const i=Math.sin(t)*e;return this.x=i*Math.sin(s),this.y=Math.cos(t)*e,this.z=i*Math.cos(s),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,s){return this.x=e*Math.sin(t),this.y=s,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),s=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=s,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=2*Math.random()-1,s=Math.sqrt(1-t*t);return this.x=s*Math.cos(e),this.y=t,this.z=s*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const pa=new da,ma=new ca;class fa{constructor(e,t,s,i,r,n,o,a,l){fa.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,s,i,r,n,o,a,l)}set(e,t,s,i,r,n,o,a,l){const h=this.elements;return h[0]=e,h[1]=i,h[2]=o,h[3]=t,h[4]=r,h[5]=a,h[6]=s,h[7]=n,h[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],this}extractBasis(e,t,s){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),s.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const s=e.elements,i=t.elements,r=this.elements,n=s[0],o=s[3],a=s[6],l=s[1],h=s[4],u=s[7],c=s[2],d=s[5],p=s[8],m=i[0],f=i[3],g=i[6],y=i[1],x=i[4],b=i[7],_=i[2],w=i[5],v=i[8];return r[0]=n*m+o*y+a*_,r[3]=n*f+o*x+a*w,r[6]=n*g+o*b+a*v,r[1]=l*m+h*y+u*_,r[4]=l*f+h*x+u*w,r[7]=l*g+h*b+u*v,r[2]=c*m+d*y+p*_,r[5]=c*f+d*x+p*w,r[8]=c*g+d*b+p*v,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],o=e[5],a=e[6],l=e[7],h=e[8];return t*n*h-t*o*l-s*r*h+s*o*a+i*r*l-i*n*a}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],o=e[5],a=e[6],l=e[7],h=e[8],u=h*n-o*l,c=o*a-h*r,d=l*r-n*a,p=t*u+s*c+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return e[0]=u*m,e[1]=(i*l-h*s)*m,e[2]=(o*s-i*n)*m,e[3]=c*m,e[4]=(h*t-i*a)*m,e[5]=(i*r-o*t)*m,e[6]=d*m,e[7]=(s*a-l*t)*m,e[8]=(n*t-s*r)*m,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,s,i,r,n,o){const a=Math.cos(r),l=Math.sin(r);return this.set(s*a,s*l,-s*(a*n+l*o)+n+e,-i*l,i*a,-i*(-l*n+a*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(ga.makeScale(e,t)),this}rotate(e){return this.premultiply(ga.makeRotation(-e)),this}translate(e,t){return this.premultiply(ga.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,s,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,s=e.elements;for(let e=0;e<9;e++)if(t[e]!==s[e])return!1;return!0}fromArray(e,t=0){for(let s=0;s<9;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e}clone(){return(new this.constructor).fromArray(this.elements)}}const ga=new fa,ya=(new fa).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),xa=(new fa).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function ba(){const e={enabled:!0,workingColorSpace:Ao,spaces:{},convert:function(e,t,s){return!1!==this.enabled&&t!==s&&t&&s?(this.spaces[t].transfer===Eo&&(e.r=wa(e.r),e.g=wa(e.g),e.b=wa(e.b)),this.spaces[t].primaries!==this.spaces[s].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[s].fromXYZ)),this.spaces[s].transfer===Eo&&(e.r=va(e.r),e.g=va(e.g),e.b=va(e.b)),e):e},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===So?No:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,s){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[s].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,s){return Qo("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),e.workingToColorSpace(t,s)},toWorkingColorSpace:function(t,s){return Qo("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),e.colorSpaceToWorking(t,s)}},t=[.64,.33,.3,.6,.15,.06],s=[.2126,.7152,.0722],i=[.3127,.329];return e.define({[Ao]:{primaries:t,whitePoint:i,transfer:No,toXYZ:ya,fromXYZ:xa,luminanceCoefficients:s,workingColorSpaceConfig:{unpackColorSpace:Mo},outputColorSpaceConfig:{drawingBufferColorSpace:Mo}},[Mo]:{primaries:t,whitePoint:i,transfer:Eo,toXYZ:ya,fromXYZ:xa,luminanceCoefficients:s,outputColorSpaceConfig:{drawingBufferColorSpace:Mo}}}),e}const _a=ba();function wa(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function va(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let Ta;class Sa{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let s;if(e instanceof HTMLCanvasElement)s=e;else{void 0===Ta&&(Ta=Ho("canvas")),Ta.width=e.width,Ta.height=e.height;const t=Ta.getContext("2d");e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),s=Ta}return s.toDataURL(t)}static sRGBToLinear(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const t=Ho("canvas");t.width=e.width,t.height=e.height;const s=t.getContext("2d");s.drawImage(e,0,0,e.width,e.height);const i=s.getImageData(0,0,e.width,e.height),r=i.data;for(let e=0;e<r.length;e++)r[e]=255*wa(r[e]/255);return s.putImageData(i,0,0),t}if(e.data){const t=e.data.slice(0);for(let e=0;e<t.length;e++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[e]=Math.floor(255*wa(t[e]/255)):t[e]=wa(t[e]);return{data:t,width:e.width,height:e.height}}return Yo("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let Ma=0;class Aa{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Ma++}),this.uuid=ia(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return"undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):"undefined"!=typeof VideoFrame&&t instanceof VideoFrame?e.set(t.displayHeight,t.displayWidth,0):null!==t?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){!0===e&&this.version++}toJSON(e){const t=void 0===e||"string"==typeof e;if(!t&&void 0!==e.images[this.uuid])return e.images[this.uuid];const s={uuid:this.uuid,url:""},i=this.data;if(null!==i){let e;if(Array.isArray(i)){e=[];for(let t=0,s=i.length;t<s;t++)i[t].isDataTexture?e.push(Na(i[t].image)):e.push(Na(i[t]))}else e=Na(i);s.url=e}return t||(e.images[this.uuid]=s),s}}function Na(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?Sa.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(Yo("Texture: Unable to serialize Texture."),{})}let Ea=0;const Ca=new da;class Ra extends Ko{constructor(e=Ra.DEFAULT_IMAGE,t=Ra.DEFAULT_MAPPING,s=1001,i=1001,r=1006,n=1008,o=1023,a=1009,l=Ra.DEFAULT_ANISOTROPY,h=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Ea++}),this.uuid=ia(),this.name="",this.source=new Aa(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=s,this.wrapT=i,this.magFilter=r,this.minFilter=n,this.anisotropy=l,this.format=o,this.internalFormat=null,this.type=a,this.offset=new ua(0,0),this.repeat=new ua(1,1),this.center=new ua(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new fa,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=h,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(Ca).x}get height(){return this.source.getSize(Ca).y}get depth(){return this.source.getSize(Ca).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return(new this.constructor).copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const s=e[t];if(void 0===s){Yo(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&s&&i.isVector2&&s.isVector2||i&&s&&i.isVector3&&s.isVector3||i&&s&&i.isMatrix3&&s.isMatrix3?i.copy(s):this[t]=s:Yo(`Texture.setValues(): property '${t}' does not exist.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;if(!t&&void 0!==e.textures[this.uuid])return e.textures[this.uuid];const s={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(s.userData=this.userData),t||(e.textures[this.uuid]=s),s}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(300!==this.mapping)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case dn:e.x=e.x-Math.floor(e.x);break;case pn:e.x=e.x<0?0:1;break;case mn:1===Math.abs(Math.floor(e.x)%2)?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case dn:e.y=e.y-Math.floor(e.y);break;case pn:e.y=e.y<0?0:1;break;case mn:1===Math.abs(Math.floor(e.y)%2)?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){!0===e&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){!0===e&&this.pmremVersion++}}Ra.DEFAULT_IMAGE=null,Ra.DEFAULT_MAPPING=300,Ra.DEFAULT_ANISOTROPY=1;class Pa{constructor(e=0,t=0,s=0,i=1){Pa.prototype.isVector4=!0,this.x=e,this.y=t,this.z=s,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,s,i){return this.x=e,this.y=t,this.z=s,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=void 0!==e.w?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,s=this.y,i=this.z,r=this.w,n=e.elements;return this.x=n[0]*t+n[4]*s+n[8]*i+n[12]*r,this.y=n[1]*t+n[5]*s+n[9]*i+n[13]*r,this.z=n[2]*t+n[6]*s+n[10]*i+n[14]*r,this.w=n[3]*t+n[7]*s+n[11]*i+n[15]*r,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,s,i,r;const n=.01,o=.1,a=e.elements,l=a[0],h=a[4],u=a[8],c=a[1],d=a[5],p=a[9],m=a[2],f=a[6],g=a[10];if(Math.abs(h-c)<n&&Math.abs(u-m)<n&&Math.abs(p-f)<n){if(Math.abs(h+c)<o&&Math.abs(u+m)<o&&Math.abs(p+f)<o&&Math.abs(l+d+g-3)<o)return this.set(1,0,0,0),this;t=Math.PI;const e=(l+1)/2,a=(d+1)/2,y=(g+1)/2,x=(h+c)/4,b=(u+m)/4,_=(p+f)/4;return e>a&&e>y?e<n?(s=0,i=.707106781,r=.707106781):(s=Math.sqrt(e),i=x/s,r=b/s):a>y?a<n?(s=.707106781,i=0,r=.707106781):(i=Math.sqrt(a),s=x/i,r=_/i):y<n?(s=.707106781,i=.707106781,r=0):(r=Math.sqrt(y),s=b/r,i=_/r),this.set(s,i,r,t),this}let y=Math.sqrt((f-p)*(f-p)+(u-m)*(u-m)+(c-h)*(c-h));return Math.abs(y)<.001&&(y=1),this.x=(f-p)/y,this.y=(u-m)/y,this.z=(c-h)/y,this.w=Math.acos((l+d+g-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=ra(this.x,e.x,t.x),this.y=ra(this.y,e.y,t.y),this.z=ra(this.z,e.z,t.z),this.w=ra(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=ra(this.x,e,t),this.y=ra(this.y,e,t),this.z=ra(this.z,e,t),this.w=ra(this.w,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(ra(s,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this.w=e.w+(t.w-e.w)*s,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class Ba extends Ko{constructor(e=1,t=1,s={}){super(),s=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:xn,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},s),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=s.depth,this.scissor=new Pa(0,0,e,t),this.scissorTest=!1,this.viewport=new Pa(0,0,e,t);const i={width:e,height:t,depth:s.depth},r=new Ra(i);this.textures=[];const n=s.count;for(let e=0;e<n;e++)this.textures[e]=r.clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;this._setTextureOptions(s),this.depthBuffer=s.depthBuffer,this.stencilBuffer=s.stencilBuffer,this.resolveDepthBuffer=s.resolveDepthBuffer,this.resolveStencilBuffer=s.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=s.depthTexture,this.samples=s.samples,this.multiview=s.multiview}_setTextureOptions(e={}){const t={minFilter:xn,generateMipmaps:!1,flipY:!1,internalFormat:null};void 0!==e.mapping&&(t.mapping=e.mapping),void 0!==e.wrapS&&(t.wrapS=e.wrapS),void 0!==e.wrapT&&(t.wrapT=e.wrapT),void 0!==e.wrapR&&(t.wrapR=e.wrapR),void 0!==e.magFilter&&(t.magFilter=e.magFilter),void 0!==e.minFilter&&(t.minFilter=e.minFilter),void 0!==e.format&&(t.format=e.format),void 0!==e.type&&(t.type=e.type),void 0!==e.anisotropy&&(t.anisotropy=e.anisotropy),void 0!==e.colorSpace&&(t.colorSpace=e.colorSpace),void 0!==e.flipY&&(t.flipY=e.flipY),void 0!==e.generateMipmaps&&(t.generateMipmaps=e.generateMipmaps),void 0!==e.internalFormat&&(t.internalFormat=e.internalFormat);for(let e=0;e<this.textures.length;e++){this.textures[e].setValues(t)}}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){null!==this._depthTexture&&(this._depthTexture.renderTarget=null),null!==e&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,s=1){if(this.width!==e||this.height!==t||this.depth!==s){this.width=e,this.height=t,this.depth=s;for(let i=0,r=this.textures.length;i<r;i++)this.textures[i].image.width=e,this.textures[i].image.height=t,this.textures[i].image.depth=s,!0!==this.textures[i].isData3DTexture&&(this.textures[i].isArrayTexture=this.textures[i].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return(new this.constructor).copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,s=e.textures.length;t<s;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const s=Object.assign({},e.textures[t].image);this.textures[t].source=new Aa(s)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,null!==e.depthTexture&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class Ia extends Ba{constructor(e=1,t=1,s={}){super(e,t,s),this.isWebGLRenderTarget=!0}}class Da extends Ra{constructor(e=null,t=1,s=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:s,depth:i},this.magFilter=fn,this.minFilter=fn,this.wrapR=pn,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class La{constructor(e=new da(1/0,1/0,1/0),t=new da(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,s=e.length;t<s;t+=3)this.expandByPoint(Oa.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,s=e.count;t<s;t++)this.expandByPoint(Oa.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,s=e.length;t<s;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const s=Oa.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(s),this.max.copy(e).add(s),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return(new this.constructor).copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const s=e.geometry;if(void 0!==s){const i=s.getAttribute("position");if(!0===t&&void 0!==i&&!0!==e.isInstancedMesh)for(let t=0,s=i.count;t<s;t++)!0===e.isMesh?e.getVertexPosition(t,Oa):Oa.fromBufferAttribute(i,t),Oa.applyMatrix4(e.matrixWorld),this.expandByPoint(Oa);else void 0!==e.boundingBox?(null===e.boundingBox&&e.computeBoundingBox(),Va.copy(e.boundingBox)):(null===s.boundingBox&&s.computeBoundingBox(),Va.copy(s.boundingBox)),Va.applyMatrix4(e.matrixWorld),this.union(Va)}const i=e.children;for(let e=0,s=i.length;e<s;e++)this.expandByObject(i[e],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Oa),Oa.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,s;return e.normal.x>0?(t=e.normal.x*this.min.x,s=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,s=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,s+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,s+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,s+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,s+=e.normal.z*this.min.z),t<=-e.constant&&s>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Wa),Ha.subVectors(this.max,Wa),za.subVectors(e.a,Wa),ka.subVectors(e.b,Wa),Ua.subVectors(e.c,Wa),Ga.subVectors(ka,za),ja.subVectors(Ua,ka),$a.subVectors(za,Ua);let t=[0,-Ga.z,Ga.y,0,-ja.z,ja.y,0,-$a.z,$a.y,Ga.z,0,-Ga.x,ja.z,0,-ja.x,$a.z,0,-$a.x,-Ga.y,Ga.x,0,-ja.y,ja.x,0,-$a.y,$a.x,0];return!!Ya(t,za,ka,Ua,Ha)&&(t=[1,0,0,0,1,0,0,0,1],!!Ya(t,za,ka,Ua,Ha)&&(qa.crossVectors(Ga,ja),t=[qa.x,qa.y,qa.z],Ya(t,za,ka,Ua,Ha)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Oa).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(Oa).length()),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()||(Fa[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Fa[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Fa[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Fa[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Fa[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Fa[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Fa[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Fa[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Fa)),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const Fa=[new da,new da,new da,new da,new da,new da,new da,new da],Oa=new da,Va=new La,za=new da,ka=new da,Ua=new da,Ga=new da,ja=new da,$a=new da,Wa=new da,Ha=new da,qa=new da,Xa=new da;function Ya(e,t,s,i,r){for(let n=0,o=e.length-3;n<=o;n+=3){Xa.fromArray(e,n);const o=r.x*Math.abs(Xa.x)+r.y*Math.abs(Xa.y)+r.z*Math.abs(Xa.z),a=t.dot(Xa),l=s.dot(Xa),h=i.dot(Xa);if(Math.max(-Math.max(a,l,h),Math.min(a,l,h))>o)return!1}return!0}const Za=new La,Qa=new da,Ka=new da;class Ja{constructor(e=new da,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const s=this.center;void 0!==t?s.copy(t):Za.setFromPoints(e).getCenter(s);let i=0;for(let t=0,r=e.length;t<r;t++)i=Math.max(i,s.distanceToSquared(e[t]));return this.radius=Math.sqrt(i),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const s=this.center.distanceToSquared(e);return t.copy(e),s>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Qa.subVectors(e,this.center);const t=Qa.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),s=.5*(e-this.radius);this.center.addScaledVector(Qa,s/e),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(!0===this.center.equals(e.center)?this.radius=Math.max(this.radius,e.radius):(Ka.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Qa.copy(e.center).add(Ka)),this.expandByPoint(Qa.copy(e.center).sub(Ka))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}const el=new da,tl=new da,sl=new da,il=new da,rl=new da,nl=new da,ol=new da;class al{constructor(e=new da,t=new da(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,el)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const s=t.dot(this.direction);return s<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,s)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=el.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(el.copy(this.origin).addScaledVector(this.direction,t),el.distanceToSquared(e))}distanceSqToSegment(e,t,s,i){tl.copy(e).add(t).multiplyScalar(.5),sl.copy(t).sub(e).normalize(),il.copy(this.origin).sub(tl);const r=.5*e.distanceTo(t),n=-this.direction.dot(sl),o=il.dot(this.direction),a=-il.dot(sl),l=il.lengthSq(),h=Math.abs(1-n*n);let u,c,d,p;if(h>0)if(u=n*a-o,c=n*o-a,p=r*h,u>=0)if(c>=-p)if(c<=p){const e=1/h;u*=e,c*=e,d=u*(u+n*c+2*o)+c*(n*u+c+2*a)+l}else c=r,u=Math.max(0,-(n*c+o)),d=-u*u+c*(c+2*a)+l;else c=-r,u=Math.max(0,-(n*c+o)),d=-u*u+c*(c+2*a)+l;else c<=-p?(u=Math.max(0,-(-n*r+o)),c=u>0?-r:Math.min(Math.max(-r,-a),r),d=-u*u+c*(c+2*a)+l):c<=p?(u=0,c=Math.min(Math.max(-r,-a),r),d=c*(c+2*a)+l):(u=Math.max(0,-(n*r+o)),c=u>0?r:Math.min(Math.max(-r,-a),r),d=-u*u+c*(c+2*a)+l);else c=n>0?-r:r,u=Math.max(0,-(n*c+o)),d=-u*u+c*(c+2*a)+l;return s&&s.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(tl).addScaledVector(sl,c),d}intersectSphere(e,t){el.subVectors(e.center,this.origin);const s=el.dot(this.direction),i=el.dot(el)-s*s,r=e.radius*e.radius;if(i>r)return null;const n=Math.sqrt(r-i),o=s-n,a=s+n;return a<0?null:o<0?this.at(a,t):this.at(o,t)}intersectsSphere(e){return!(e.radius<0)&&this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(0===t)return 0===e.distanceToPoint(this.origin)?0:null;const s=-(this.origin.dot(e.normal)+e.constant)/t;return s>=0?s:null}intersectPlane(e,t){const s=this.distanceToPlane(e);return null===s?null:this.at(s,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);if(0===t)return!0;return e.normal.dot(this.direction)*t<0}intersectBox(e,t){let s,i,r,n,o,a;const l=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,c=this.origin;return l>=0?(s=(e.min.x-c.x)*l,i=(e.max.x-c.x)*l):(s=(e.max.x-c.x)*l,i=(e.min.x-c.x)*l),h>=0?(r=(e.min.y-c.y)*h,n=(e.max.y-c.y)*h):(r=(e.max.y-c.y)*h,n=(e.min.y-c.y)*h),s>n||r>i?null:((r>s||isNaN(s))&&(s=r),(n<i||isNaN(i))&&(i=n),u>=0?(o=(e.min.z-c.z)*u,a=(e.max.z-c.z)*u):(o=(e.max.z-c.z)*u,a=(e.min.z-c.z)*u),s>a||o>i?null:((o>s||s!=s)&&(s=o),(a<i||i!=i)&&(i=a),i<0?null:this.at(s>=0?s:i,t)))}intersectsBox(e){return null!==this.intersectBox(e,el)}intersectTriangle(e,t,s,i,r){rl.subVectors(t,e),nl.subVectors(s,e),ol.crossVectors(rl,nl);let n,o=this.direction.dot(ol);if(o>0){if(i)return null;n=1}else{if(!(o<0))return null;n=-1,o=-o}il.subVectors(this.origin,e);const a=n*this.direction.dot(nl.crossVectors(il,nl));if(a<0)return null;const l=n*this.direction.dot(rl.cross(il));if(l<0)return null;if(a+l>o)return null;const h=-n*il.dot(ol);return h<0?null:this.at(h/o,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class ll{constructor(e,t,s,i,r,n,o,a,l,h,u,c,d,p,m,f){ll.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==e&&this.set(e,t,s,i,r,n,o,a,l,h,u,c,d,p,m,f)}set(e,t,s,i,r,n,o,a,l,h,u,c,d,p,m,f){const g=this.elements;return g[0]=e,g[4]=t,g[8]=s,g[12]=i,g[1]=r,g[5]=n,g[9]=o,g[13]=a,g[2]=l,g[6]=h,g[10]=u,g[14]=c,g[3]=d,g[7]=p,g[11]=m,g[15]=f,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new ll).fromArray(this.elements)}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],t[9]=s[9],t[10]=s[10],t[11]=s[11],t[12]=s[12],t[13]=s[13],t[14]=s[14],t[15]=s[15],this}copyPosition(e){const t=this.elements,s=e.elements;return t[12]=s[12],t[13]=s[13],t[14]=s[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,s){return 0===this.determinant()?(e.set(1,0,0),t.set(0,1,0),s.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),s.setFromMatrixColumn(this,2),this)}makeBasis(e,t,s){return this.set(e.x,t.x,s.x,0,e.y,t.y,s.y,0,e.z,t.z,s.z,0,0,0,0,1),this}extractRotation(e){if(0===e.determinant())return this.identity();const t=this.elements,s=e.elements,i=1/hl.setFromMatrixColumn(e,0).length(),r=1/hl.setFromMatrixColumn(e,1).length(),n=1/hl.setFromMatrixColumn(e,2).length();return t[0]=s[0]*i,t[1]=s[1]*i,t[2]=s[2]*i,t[3]=0,t[4]=s[4]*r,t[5]=s[5]*r,t[6]=s[6]*r,t[7]=0,t[8]=s[8]*n,t[9]=s[9]*n,t[10]=s[10]*n,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,s=e.x,i=e.y,r=e.z,n=Math.cos(s),o=Math.sin(s),a=Math.cos(i),l=Math.sin(i),h=Math.cos(r),u=Math.sin(r);if("XYZ"===e.order){const e=n*h,s=n*u,i=o*h,r=o*u;t[0]=a*h,t[4]=-a*u,t[8]=l,t[1]=s+i*l,t[5]=e-r*l,t[9]=-o*a,t[2]=r-e*l,t[6]=i+s*l,t[10]=n*a}else if("YXZ"===e.order){const e=a*h,s=a*u,i=l*h,r=l*u;t[0]=e+r*o,t[4]=i*o-s,t[8]=n*l,t[1]=n*u,t[5]=n*h,t[9]=-o,t[2]=s*o-i,t[6]=r+e*o,t[10]=n*a}else if("ZXY"===e.order){const e=a*h,s=a*u,i=l*h,r=l*u;t[0]=e-r*o,t[4]=-n*u,t[8]=i+s*o,t[1]=s+i*o,t[5]=n*h,t[9]=r-e*o,t[2]=-n*l,t[6]=o,t[10]=n*a}else if("ZYX"===e.order){const e=n*h,s=n*u,i=o*h,r=o*u;t[0]=a*h,t[4]=i*l-s,t[8]=e*l+r,t[1]=a*u,t[5]=r*l+e,t[9]=s*l-i,t[2]=-l,t[6]=o*a,t[10]=n*a}else if("YZX"===e.order){const e=n*a,s=n*l,i=o*a,r=o*l;t[0]=a*h,t[4]=r-e*u,t[8]=i*u+s,t[1]=u,t[5]=n*h,t[9]=-o*h,t[2]=-l*h,t[6]=s*u+i,t[10]=e-r*u}else if("XZY"===e.order){const e=n*a,s=n*l,i=o*a,r=o*l;t[0]=a*h,t[4]=-u,t[8]=l*h,t[1]=e*u+r,t[5]=n*h,t[9]=s*u-i,t[2]=i*u-s,t[6]=o*h,t[10]=r*u+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(cl,e,dl)}lookAt(e,t,s){const i=this.elements;return fl.subVectors(e,t),0===fl.lengthSq()&&(fl.z=1),fl.normalize(),pl.crossVectors(s,fl),0===pl.lengthSq()&&(1===Math.abs(s.z)?fl.x+=1e-4:fl.z+=1e-4,fl.normalize(),pl.crossVectors(s,fl)),pl.normalize(),ml.crossVectors(fl,pl),i[0]=pl.x,i[4]=ml.x,i[8]=fl.x,i[1]=pl.y,i[5]=ml.y,i[9]=fl.y,i[2]=pl.z,i[6]=ml.z,i[10]=fl.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const s=e.elements,i=t.elements,r=this.elements,n=s[0],o=s[4],a=s[8],l=s[12],h=s[1],u=s[5],c=s[9],d=s[13],p=s[2],m=s[6],f=s[10],g=s[14],y=s[3],x=s[7],b=s[11],_=s[15],w=i[0],v=i[4],T=i[8],S=i[12],M=i[1],A=i[5],N=i[9],E=i[13],C=i[2],R=i[6],P=i[10],B=i[14],I=i[3],D=i[7],L=i[11],F=i[15];return r[0]=n*w+o*M+a*C+l*I,r[4]=n*v+o*A+a*R+l*D,r[8]=n*T+o*N+a*P+l*L,r[12]=n*S+o*E+a*B+l*F,r[1]=h*w+u*M+c*C+d*I,r[5]=h*v+u*A+c*R+d*D,r[9]=h*T+u*N+c*P+d*L,r[13]=h*S+u*E+c*B+d*F,r[2]=p*w+m*M+f*C+g*I,r[6]=p*v+m*A+f*R+g*D,r[10]=p*T+m*N+f*P+g*L,r[14]=p*S+m*E+f*B+g*F,r[3]=y*w+x*M+b*C+_*I,r[7]=y*v+x*A+b*R+_*D,r[11]=y*T+x*N+b*P+_*L,r[15]=y*S+x*E+b*B+_*F,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],s=e[4],i=e[8],r=e[12],n=e[1],o=e[5],a=e[9],l=e[13],h=e[2],u=e[6],c=e[10],d=e[14],p=e[3],m=e[7],f=e[11],g=e[15],y=a*d-l*c,x=o*d-l*u,b=o*c-a*u,_=n*d-l*h,w=n*c-a*h,v=n*u-o*h;return t*(m*y-f*x+g*b)-s*(p*y-f*_+g*w)+i*(p*x-m*_+g*v)-r*(p*b-m*w+f*v)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,s){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=s),this}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],o=e[5],a=e[6],l=e[7],h=e[8],u=e[9],c=e[10],d=e[11],p=e[12],m=e[13],f=e[14],g=e[15],y=u*f*l-m*c*l+m*a*d-o*f*d-u*a*g+o*c*g,x=p*c*l-h*f*l-p*a*d+n*f*d+h*a*g-n*c*g,b=h*m*l-p*u*l+p*o*d-n*m*d-h*o*g+n*u*g,_=p*u*a-h*m*a-p*o*c+n*m*c+h*o*f-n*u*f,w=t*y+s*x+i*b+r*_;if(0===w)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const v=1/w;return e[0]=y*v,e[1]=(m*c*r-u*f*r-m*i*d+s*f*d+u*i*g-s*c*g)*v,e[2]=(o*f*r-m*a*r+m*i*l-s*f*l-o*i*g+s*a*g)*v,e[3]=(u*a*r-o*c*r-u*i*l+s*c*l+o*i*d-s*a*d)*v,e[4]=x*v,e[5]=(h*f*r-p*c*r+p*i*d-t*f*d-h*i*g+t*c*g)*v,e[6]=(p*a*r-n*f*r-p*i*l+t*f*l+n*i*g-t*a*g)*v,e[7]=(n*c*r-h*a*r+h*i*l-t*c*l-n*i*d+t*a*d)*v,e[8]=b*v,e[9]=(p*u*r-h*m*r-p*s*d+t*m*d+h*s*g-t*u*g)*v,e[10]=(n*m*r-p*o*r+p*s*l-t*m*l-n*s*g+t*o*g)*v,e[11]=(h*o*r-n*u*r-h*s*l+t*u*l+n*s*d-t*o*d)*v,e[12]=_*v,e[13]=(h*m*i-p*u*i+p*s*c-t*m*c-h*s*f+t*u*f)*v,e[14]=(p*o*i-n*m*i-p*s*a+t*m*a+n*s*f-t*o*f)*v,e[15]=(n*u*i-h*o*i+h*s*a-t*u*a-n*s*c+t*o*c)*v,this}scale(e){const t=this.elements,s=e.x,i=e.y,r=e.z;return t[0]*=s,t[4]*=i,t[8]*=r,t[1]*=s,t[5]*=i,t[9]*=r,t[2]*=s,t[6]*=i,t[10]*=r,t[3]*=s,t[7]*=i,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],s=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,s,i))}makeTranslation(e,t,s){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,s,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),s=Math.sin(e);return this.set(1,0,0,0,0,t,-s,0,0,s,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,0,s,0,0,1,0,0,-s,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,0,s,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const s=Math.cos(t),i=Math.sin(t),r=1-s,n=e.x,o=e.y,a=e.z,l=r*n,h=r*o;return this.set(l*n+s,l*o-i*a,l*a+i*o,0,l*o+i*a,h*o+s,h*a-i*n,0,l*a-i*o,h*a+i*n,r*a*a+s,0,0,0,0,1),this}makeScale(e,t,s){return this.set(e,0,0,0,0,t,0,0,0,0,s,0,0,0,0,1),this}makeShear(e,t,s,i,r,n){return this.set(1,s,r,0,e,1,n,0,t,i,1,0,0,0,0,1),this}compose(e,t,s){const i=this.elements,r=t._x,n=t._y,o=t._z,a=t._w,l=r+r,h=n+n,u=o+o,c=r*l,d=r*h,p=r*u,m=n*h,f=n*u,g=o*u,y=a*l,x=a*h,b=a*u,_=s.x,w=s.y,v=s.z;return i[0]=(1-(m+g))*_,i[1]=(d+b)*_,i[2]=(p-x)*_,i[3]=0,i[4]=(d-b)*w,i[5]=(1-(c+g))*w,i[6]=(f+y)*w,i[7]=0,i[8]=(p+x)*v,i[9]=(f-y)*v,i[10]=(1-(c+m))*v,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,s){const i=this.elements;if(e.x=i[12],e.y=i[13],e.z=i[14],0===this.determinant())return s.set(1,1,1),t.identity(),this;let r=hl.set(i[0],i[1],i[2]).length();const n=hl.set(i[4],i[5],i[6]).length(),o=hl.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),ul.copy(this);const a=1/r,l=1/n,h=1/o;return ul.elements[0]*=a,ul.elements[1]*=a,ul.elements[2]*=a,ul.elements[4]*=l,ul.elements[5]*=l,ul.elements[6]*=l,ul.elements[8]*=h,ul.elements[9]*=h,ul.elements[10]*=h,t.setFromRotationMatrix(ul),s.x=r,s.y=n,s.z=o,this}makePerspective(e,t,s,i,r,n,o=2e3,a=!1){const l=this.elements,h=2*r/(t-e),u=2*r/(s-i),c=(t+e)/(t-e),d=(s+i)/(s-i);let p,m;if(a)p=r/(n-r),m=n*r/(n-r);else if(o===ko)p=-(n+r)/(n-r),m=-2*n*r/(n-r);else{if(o!==Uo)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);p=-n/(n-r),m=-n*r/(n-r)}return l[0]=h,l[4]=0,l[8]=c,l[12]=0,l[1]=0,l[5]=u,l[9]=d,l[13]=0,l[2]=0,l[6]=0,l[10]=p,l[14]=m,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,s,i,r,n,o=2e3,a=!1){const l=this.elements,h=2/(t-e),u=2/(s-i),c=-(t+e)/(t-e),d=-(s+i)/(s-i);let p,m;if(a)p=1/(n-r),m=n/(n-r);else if(o===ko)p=-2/(n-r),m=-(n+r)/(n-r);else{if(o!==Uo)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);p=-1/(n-r),m=-r/(n-r)}return l[0]=h,l[4]=0,l[8]=0,l[12]=c,l[1]=0,l[5]=u,l[9]=0,l[13]=d,l[2]=0,l[6]=0,l[10]=p,l[14]=m,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const t=this.elements,s=e.elements;for(let e=0;e<16;e++)if(t[e]!==s[e])return!1;return!0}fromArray(e,t=0){for(let s=0;s<16;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e[t+9]=s[9],e[t+10]=s[10],e[t+11]=s[11],e[t+12]=s[12],e[t+13]=s[13],e[t+14]=s[14],e[t+15]=s[15],e}}const hl=new da,ul=new ll,cl=new da(0,0,0),dl=new da(1,1,1),pl=new da,ml=new da,fl=new da,gl=new ll,yl=new ca;class xl{constructor(e=0,t=0,s=0,i=xl.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=s,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,s,i=this._order){return this._x=e,this._y=t,this._z=s,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,s=!0){const i=e.elements,r=i[0],n=i[4],o=i[8],a=i[1],l=i[5],h=i[9],u=i[2],c=i[6],d=i[10];switch(t){case"XYZ":this._y=Math.asin(ra(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-h,d),this._z=Math.atan2(-n,r)):(this._x=Math.atan2(c,l),this._z=0);break;case"YXZ":this._x=Math.asin(-ra(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(o,d),this._z=Math.atan2(a,l)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(ra(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(-u,d),this._z=Math.atan2(-n,l)):(this._y=0,this._z=Math.atan2(a,r));break;case"ZYX":this._y=Math.asin(-ra(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(c,d),this._z=Math.atan2(a,r)):(this._x=0,this._z=Math.atan2(-n,l));break;case"YZX":this._z=Math.asin(ra(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-h,l),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(o,d));break;case"XZY":this._z=Math.asin(-ra(n,-1,1)),Math.abs(n)<.9999999?(this._x=Math.atan2(c,l),this._y=Math.atan2(o,r)):(this._x=Math.atan2(-h,d),this._y=0);break;default:Yo("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===s&&this._onChangeCallback(),this}setFromQuaternion(e,t,s){return gl.makeRotationFromQuaternion(e),this.setFromRotationMatrix(gl,t,s)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return yl.setFromEuler(this),this.setFromQuaternion(yl,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],void 0!==e[3]&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}xl.DEFAULT_ORDER="XYZ";class bl{constructor(){this.mask=1}set(e){this.mask=1<<e>>>0}enable(e){this.mask|=1<<e}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e}disable(e){this.mask&=~(1<<e)}disableAll(){this.mask=0}test(e){return 0!==(this.mask&e.mask)}isEnabled(e){return!!(this.mask&1<<e)}}let _l=0;const wl=new da,vl=new ca,Tl=new ll,Sl=new da,Ml=new da,Al=new da,Nl=new ca,El=new da(1,0,0),Cl=new da(0,1,0),Rl=new da(0,0,1),Pl={type:"added"},Bl={type:"removed"},Il={type:"childadded",child:null},Dl={type:"childremoved",child:null};class Ll extends Ko{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:_l++}),this.uuid=ia(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Ll.DEFAULT_UP.clone();const e=new da,t=new xl,s=new ca,i=new da(1,1,1);t._onChange(function(){s.setFromEuler(t,!1)}),s._onChange(function(){t.setFromQuaternion(s,void 0,!1)}),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:s},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new ll},normalMatrix:{value:new fa}}),this.matrix=new ll,this.matrixWorld=new ll,this.matrixAutoUpdate=Ll.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Ll.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new bl,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return vl.setFromAxisAngle(e,t),this.quaternion.multiply(vl),this}rotateOnWorldAxis(e,t){return vl.setFromAxisAngle(e,t),this.quaternion.premultiply(vl),this}rotateX(e){return this.rotateOnAxis(El,e)}rotateY(e){return this.rotateOnAxis(Cl,e)}rotateZ(e){return this.rotateOnAxis(Rl,e)}translateOnAxis(e,t){return wl.copy(e).applyQuaternion(this.quaternion),this.position.add(wl.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(El,e)}translateY(e){return this.translateOnAxis(Cl,e)}translateZ(e){return this.translateOnAxis(Rl,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Tl.copy(this.matrixWorld).invert())}lookAt(e,t,s){e.isVector3?Sl.copy(e):Sl.set(e,t,s);const i=this.parent;this.updateWorldMatrix(!0,!1),Ml.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Tl.lookAt(Ml,Sl,this.up):Tl.lookAt(Sl,Ml,this.up),this.quaternion.setFromRotationMatrix(Tl),i&&(Tl.extractRotation(i.matrixWorld),vl.setFromRotationMatrix(Tl),this.quaternion.premultiply(vl.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(Zo("Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(Pl),Il.child=e,this.dispatchEvent(Il),Il.child=null):Zo("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.remove(arguments[e]);return this}const t=this.children.indexOf(e);return-1!==t&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(Bl),Dl.child=e,this.dispatchEvent(Dl),Dl.child=null),this}removeFromParent(){const e=this.parent;return null!==e&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),Tl.copy(this.matrixWorld).invert(),null!==e.parent&&(e.parent.updateWorldMatrix(!0,!1),Tl.multiply(e.parent.matrixWorld)),e.applyMatrix4(Tl),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Pl),Il.child=e,this.dispatchEvent(Il),Il.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let s=0,i=this.children.length;s<i;s++){const i=this.children[s].getObjectByProperty(e,t);if(void 0!==i)return i}}getObjectsByProperty(e,t,s=[]){this[e]===t&&s.push(this);const i=this.children;for(let r=0,n=i.length;r<n;r++)i[r].getObjectsByProperty(e,t,s);return s}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Ml,e,Al),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Ml,Nl,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].traverse(e)}traverseVisible(e){if(!1===this.visible)return;e(this);const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].traverseVisible(e)}traverseAncestors(e){const t=this.parent;null!==t&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let s=0,i=t.length;s<i;s++){t[s].updateMatrixWorld(e)}}updateWorldMatrix(e,t){const s=this.parent;if(!0===e&&null!==s&&s.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),!0===t){const e=this.children;for(let t=0,s=e.length;t<s;t++){e[t].updateWorldMatrix(!1,!0)}}}toJSON(e){const t=void 0===e||"string"==typeof e,s={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},s.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const i={};function r(t,s){return void 0===t[s.uuid]&&(t[s.uuid]=s.toJSON(e)),s.uuid}if(i.uuid=this.uuid,i.type=this.type,""!==this.name&&(i.name=this.name),!0===this.castShadow&&(i.castShadow=!0),!0===this.receiveShadow&&(i.receiveShadow=!0),!1===this.visible&&(i.visible=!1),!1===this.frustumCulled&&(i.frustumCulled=!1),0!==this.renderOrder&&(i.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(e=>({...e})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(e),i.indirectTexture=this._indirectTexture.toJSON(e),null!==this._colorsTexture&&(i.colorsTexture=this._colorsTexture.toJSON(e)),null!==this.boundingSphere&&(i.boundingSphere=this.boundingSphere.toJSON()),null!==this.boundingBox&&(i.boundingBox=this.boundingBox.toJSON())),this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);const t=this.geometry.parameters;if(void 0!==t&&void 0!==t.shapes){const s=t.shapes;if(Array.isArray(s))for(let t=0,i=s.length;t<i;t++){const i=s[t];r(e.shapes,i)}else r(e.shapes,s)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),void 0!==this.skeleton&&(r(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),void 0!==this.material)if(Array.isArray(this.material)){const t=[];for(let s=0,i=this.material.length;s<i;s++)t.push(r(e.materials,this.material[s]));i.material=t}else i.material=r(e.materials,this.material);if(this.children.length>0){i.children=[];for(let t=0;t<this.children.length;t++)i.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let t=0;t<this.animations.length;t++){const s=this.animations[t];i.animations.push(r(e.animations,s))}}if(t){const t=n(e.geometries),i=n(e.materials),r=n(e.textures),o=n(e.images),a=n(e.shapes),l=n(e.skeletons),h=n(e.animations),u=n(e.nodes);t.length>0&&(s.geometries=t),i.length>0&&(s.materials=i),r.length>0&&(s.textures=r),o.length>0&&(s.images=o),a.length>0&&(s.shapes=a),l.length>0&&(s.skeletons=l),h.length>0&&(s.animations=h),u.length>0&&(s.nodes=u)}return s.object=i,s;function n(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}}clone(e){return(new this.constructor).copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),!0===t)for(let t=0;t<e.children.length;t++){const s=e.children[t];this.add(s.clone())}return this}}Ll.DEFAULT_UP=new da(0,1,0),Ll.DEFAULT_MATRIX_AUTO_UPDATE=!0,Ll.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Fl=new da,Ol=new da,Vl=new da,zl=new da,kl=new da,Ul=new da,Gl=new da,jl=new da,$l=new da,Wl=new da,Hl=new Pa,ql=new Pa,Xl=new Pa;class Yl{constructor(e=new da,t=new da,s=new da){this.a=e,this.b=t,this.c=s}static getNormal(e,t,s,i){i.subVectors(s,t),Fl.subVectors(e,t),i.cross(Fl);const r=i.lengthSq();return r>0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,s,i,r){Fl.subVectors(i,t),Ol.subVectors(s,t),Vl.subVectors(e,t);const n=Fl.dot(Fl),o=Fl.dot(Ol),a=Fl.dot(Vl),l=Ol.dot(Ol),h=Ol.dot(Vl),u=n*l-o*o;if(0===u)return r.set(0,0,0),null;const c=1/u,d=(l*a-o*h)*c,p=(n*h-o*a)*c;return r.set(1-d-p,p,d)}static containsPoint(e,t,s,i){return null!==this.getBarycoord(e,t,s,i,zl)&&(zl.x>=0&&zl.y>=0&&zl.x+zl.y<=1)}static getInterpolation(e,t,s,i,r,n,o,a){return null===this.getBarycoord(e,t,s,i,zl)?(a.x=0,a.y=0,"z"in a&&(a.z=0),"w"in a&&(a.w=0),null):(a.setScalar(0),a.addScaledVector(r,zl.x),a.addScaledVector(n,zl.y),a.addScaledVector(o,zl.z),a)}static getInterpolatedAttribute(e,t,s,i,r,n){return Hl.setScalar(0),ql.setScalar(0),Xl.setScalar(0),Hl.fromBufferAttribute(e,t),ql.fromBufferAttribute(e,s),Xl.fromBufferAttribute(e,i),n.setScalar(0),n.addScaledVector(Hl,r.x),n.addScaledVector(ql,r.y),n.addScaledVector(Xl,r.z),n}static isFrontFacing(e,t,s,i){return Fl.subVectors(s,t),Ol.subVectors(e,t),Fl.cross(Ol).dot(i)<0}set(e,t,s){return this.a.copy(e),this.b.copy(t),this.c.copy(s),this}setFromPointsAndIndices(e,t,s,i){return this.a.copy(e[t]),this.b.copy(e[s]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,s,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,s),this.c.fromBufferAttribute(e,i),this}clone(){return(new this.constructor).copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Fl.subVectors(this.c,this.b),Ol.subVectors(this.a,this.b),.5*Fl.cross(Ol).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Yl.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Yl.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,s,i,r){return Yl.getInterpolation(e,this.a,this.b,this.c,t,s,i,r)}containsPoint(e){return Yl.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Yl.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const s=this.a,i=this.b,r=this.c;let n,o;kl.subVectors(i,s),Ul.subVectors(r,s),jl.subVectors(e,s);const a=kl.dot(jl),l=Ul.dot(jl);if(a<=0&&l<=0)return t.copy(s);$l.subVectors(e,i);const h=kl.dot($l),u=Ul.dot($l);if(h>=0&&u<=h)return t.copy(i);const c=a*u-h*l;if(c<=0&&a>=0&&h<=0)return n=a/(a-h),t.copy(s).addScaledVector(kl,n);Wl.subVectors(e,r);const d=kl.dot(Wl),p=Ul.dot(Wl);if(p>=0&&d<=p)return t.copy(r);const m=d*l-a*p;if(m<=0&&l>=0&&p<=0)return o=l/(l-p),t.copy(s).addScaledVector(Ul,o);const f=h*p-d*u;if(f<=0&&u-h>=0&&d-p>=0)return Gl.subVectors(r,i),o=(u-h)/(u-h+(d-p)),t.copy(i).addScaledVector(Gl,o);const g=1/(f+m+c);return n=m*g,o=c*g,t.copy(s).addScaledVector(kl,n).addScaledVector(Ul,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const Zl={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},Ql={h:0,s:0,l:0},Kl={h:0,s:0,l:0};function Jl(e,t,s){return s<0&&(s+=1),s>1&&(s-=1),s<1/6?e+6*(t-e)*s:s<.5?t:s<2/3?e+6*(t-e)*(2/3-s):e}class eh{constructor(e,t,s){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,s)}set(e,t,s){if(void 0===t&&void 0===s){const t=e;t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t)}else this.setRGB(e,t,s);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Mo){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,_a.colorSpaceToWorking(this,t),this}setRGB(e,t,s,i=_a.workingColorSpace){return this.r=e,this.g=t,this.b=s,_a.colorSpaceToWorking(this,i),this}setHSL(e,t,s,i=_a.workingColorSpace){if(e=na(e,1),t=ra(t,0,1),s=ra(s,0,1),0===t)this.r=this.g=this.b=s;else{const i=s<=.5?s*(1+t):s+t-s*t,r=2*s-i;this.r=Jl(r,i,e+1/3),this.g=Jl(r,i,e),this.b=Jl(r,i,e-1/3)}return _a.colorSpaceToWorking(this,i),this}setStyle(e,t=Mo){function s(t){void 0!==t&&parseFloat(t)<1&&Yo("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const n=i[1],o=i[2];switch(n){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:Yo("Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=i[1],r=s.length;if(3===r)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(6===r)return this.setHex(parseInt(s,16),t);Yo("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Mo){const s=Zl[e.toLowerCase()];return void 0!==s?this.setHex(s,t):Yo("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=wa(e.r),this.g=wa(e.g),this.b=wa(e.b),this}copyLinearToSRGB(e){return this.r=va(e.r),this.g=va(e.g),this.b=va(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Mo){return _a.workingToColorSpace(th.copy(this),e),65536*Math.round(ra(255*th.r,0,255))+256*Math.round(ra(255*th.g,0,255))+Math.round(ra(255*th.b,0,255))}getHexString(e=Mo){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=_a.workingColorSpace){_a.workingToColorSpace(th.copy(this),t);const s=th.r,i=th.g,r=th.b,n=Math.max(s,i,r),o=Math.min(s,i,r);let a,l;const h=(o+n)/2;if(o===n)a=0,l=0;else{const e=n-o;switch(l=h<=.5?e/(n+o):e/(2-n-o),n){case s:a=(i-r)/e+(i<r?6:0);break;case i:a=(r-s)/e+2;break;case r:a=(s-i)/e+4}a/=6}return e.h=a,e.s=l,e.l=h,e}getRGB(e,t=_a.workingColorSpace){return _a.workingToColorSpace(th.copy(this),t),e.r=th.r,e.g=th.g,e.b=th.b,e}getStyle(e=Mo){_a.workingToColorSpace(th.copy(this),e);const t=th.r,s=th.g,i=th.b;return e!==Mo?`color(${e} ${t.toFixed(3)} ${s.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(255*t)},${Math.round(255*s)},${Math.round(255*i)})`}offsetHSL(e,t,s){return this.getHSL(Ql),this.setHSL(Ql.h+e,Ql.s+t,Ql.l+s)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,s){return this.r=e.r+(t.r-e.r)*s,this.g=e.g+(t.g-e.g)*s,this.b=e.b+(t.b-e.b)*s,this}lerpHSL(e,t){this.getHSL(Ql),e.getHSL(Kl);const s=oa(Ql.h,Kl.h,t),i=oa(Ql.s,Kl.s,t),r=oa(Ql.l,Kl.l,t);return this.setHSL(s,i,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,s=this.g,i=this.b,r=e.elements;return this.r=r[0]*t+r[3]*s+r[6]*i,this.g=r[1]*t+r[4]*s+r[7]*i,this.b=r[2]*t+r[5]*s+r[8]*i,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const th=new eh;eh.NAMES=Zl;let sh=0;class ih extends Ko{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:sh++}),this.uuid=ia(),this.name="",this.type="Material",this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=sn,this.blendDst=rn,this.blendEquation=Yr,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new eh(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Co,this.stencilZFail=Co,this.stencilZPass=Co,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(void 0!==e)for(const t in e){const s=e[t];if(void 0===s){Yo(`Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&i.isColor?i.set(s):i&&i.isVector3&&s&&s.isVector3?i.copy(s):this[t]=s:Yo(`Material: '${t}' is not a property of THREE.${this.type}.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{}});const s={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};function i(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(s.uuid=this.uuid,s.type=this.type,""!==this.name&&(s.name=this.name),this.color&&this.color.isColor&&(s.color=this.color.getHex()),void 0!==this.roughness&&(s.roughness=this.roughness),void 0!==this.metalness&&(s.metalness=this.metalness),void 0!==this.sheen&&(s.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(s.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(s.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(s.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(s.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(s.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(s.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(s.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(s.shininess=this.shininess),void 0!==this.clearcoat&&(s.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(s.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(s.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(s.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(s.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,s.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(s.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(s.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),void 0!==this.dispersion&&(s.dispersion=this.dispersion),void 0!==this.iridescence&&(s.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(s.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(s.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(s.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(s.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),void 0!==this.anisotropy&&(s.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(s.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(s.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(s.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(s.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(s.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(s.lightMap=this.lightMap.toJSON(e).uuid,s.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(s.aoMap=this.aoMap.toJSON(e).uuid,s.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(s.bumpMap=this.bumpMap.toJSON(e).uuid,s.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(s.normalMap=this.normalMap.toJSON(e).uuid,s.normalMapType=this.normalMapType,s.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(s.displacementMap=this.displacementMap.toJSON(e).uuid,s.displacementScale=this.displacementScale,s.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(s.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(s.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(s.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(s.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(s.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(s.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(s.envMap=this.envMap.toJSON(e).uuid,void 0!==this.combine&&(s.combine=this.combine)),void 0!==this.envMapRotation&&(s.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(s.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(s.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(s.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(s.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.transmission&&(s.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(s.transmissionMap=this.transmissionMap.toJSON(e).uuid),void 0!==this.thickness&&(s.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(s.thicknessMap=this.thicknessMap.toJSON(e).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(s.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(s.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(s.size=this.size),null!==this.shadowSide&&(s.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(s.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(s.blending=this.blending),0!==this.side&&(s.side=this.side),!0===this.vertexColors&&(s.vertexColors=!0),this.opacity<1&&(s.opacity=this.opacity),!0===this.transparent&&(s.transparent=!0),this.blendSrc!==sn&&(s.blendSrc=this.blendSrc),this.blendDst!==rn&&(s.blendDst=this.blendDst),this.blendEquation!==Yr&&(s.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(s.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(s.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(s.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(s.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(s.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(s.depthFunc=this.depthFunc),!1===this.depthTest&&(s.depthTest=this.depthTest),!1===this.depthWrite&&(s.depthWrite=this.depthWrite),!1===this.colorWrite&&(s.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(s.stencilWriteMask=this.stencilWriteMask),519!==this.stencilFunc&&(s.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(s.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(s.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Co&&(s.stencilFail=this.stencilFail),this.stencilZFail!==Co&&(s.stencilZFail=this.stencilZFail),this.stencilZPass!==Co&&(s.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(s.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(s.rotation=this.rotation),!0===this.polygonOffset&&(s.polygonOffset=!0),0!==this.polygonOffsetFactor&&(s.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(s.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(s.linewidth=this.linewidth),void 0!==this.dashSize&&(s.dashSize=this.dashSize),void 0!==this.gapSize&&(s.gapSize=this.gapSize),void 0!==this.scale&&(s.scale=this.scale),!0===this.dithering&&(s.dithering=!0),this.alphaTest>0&&(s.alphaTest=this.alphaTest),!0===this.alphaHash&&(s.alphaHash=!0),!0===this.alphaToCoverage&&(s.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(s.premultipliedAlpha=!0),!0===this.forceSinglePass&&(s.forceSinglePass=!0),!1===this.allowOverride&&(s.allowOverride=!1),!0===this.wireframe&&(s.wireframe=!0),this.wireframeLinewidth>1&&(s.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(s.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(s.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(s.flatShading=!0),!1===this.visible&&(s.visible=!1),!1===this.toneMapped&&(s.toneMapped=!1),!1===this.fog&&(s.fog=!1),Object.keys(this.userData).length>0&&(s.userData=this.userData),t){const t=i(e.textures),r=i(e.images);t.length>0&&(s.textures=t),r.length>0&&(s.images=r)}return s}clone(){return(new this.constructor).copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let s=null;if(null!==t){const e=t.length;s=new Array(e);for(let i=0;i!==e;++i)s[i]=t[i].clone()}return this.clippingPlanes=s,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}}class rh extends ih{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new eh(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new xl,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const nh=oh();function oh(){const e=new ArrayBuffer(4),t=new Float32Array(e),s=new Uint32Array(e),i=new Uint32Array(512),r=new Uint32Array(512);for(let e=0;e<256;++e){const t=e-127;t<-27?(i[e]=0,i[256|e]=32768,r[e]=24,r[256|e]=24):t<-14?(i[e]=1024>>-t-14,i[256|e]=1024>>-t-14|32768,r[e]=-t-1,r[256|e]=-t-1):t<=15?(i[e]=t+15<<10,i[256|e]=t+15<<10|32768,r[e]=13,r[256|e]=13):t<128?(i[e]=31744,i[256|e]=64512,r[e]=24,r[256|e]=24):(i[e]=31744,i[256|e]=64512,r[e]=13,r[256|e]=13)}const n=new Uint32Array(2048),o=new Uint32Array(64),a=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,s=0;for(;!(8388608&t);)t<<=1,s-=8388608;t&=-8388609,s+=947912704,n[e]=t|s}for(let e=1024;e<2048;++e)n[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)o[e]=e<<23;o[31]=1199570944,o[32]=2147483648;for(let e=33;e<63;++e)o[e]=2147483648+(e-32<<23);o[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(a[e]=1024);return{floatView:t,uint32View:s,baseTable:i,shiftTable:r,mantissaTable:n,exponentTable:o,offsetTable:a}}function ah(e){Math.abs(e)>65504&&Yo("DataUtils.toHalfFloat(): Value out of range."),e=ra(e,-65504,65504),nh.floatView[0]=e;const t=nh.uint32View[0],s=t>>23&511;return nh.baseTable[s]+((8388607&t)>>nh.shiftTable[s])}function lh(e){const t=e>>10;return nh.uint32View[0]=nh.mantissaTable[nh.offsetTable[t]+(1023&e)]+nh.exponentTable[t],nh.floatView[0]}const hh=new da,uh=new ua;let ch=0;class dh{constructor(e,t,s=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:ch++}),this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=s,this.usage=Vo,this.updateRanges=[],this.gpuType=Nn,this.version=0}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,s){e*=this.itemSize,s*=t.itemSize;for(let i=0,r=this.itemSize;i<r;i++)this.array[e+i]=t.array[s+i];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(2===this.itemSize)for(let t=0,s=this.count;t<s;t++)uh.fromBufferAttribute(this,t),uh.applyMatrix3(e),this.setXY(t,uh.x,uh.y);else if(3===this.itemSize)for(let t=0,s=this.count;t<s;t++)hh.fromBufferAttribute(this,t),hh.applyMatrix3(e),this.setXYZ(t,hh.x,hh.y,hh.z);return this}applyMatrix4(e){for(let t=0,s=this.count;t<s;t++)hh.fromBufferAttribute(this,t),hh.applyMatrix4(e),this.setXYZ(t,hh.x,hh.y,hh.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)hh.fromBufferAttribute(this,t),hh.applyNormalMatrix(e),this.setXYZ(t,hh.x,hh.y,hh.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)hh.fromBufferAttribute(this,t),hh.transformDirection(e),this.setXYZ(t,hh.x,hh.y,hh.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let s=this.array[e*this.itemSize+t];return this.normalized&&(s=aa(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=la(s,this.array)),this.array[e*this.itemSize+t]=s,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=aa(t,this.array)),t}setX(e,t){return this.normalized&&(t=la(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=aa(t,this.array)),t}setY(e,t){return this.normalized&&(t=la(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=aa(t,this.array)),t}setZ(e,t){return this.normalized&&(t=la(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=aa(t,this.array)),t}setW(e,t){return this.normalized&&(t=la(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=la(t,this.array),s=la(s,this.array)),this.array[e+0]=t,this.array[e+1]=s,this}setXYZ(e,t,s,i){return e*=this.itemSize,this.normalized&&(t=la(t,this.array),s=la(s,this.array),i=la(i,this.array)),this.array[e+0]=t,this.array[e+1]=s,this.array[e+2]=i,this}setXYZW(e,t,s,i,r){return e*=this.itemSize,this.normalized&&(t=la(t,this.array),s=la(s,this.array),i=la(i,this.array),r=la(r,this.array)),this.array[e+0]=t,this.array[e+1]=s,this.array[e+2]=i,this.array[e+3]=r,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return""!==this.name&&(e.name=this.name),this.usage!==Vo&&(e.usage=this.usage),e}}class ph extends dh{constructor(e,t,s){super(new Uint16Array(e),t,s)}}class mh extends dh{constructor(e,t,s){super(new Uint32Array(e),t,s)}}class fh extends dh{constructor(e,t,s){super(new Uint16Array(e),t,s),this.isFloat16BufferAttribute=!0}getX(e){let t=lh(this.array[e*this.itemSize]);return this.normalized&&(t=aa(t,this.array)),t}setX(e,t){return this.normalized&&(t=la(t,this.array)),this.array[e*this.itemSize]=ah(t),this}getY(e){let t=lh(this.array[e*this.itemSize+1]);return this.normalized&&(t=aa(t,this.array)),t}setY(e,t){return this.normalized&&(t=la(t,this.array)),this.array[e*this.itemSize+1]=ah(t),this}getZ(e){let t=lh(this.array[e*this.itemSize+2]);return this.normalized&&(t=aa(t,this.array)),t}setZ(e,t){return this.normalized&&(t=la(t,this.array)),this.array[e*this.itemSize+2]=ah(t),this}getW(e){let t=lh(this.array[e*this.itemSize+3]);return this.normalized&&(t=aa(t,this.array)),t}setW(e,t){return this.normalized&&(t=la(t,this.array)),this.array[e*this.itemSize+3]=ah(t),this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=la(t,this.array),s=la(s,this.array)),this.array[e+0]=ah(t),this.array[e+1]=ah(s),this}setXYZ(e,t,s,i){return e*=this.itemSize,this.normalized&&(t=la(t,this.array),s=la(s,this.array),i=la(i,this.array)),this.array[e+0]=ah(t),this.array[e+1]=ah(s),this.array[e+2]=ah(i),this}setXYZW(e,t,s,i,r){return e*=this.itemSize,this.normalized&&(t=la(t,this.array),s=la(s,this.array),i=la(i,this.array),r=la(r,this.array)),this.array[e+0]=ah(t),this.array[e+1]=ah(s),this.array[e+2]=ah(i),this.array[e+3]=ah(r),this}}class gh extends dh{constructor(e,t,s){super(new Float32Array(e),t,s)}}let yh=0;const xh=new ll,bh=new Ll,_h=new da,wh=new La,vh=new La,Th=new da;class Sh extends Ko{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:yh++}),this.uuid=ia(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new($o(e)?mh:ph)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return void 0!==this.attributes[e]}addGroup(e,t,s=0){this.groups.push({start:e,count:t,materialIndex:s})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;void 0!==t&&(t.applyMatrix4(e),t.needsUpdate=!0);const s=this.attributes.normal;if(void 0!==s){const t=(new fa).getNormalMatrix(e);s.applyNormalMatrix(t),s.needsUpdate=!0}const i=this.attributes.tangent;return void 0!==i&&(i.transformDirection(e),i.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}applyQuaternion(e){return xh.makeRotationFromQuaternion(e),this.applyMatrix4(xh),this}rotateX(e){return xh.makeRotationX(e),this.applyMatrix4(xh),this}rotateY(e){return xh.makeRotationY(e),this.applyMatrix4(xh),this}rotateZ(e){return xh.makeRotationZ(e),this.applyMatrix4(xh),this}translate(e,t,s){return xh.makeTranslation(e,t,s),this.applyMatrix4(xh),this}scale(e,t,s){return xh.makeScale(e,t,s),this.applyMatrix4(xh),this}lookAt(e){return bh.lookAt(e),bh.updateMatrix(),this.applyMatrix4(bh.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(_h).negate(),this.translate(_h.x,_h.y,_h.z),this}setFromPoints(e){const t=this.getAttribute("position");if(void 0===t){const t=[];for(let s=0,i=e.length;s<i;s++){const i=e[s];t.push(i.x,i.y,i.z||0)}this.setAttribute("position",new gh(t,3))}else{const s=Math.min(e.length,t.count);for(let i=0;i<s;i++){const s=e[i];t.setXYZ(i,s.x,s.y,s.z||0)}e.length>t.count&&Yo("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new La);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return Zo("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new da(-1/0,-1/0,-1/0),new da(1/0,1/0,1/0));if(void 0!==e){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,s=t.length;e<s;e++){const s=t[e];wh.setFromBufferAttribute(s),this.morphTargetsRelative?(Th.addVectors(this.boundingBox.min,wh.min),this.boundingBox.expandByPoint(Th),Th.addVectors(this.boundingBox.max,wh.max),this.boundingBox.expandByPoint(Th)):(this.boundingBox.expandByPoint(wh.min),this.boundingBox.expandByPoint(wh.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&Zo('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){null===this.boundingSphere&&(this.boundingSphere=new Ja);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return Zo("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),void this.boundingSphere.set(new da,1/0);if(e){const s=this.boundingSphere.center;if(wh.setFromBufferAttribute(e),t)for(let e=0,s=t.length;e<s;e++){const s=t[e];vh.setFromBufferAttribute(s),this.morphTargetsRelative?(Th.addVectors(wh.min,vh.min),wh.expandByPoint(Th),Th.addVectors(wh.max,vh.max),wh.expandByPoint(Th)):(wh.expandByPoint(vh.min),wh.expandByPoint(vh.max))}wh.getCenter(s);let i=0;for(let t=0,r=e.count;t<r;t++)Th.fromBufferAttribute(e,t),i=Math.max(i,s.distanceToSquared(Th));if(t)for(let r=0,n=t.length;r<n;r++){const n=t[r],o=this.morphTargetsRelative;for(let t=0,r=n.count;t<r;t++)Th.fromBufferAttribute(n,t),o&&(_h.fromBufferAttribute(e,t),Th.add(_h)),i=Math.max(i,s.distanceToSquared(Th))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&Zo('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(null===e||void 0===t.position||void 0===t.normal||void 0===t.uv)return void Zo("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");const s=t.position,i=t.normal,r=t.uv;!1===this.hasAttribute("tangent")&&this.setAttribute("tangent",new dh(new Float32Array(4*s.count),4));const n=this.getAttribute("tangent"),o=[],a=[];for(let e=0;e<s.count;e++)o[e]=new da,a[e]=new da;const l=new da,h=new da,u=new da,c=new ua,d=new ua,p=new ua,m=new da,f=new da;function g(e,t,i){l.fromBufferAttribute(s,e),h.fromBufferAttribute(s,t),u.fromBufferAttribute(s,i),c.fromBufferAttribute(r,e),d.fromBufferAttribute(r,t),p.fromBufferAttribute(r,i),h.sub(l),u.sub(l),d.sub(c),p.sub(c);const n=1/(d.x*p.y-p.x*d.y);isFinite(n)&&(m.copy(h).multiplyScalar(p.y).addScaledVector(u,-d.y).multiplyScalar(n),f.copy(u).multiplyScalar(d.x).addScaledVector(h,-p.x).multiplyScalar(n),o[e].add(m),o[t].add(m),o[i].add(m),a[e].add(f),a[t].add(f),a[i].add(f))}let y=this.groups;0===y.length&&(y=[{start:0,count:e.count}]);for(let t=0,s=y.length;t<s;++t){const s=y[t],i=s.start;for(let t=i,r=i+s.count;t<r;t+=3)g(e.getX(t+0),e.getX(t+1),e.getX(t+2))}const x=new da,b=new da,_=new da,w=new da;function v(e){_.fromBufferAttribute(i,e),w.copy(_);const t=o[e];x.copy(t),x.sub(_.multiplyScalar(_.dot(t))).normalize(),b.crossVectors(w,t);const s=b.dot(a[e])<0?-1:1;n.setXYZW(e,x.x,x.y,x.z,s)}for(let t=0,s=y.length;t<s;++t){const s=y[t],i=s.start;for(let t=i,r=i+s.count;t<r;t+=3)v(e.getX(t+0)),v(e.getX(t+1)),v(e.getX(t+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(void 0!==t){let s=this.getAttribute("normal");if(void 0===s)s=new dh(new Float32Array(3*t.count),3),this.setAttribute("normal",s);else for(let e=0,t=s.count;e<t;e++)s.setXYZ(e,0,0,0);const i=new da,r=new da,n=new da,o=new da,a=new da,l=new da,h=new da,u=new da;if(e)for(let c=0,d=e.count;c<d;c+=3){const d=e.getX(c+0),p=e.getX(c+1),m=e.getX(c+2);i.fromBufferAttribute(t,d),r.fromBufferAttribute(t,p),n.fromBufferAttribute(t,m),h.subVectors(n,r),u.subVectors(i,r),h.cross(u),o.fromBufferAttribute(s,d),a.fromBufferAttribute(s,p),l.fromBufferAttribute(s,m),o.add(h),a.add(h),l.add(h),s.setXYZ(d,o.x,o.y,o.z),s.setXYZ(p,a.x,a.y,a.z),s.setXYZ(m,l.x,l.y,l.z)}else for(let e=0,o=t.count;e<o;e+=3)i.fromBufferAttribute(t,e+0),r.fromBufferAttribute(t,e+1),n.fromBufferAttribute(t,e+2),h.subVectors(n,r),u.subVectors(i,r),h.cross(u),s.setXYZ(e+0,h.x,h.y,h.z),s.setXYZ(e+1,h.x,h.y,h.z),s.setXYZ(e+2,h.x,h.y,h.z);this.normalizeNormals(),s.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,s=e.count;t<s;t++)Th.fromBufferAttribute(e,t),Th.normalize(),e.setXYZ(t,Th.x,Th.y,Th.z)}toNonIndexed(){function e(e,t){const s=e.array,i=e.itemSize,r=e.normalized,n=new s.constructor(t.length*i);let o=0,a=0;for(let r=0,l=t.length;r<l;r++){o=e.isInterleavedBufferAttribute?t[r]*e.data.stride+e.offset:t[r]*i;for(let e=0;e<i;e++)n[a++]=s[o++]}return new dh(n,i,r)}if(null===this.index)return Yo("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Sh,s=this.index.array,i=this.attributes;for(const r in i){const n=e(i[r],s);t.setAttribute(r,n)}const r=this.morphAttributes;for(const i in r){const n=[],o=r[i];for(let t=0,i=o.length;t<i;t++){const i=e(o[t],s);n.push(i)}t.morphAttributes[i]=n}t.morphTargetsRelative=this.morphTargetsRelative;const n=this.groups;for(let e=0,s=n.length;e<s;e++){const s=n[e];t.addGroup(s.start,s.count,s.materialIndex)}return t}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,""!==this.name&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),void 0!==this.parameters){const t=this.parameters;for(const s in t)void 0!==t[s]&&(e[s]=t[s]);return e}e.data={attributes:{}};const t=this.index;null!==t&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const s=this.attributes;for(const t in s){const i=s[t];e.data.attributes[t]=i.toJSON(e.data)}const i={};let r=!1;for(const t in this.morphAttributes){const s=this.morphAttributes[t],n=[];for(let t=0,i=s.length;t<i;t++){const i=s[t];n.push(i.toJSON(e.data))}n.length>0&&(i[t]=n,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const n=this.groups;n.length>0&&(e.data.groups=JSON.parse(JSON.stringify(n)));const o=this.boundingSphere;return null!==o&&(e.data.boundingSphere=o.toJSON()),e}clone(){return(new this.constructor).copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const s=e.index;null!==s&&this.setIndex(s.clone());const i=e.attributes;for(const e in i){const s=i[e];this.setAttribute(e,s.clone(t))}const r=e.morphAttributes;for(const e in r){const s=[],i=r[e];for(let e=0,r=i.length;e<r;e++)s.push(i[e].clone(t));this.morphAttributes[e]=s}this.morphTargetsRelative=e.morphTargetsRelative;const n=e.groups;for(let e=0,t=n.length;e<t;e++){const t=n[e];this.addGroup(t.start,t.count,t.materialIndex)}const o=e.boundingBox;null!==o&&(this.boundingBox=o.clone());const a=e.boundingSphere;return null!==a&&(this.boundingSphere=a.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const Mh=new ll,Ah=new al,Nh=new Ja,Eh=new da,Ch=new da,Rh=new da,Ph=new da,Bh=new da,Ih=new da,Dh=new da,Lh=new da;class Fh extends Ll{constructor(e=new Sh,t=new rh){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),void 0!==e.morphTargetInfluences&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),void 0!==e.morphTargetDictionary&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){const s=e[t[0]];if(void 0!==s){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=s.length;e<t;e++){const t=s[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){const s=this.geometry,i=s.attributes.position,r=s.morphAttributes.position,n=s.morphTargetsRelative;t.fromBufferAttribute(i,e);const o=this.morphTargetInfluences;if(r&&o){Ih.set(0,0,0);for(let s=0,i=r.length;s<i;s++){const i=o[s],a=r[s];0!==i&&(Bh.fromBufferAttribute(a,e),n?Ih.addScaledVector(Bh,i):Ih.addScaledVector(Bh.sub(t),i))}t.add(Ih)}return t}raycast(e,t){const s=this.geometry,i=this.material,r=this.matrixWorld;if(void 0!==i){if(null===s.boundingSphere&&s.computeBoundingSphere(),Nh.copy(s.boundingSphere),Nh.applyMatrix4(r),Ah.copy(e.ray).recast(e.near),!1===Nh.containsPoint(Ah.origin)){if(null===Ah.intersectSphere(Nh,Eh))return;if(Ah.origin.distanceToSquared(Eh)>(e.far-e.near)**2)return}Mh.copy(r).invert(),Ah.copy(e.ray).applyMatrix4(Mh),null!==s.boundingBox&&!1===Ah.intersectsBox(s.boundingBox)||this._computeIntersections(e,t,Ah)}}_computeIntersections(e,t,s){let i;const r=this.geometry,n=this.material,o=r.index,a=r.attributes.position,l=r.attributes.uv,h=r.attributes.uv1,u=r.attributes.normal,c=r.groups,d=r.drawRange;if(null!==o)if(Array.isArray(n))for(let r=0,a=c.length;r<a;r++){const a=c[r],p=n[a.materialIndex];for(let r=Math.max(a.start,d.start),n=Math.min(o.count,Math.min(a.start+a.count,d.start+d.count));r<n;r+=3){i=Oh(this,p,e,s,l,h,u,o.getX(r),o.getX(r+1),o.getX(r+2)),i&&(i.faceIndex=Math.floor(r/3),i.face.materialIndex=a.materialIndex,t.push(i))}}else{for(let r=Math.max(0,d.start),a=Math.min(o.count,d.start+d.count);r<a;r+=3){i=Oh(this,n,e,s,l,h,u,o.getX(r),o.getX(r+1),o.getX(r+2)),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}else if(void 0!==a)if(Array.isArray(n))for(let r=0,o=c.length;r<o;r++){const o=c[r],p=n[o.materialIndex];for(let r=Math.max(o.start,d.start),n=Math.min(a.count,Math.min(o.start+o.count,d.start+d.count));r<n;r+=3){i=Oh(this,p,e,s,l,h,u,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),i.face.materialIndex=o.materialIndex,t.push(i))}}else{for(let r=Math.max(0,d.start),o=Math.min(a.count,d.start+d.count);r<o;r+=3){i=Oh(this,n,e,s,l,h,u,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}}}function Oh(e,t,s,i,r,n,o,a,l,h){e.getVertexPosition(a,Ch),e.getVertexPosition(l,Rh),e.getVertexPosition(h,Ph);const u=function(e,t,s,i,r,n,o,a){let l;if(l=1===t.side?i.intersectTriangle(o,n,r,!0,a):i.intersectTriangle(r,n,o,0===t.side,a),null===l)return null;Lh.copy(a),Lh.applyMatrix4(e.matrixWorld);const h=s.ray.origin.distanceTo(Lh);return h<s.near||h>s.far?null:{distance:h,point:Lh.clone(),object:e}}(e,t,s,i,Ch,Rh,Ph,Dh);if(u){const e=new da;Yl.getBarycoord(Dh,Ch,Rh,Ph,e),r&&(u.uv=Yl.getInterpolatedAttribute(r,a,l,h,e,new ua)),n&&(u.uv1=Yl.getInterpolatedAttribute(n,a,l,h,e,new ua)),o&&(u.normal=Yl.getInterpolatedAttribute(o,a,l,h,e,new da),u.normal.dot(i.direction)>0&&u.normal.multiplyScalar(-1));const t={a:a,b:l,c:h,normal:new da,materialIndex:0};Yl.getNormal(Ch,Rh,Ph,t.normal),u.face=t,u.barycoord=e}return u}class Vh extends Sh{constructor(e=1,t=1,s=1,i=1,r=1,n=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:s,widthSegments:i,heightSegments:r,depthSegments:n};const o=this;i=Math.floor(i),r=Math.floor(r),n=Math.floor(n);const a=[],l=[],h=[],u=[];let c=0,d=0;function p(e,t,s,i,r,n,p,m,f,g,y){const x=n/f,b=p/g,_=n/2,w=p/2,v=m/2,T=f+1,S=g+1;let M=0,A=0;const N=new da;for(let n=0;n<S;n++){const o=n*b-w;for(let a=0;a<T;a++){const c=a*x-_;N[e]=c*i,N[t]=o*r,N[s]=v,l.push(N.x,N.y,N.z),N[e]=0,N[t]=0,N[s]=m>0?1:-1,h.push(N.x,N.y,N.z),u.push(a/f),u.push(1-n/g),M+=1}}for(let e=0;e<g;e++)for(let t=0;t<f;t++){const s=c+t+T*e,i=c+t+T*(e+1),r=c+(t+1)+T*(e+1),n=c+(t+1)+T*e;a.push(s,i,n),a.push(i,r,n),A+=6}o.addGroup(d,A,y),d+=A,c+=M}p("z","y","x",-1,-1,s,t,e,n,r,0),p("z","y","x",1,-1,s,t,-e,n,r,1),p("x","z","y",1,1,e,s,t,i,n,2),p("x","z","y",1,-1,e,s,-t,i,n,3),p("x","y","z",1,-1,e,t,s,i,r,4),p("x","y","z",-1,-1,e,t,-s,i,r,5),this.setIndex(a),this.setAttribute("position",new gh(l,3)),this.setAttribute("normal",new gh(h,3)),this.setAttribute("uv",new gh(u,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Vh(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function zh(e){const t={};for(const s in e){t[s]={};for(const i in e[s]){const r=e[s][i];r&&(r.isColor||r.isMatrix3||r.isMatrix4||r.isVector2||r.isVector3||r.isVector4||r.isTexture||r.isQuaternion)?r.isRenderTargetTexture?(Yo("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),t[s][i]=null):t[s][i]=r.clone():Array.isArray(r)?t[s][i]=r.slice():t[s][i]=r}}return t}class kh extends ih{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}",this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,void 0!==e&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=zh(e.uniforms),this.uniformsGroups=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].clone());return t}(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const s in this.uniforms){const i=this.uniforms[s].value;i&&i.isTexture?t.uniforms[s]={type:"t",value:i.toJSON(e).uuid}:i&&i.isColor?t.uniforms[s]={type:"c",value:i.getHex()}:i&&i.isVector2?t.uniforms[s]={type:"v2",value:i.toArray()}:i&&i.isVector3?t.uniforms[s]={type:"v3",value:i.toArray()}:i&&i.isVector4?t.uniforms[s]={type:"v4",value:i.toArray()}:i&&i.isMatrix3?t.uniforms[s]={type:"m3",value:i.toArray()}:i&&i.isMatrix4?t.uniforms[s]={type:"m4",value:i.toArray()}:t.uniforms[s]={value:i}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const s={};for(const e in this.extensions)!0===this.extensions[e]&&(s[e]=!0);return Object.keys(s).length>0&&(t.extensions=s),t}}class Uh extends Ll{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new ll,this.projectionMatrix=new ll,this.projectionMatrixInverse=new ll,this.coordinateSystem=ko,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}const Gh=new da,jh=new ua,$h=new ua;class Wh extends Uh{constructor(e=50,t=1,s=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=s,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=null===e.view?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=2*sa*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*ta*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*sa*Math.atan(Math.tan(.5*ta*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,s){Gh.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Gh.x,Gh.y).multiplyScalar(-e/Gh.z),Gh.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),s.set(Gh.x,Gh.y).multiplyScalar(-e/Gh.z)}getViewSize(e,t){return this.getViewBounds(e,jh,$h),t.subVectors($h,jh)}setViewOffset(e,t,s,i,r,n){this.aspect=e/t,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=s,this.view.offsetY=i,this.view.width=r,this.view.height=n,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(.5*ta*this.fov)/this.zoom,s=2*t,i=this.aspect*s,r=-.5*i;const n=this.view;if(null!==this.view&&this.view.enabled){const e=n.fullWidth,o=n.fullHeight;r+=n.offsetX*i/e,t-=n.offsetY*s/o,i*=n.width/e,s*=n.height/o}const o=this.filmOffset;0!==o&&(r+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,t,t-s,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,null!==this.view&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const Hh=-90;class qh extends Ll{constructor(e,t,s){super(),this.type="CubeCamera",this.renderTarget=s,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Wh(Hh,1,e,t);i.layers=this.layers,this.add(i);const r=new Wh(Hh,1,e,t);r.layers=this.layers,this.add(r);const n=new Wh(Hh,1,e,t);n.layers=this.layers,this.add(n);const o=new Wh(Hh,1,e,t);o.layers=this.layers,this.add(o);const a=new Wh(Hh,1,e,t);a.layers=this.layers,this.add(a);const l=new Wh(Hh,1,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[s,i,r,n,o,a]=t;for(const e of t)this.remove(e);if(e===ko)s.up.set(0,1,0),s.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),n.up.set(0,0,1),n.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),a.up.set(0,1,0),a.lookAt(0,0,-1);else{if(e!==Uo)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);s.up.set(0,-1,0),s.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),n.up.set(0,0,-1),n.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),a.up.set(0,-1,0),a.lookAt(0,0,-1)}for(const e of t)this.add(e),e.updateMatrixWorld()}update(e,t){null===this.parent&&this.updateMatrixWorld();const{renderTarget:s,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,n,o,a,l,h]=this.children,u=e.getRenderTarget(),c=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const m=s.texture.generateMipmaps;s.texture.generateMipmaps=!1,e.setRenderTarget(s,0,i),e.render(t,r),e.setRenderTarget(s,1,i),e.render(t,n),e.setRenderTarget(s,2,i),e.render(t,o),e.setRenderTarget(s,3,i),e.render(t,a),e.setRenderTarget(s,4,i),e.render(t,l),s.texture.generateMipmaps=m,e.setRenderTarget(s,5,i),e.render(t,h),e.setRenderTarget(u,c,d),e.xr.enabled=p,s.texture.needsPMREMUpdate=!0}}class Xh extends Ra{constructor(e=[],t=301,s,i,r,n,o,a,l,h){super(e,t,s,i,r,n,o,a,l,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Yh extends Ia{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const s={width:e,height:e,depth:1},i=[s,s,s,s,s,s];this.texture=new Xh(i),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const s={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include <begin_vertex>\n\t\t\t\t\t#include <project_vertex>\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include <common>\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},i=new Vh(5,5,5),r=new kh({name:"CubemapFromEquirect",uniforms:zh(s.uniforms),vertexShader:s.vertexShader,fragmentShader:s.fragmentShader,side:1,blending:0});r.uniforms.tEquirect.value=t;const n=new Fh(i,r),o=t.minFilter;t.minFilter===_n&&(t.minFilter=xn);return new qh(1,10,this).update(e,n),t.minFilter=o,n.geometry.dispose(),n.material.dispose(),this}clear(e,t=!0,s=!0,i=!0){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,s,i);e.setRenderTarget(r)}}class Zh extends Ll{constructor(){super(),this.isGroup=!0,this.type="Group"}}const Qh={type:"move"};class Kh{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new Zh,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return null===this._targetRay&&(this._targetRay=new Zh,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new da,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new da),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new Zh,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new da,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new da),this._grip}dispatchEvent(e){return null!==this._targetRay&&this._targetRay.dispatchEvent(e),null!==this._grip&&this._grip.dispatchEvent(e),null!==this._hand&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const s of e.hand.values())this._getHandJoint(t,s)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),null!==this._targetRay&&(this._targetRay.visible=!1),null!==this._grip&&(this._grip.visible=!1),null!==this._hand&&(this._hand.visible=!1),this}update(e,t,s){let i=null,r=null,n=null;const o=this._targetRay,a=this._grip,l=this._hand;if(e&&"visible-blurred"!==t.session.visibilityState){if(l&&e.hand){n=!0;for(const i of e.hand.values()){const e=t.getJointPose(i,s),r=this._getHandJoint(l,i);null!==e&&(r.matrix.fromArray(e.transform.matrix),r.matrix.decompose(r.position,r.rotation,r.scale),r.matrixWorldNeedsUpdate=!0,r.jointRadius=e.radius),r.visible=null!==e}const i=l.joints["index-finger-tip"],r=l.joints["thumb-tip"],o=i.position.distanceTo(r.position),a=.02,h=.005;l.inputState.pinching&&o>a+h?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&o<=a-h&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else null!==a&&e.gripSpace&&(r=t.getPose(e.gripSpace,s),null!==r&&(a.matrix.fromArray(r.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,r.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(r.linearVelocity)):a.hasLinearVelocity=!1,r.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(r.angularVelocity)):a.hasAngularVelocity=!1));null!==o&&(i=t.getPose(e.targetRaySpace,s),null===i&&null!==r&&(i=r),null!==i&&(o.matrix.fromArray(i.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,i.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(i.linearVelocity)):o.hasLinearVelocity=!1,i.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(i.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(Qh)))}return null!==o&&(o.visible=null!==i),null!==a&&(a.visible=null!==r),null!==l&&(l.visible=null!==n),this}_getHandJoint(e,t){if(void 0===e.joints[t.jointName]){const s=new Zh;s.matrixAutoUpdate=!1,s.visible=!1,e.joints[t.jointName]=s,e.add(s)}return e.joints[t.jointName]}}class Jh extends Ll{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new xl,this.environmentIntensity=1,this.environmentRotation=new xl,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),null!==e.background&&(this.background=e.background.clone()),null!==e.environment&&(this.environment=e.environment.clone()),null!==e.fog&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),null!==e.overrideMaterial&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return null!==this.fog&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),1!==this.environmentIntensity&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class eu{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=Vo,this.updateRanges=[],this.version=0,this.uuid=ia()}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,s){e*=this.stride,s*=t.stride;for(let i=0,r=this.stride;i<r;i++)this.array[e+i]=t.array[s+i];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){void 0===e.arrayBuffers&&(e.arrayBuffers={}),void 0===this.array.buffer._uuid&&(this.array.buffer._uuid=ia()),void 0===e.arrayBuffers[this.array.buffer._uuid]&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),s=new this.constructor(t,this.stride);return s.setUsage(this.usage),s}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return void 0===e.arrayBuffers&&(e.arrayBuffers={}),void 0===this.array.buffer._uuid&&(this.array.buffer._uuid=ia()),void 0===e.arrayBuffers[this.array.buffer._uuid]&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}const tu=new da;class su{constructor(e,t,s,i=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=s,this.normalized=i}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,s=this.data.count;t<s;t++)tu.fromBufferAttribute(this,t),tu.applyMatrix4(e),this.setXYZ(t,tu.x,tu.y,tu.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)tu.fromBufferAttribute(this,t),tu.applyNormalMatrix(e),this.setXYZ(t,tu.x,tu.y,tu.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)tu.fromBufferAttribute(this,t),tu.transformDirection(e),this.setXYZ(t,tu.x,tu.y,tu.z);return this}getComponent(e,t){let s=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(s=aa(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=la(s,this.array)),this.data.array[e*this.data.stride+this.offset+t]=s,this}setX(e,t){return this.normalized&&(t=la(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=la(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=la(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=la(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=aa(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=aa(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=aa(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=aa(t,this.array)),t}setXY(e,t,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=la(t,this.array),s=la(s,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this}setXYZ(e,t,s,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=la(t,this.array),s=la(s,this.array),i=la(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this.data.array[e+2]=i,this}setXYZW(e,t,s,i,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=la(t,this.array),s=la(s,this.array),i=la(i,this.array),r=la(r,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this.data.array[e+2]=i,this.data.array[e+3]=r,this}clone(e){if(void 0===e){Xo("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let t=0;t<this.count;t++){const s=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[s+t])}return new dh(new this.array.constructor(e),this.itemSize,this.normalized)}return void 0===e.interleavedBuffers&&(e.interleavedBuffers={}),void 0===e.interleavedBuffers[this.data.uuid]&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new su(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(void 0===e){Xo("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let t=0;t<this.count;t++){const s=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[s+t])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:e,normalized:this.normalized}}return void 0===e.interleavedBuffers&&(e.interleavedBuffers={}),void 0===e.interleavedBuffers[this.data.uuid]&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}class iu extends ih{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new eh(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}class ru extends Ra{constructor(e=null,t=1,s=1,i,r,n,o,a,l=1003,h=1003,u,c){super(null,n,o,a,l,h,i,r,u,c),this.isDataTexture=!0,this.image={data:e,width:t,height:s},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class nu extends dh{constructor(e,t,s,i=1){super(e,t,s),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=i}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){const e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}}const ou=new da,au=new da,lu=new fa;class hu{constructor(e=new da(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,s,i){return this.normal.set(e,t,s),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,s){const i=ou.subVectors(s,t).cross(au.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const s=e.delta(ou),i=this.normal.dot(s);if(0===i)return 0===this.distanceToPoint(e.start)?t.copy(e.start):null;const r=-(e.start.dot(this.normal)+this.constant)/i;return r<0||r>1?null:t.copy(e.start).addScaledVector(s,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),s=this.distanceToPoint(e.end);return t<0&&s>0||s<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const s=t||lu.getNormalMatrix(e),i=this.coplanarPoint(ou).applyMatrix4(e),r=this.normal.applyMatrix3(s).normalize();return this.constant=-i.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return(new this.constructor).copy(this)}}const uu=new Ja,cu=new ua(.5,.5),du=new da;class pu{constructor(e=new hu,t=new hu,s=new hu,i=new hu,r=new hu,n=new hu){this.planes=[e,t,s,i,r,n]}set(e,t,s,i,r,n){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(s),o[3].copy(i),o[4].copy(r),o[5].copy(n),this}copy(e){const t=this.planes;for(let s=0;s<6;s++)t[s].copy(e.planes[s]);return this}setFromProjectionMatrix(e,t=2e3,s=!1){const i=this.planes,r=e.elements,n=r[0],o=r[1],a=r[2],l=r[3],h=r[4],u=r[5],c=r[6],d=r[7],p=r[8],m=r[9],f=r[10],g=r[11],y=r[12],x=r[13],b=r[14],_=r[15];if(i[0].setComponents(l-n,d-h,g-p,_-y).normalize(),i[1].setComponents(l+n,d+h,g+p,_+y).normalize(),i[2].setComponents(l+o,d+u,g+m,_+x).normalize(),i[3].setComponents(l-o,d-u,g-m,_-x).normalize(),s)i[4].setComponents(a,c,f,b).normalize(),i[5].setComponents(l-a,d-c,g-f,_-b).normalize();else if(i[4].setComponents(l-a,d-c,g-f,_-b).normalize(),t===ko)i[5].setComponents(l+a,d+c,g+f,_+b).normalize();else{if(t!==Uo)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);i[5].setComponents(a,c,f,b).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),uu.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),uu.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(uu)}intersectsSprite(e){uu.center.set(0,0,0);const t=cu.distanceTo(e.center);return uu.radius=.7071067811865476+t,uu.applyMatrix4(e.matrixWorld),this.intersectsSphere(uu)}intersectsSphere(e){const t=this.planes,s=e.center,i=-e.radius;for(let e=0;e<6;e++){if(t[e].distanceToPoint(s)<i)return!1}return!0}intersectsBox(e){const t=this.planes;for(let s=0;s<6;s++){const i=t[s];if(du.x=i.normal.x>0?e.max.x:e.min.x,du.y=i.normal.y>0?e.max.y:e.min.y,du.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(du)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let s=0;s<6;s++)if(t[s].distanceToPoint(e)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}const mu=new ll,fu=new pu;class gu{constructor(){this.coordinateSystem=ko}intersectsObject(e,t){if(!t.isArrayCamera||0===t.cameras.length)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(mu.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),fu.setFromProjectionMatrix(mu,i.coordinateSystem,i.reversedDepth),fu.intersectsObject(e))return!0}return!1}intersectsSprite(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(mu.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),fu.setFromProjectionMatrix(mu,i.coordinateSystem,i.reversedDepth),fu.intersectsSprite(e))return!0}return!1}intersectsSphere(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(mu.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),fu.setFromProjectionMatrix(mu,i.coordinateSystem,i.reversedDepth),fu.intersectsSphere(e))return!0}return!1}intersectsBox(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(mu.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),fu.setFromProjectionMatrix(mu,i.coordinateSystem,i.reversedDepth),fu.intersectsBox(e))return!0}return!1}containsPoint(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(mu.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),fu.setFromProjectionMatrix(mu,i.coordinateSystem,i.reversedDepth),fu.containsPoint(e))return!0}return!1}clone(){return new gu}}class yu extends ih{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new eh(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}class xu extends ih{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new eh(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}class bu extends Ra{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=fn,this.minFilter=fn,this.generateMipmaps=!1,this.needsUpdate=!0}}class _u extends Ra{constructor(e,t,s=1014,i,r,n,o=1003,a=1003,l,h=1026,u=1){if(h!==Fn&&h!==On)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super({width:e,height:t,depth:u},i,r,n,o,a,h,s,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Aa(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return null!==this.compareFunction&&(t.compareFunction=this.compareFunction),t}}class wu extends _u{constructor(e,t=1014,s=301,i,r,n=1003,o=1003,a,l=1026){const h={width:e,height:e,depth:1},u=[h,h,h,h,h,h];super(e,e,t,s,i,r,n,o,a,l),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class vu extends Sh{constructor(e=1,t=1,s=1,i=32,r=1,n=!1,o=0,a=2*Math.PI){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:s,radialSegments:i,heightSegments:r,openEnded:n,thetaStart:o,thetaLength:a};const l=this;i=Math.floor(i),r=Math.floor(r);const h=[],u=[],c=[],d=[];let p=0;const m=[],f=s/2;let g=0;function y(s){const r=p,n=new ua,m=new da;let y=0;const x=!0===s?e:t,b=!0===s?1:-1;for(let e=1;e<=i;e++)u.push(0,f*b,0),c.push(0,b,0),d.push(.5,.5),p++;const _=p;for(let e=0;e<=i;e++){const t=e/i*a+o,s=Math.cos(t),r=Math.sin(t);m.x=x*r,m.y=f*b,m.z=x*s,u.push(m.x,m.y,m.z),c.push(0,b,0),n.x=.5*s+.5,n.y=.5*r*b+.5,d.push(n.x,n.y),p++}for(let e=0;e<i;e++){const t=r+e,i=_+e;!0===s?h.push(i,i+1,t):h.push(i+1,i,t),y+=3}l.addGroup(g,y,!0===s?1:2),g+=y}!function(){const n=new da,y=new da;let x=0;const b=(t-e)/s;for(let l=0;l<=r;l++){const h=[],g=l/r,x=g*(t-e)+e;for(let e=0;e<=i;e++){const t=e/i,r=t*a+o,l=Math.sin(r),m=Math.cos(r);y.x=x*l,y.y=-g*s+f,y.z=x*m,u.push(y.x,y.y,y.z),n.set(l,b,m).normalize(),c.push(n.x,n.y,n.z),d.push(t,1-g),h.push(p++)}m.push(h)}for(let s=0;s<i;s++)for(let i=0;i<r;i++){const n=m[i][s],o=m[i+1][s],a=m[i+1][s+1],l=m[i][s+1];(e>0||0!==i)&&(h.push(n,o,l),x+=3),(t>0||i!==r-1)&&(h.push(o,a,l),x+=3)}l.addGroup(g,x,0),g+=x}(),!1===n&&(e>0&&y(!0),t>0&&y(!1)),this.setIndex(h),this.setAttribute("position",new gh(u,3)),this.setAttribute("normal",new gh(c,3)),this.setAttribute("uv",new gh(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new vu(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Tu extends Sh{constructor(e=1,t=1,s=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:s,heightSegments:i};const r=e/2,n=t/2,o=Math.floor(s),a=Math.floor(i),l=o+1,h=a+1,u=e/o,c=t/a,d=[],p=[],m=[],f=[];for(let e=0;e<h;e++){const t=e*c-n;for(let s=0;s<l;s++){const i=s*u-r;p.push(i,-t,0),m.push(0,0,1),f.push(s/o),f.push(1-e/a)}}for(let e=0;e<a;e++)for(let t=0;t<o;t++){const s=t+l*e,i=t+l*(e+1),r=t+1+l*(e+1),n=t+1+l*e;d.push(s,i,n),d.push(i,r,n)}this.setIndex(d),this.setAttribute("position",new gh(p,3)),this.setAttribute("normal",new gh(m,3)),this.setAttribute("uv",new gh(f,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Tu(e.width,e.height,e.widthSegments,e.heightSegments)}}class Su extends Sh{constructor(e=1,t=32,s=16,i=0,r=2*Math.PI,n=0,o=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:s,phiStart:i,phiLength:r,thetaStart:n,thetaLength:o},t=Math.max(3,Math.floor(t)),s=Math.max(2,Math.floor(s));const a=Math.min(n+o,Math.PI);let l=0;const h=[],u=new da,c=new da,d=[],p=[],m=[],f=[];for(let d=0;d<=s;d++){const g=[],y=d/s;let x=0;0===d&&0===n?x=.5/t:d===s&&a===Math.PI&&(x=-.5/t);for(let s=0;s<=t;s++){const a=s/t;u.x=-e*Math.cos(i+a*r)*Math.sin(n+y*o),u.y=e*Math.cos(n+y*o),u.z=e*Math.sin(i+a*r)*Math.sin(n+y*o),p.push(u.x,u.y,u.z),c.copy(u).normalize(),m.push(c.x,c.y,c.z),f.push(a+x,1-y),g.push(l++)}h.push(g)}for(let e=0;e<s;e++)for(let i=0;i<t;i++){const t=h[e][i+1],r=h[e][i],o=h[e+1][i],l=h[e+1][i+1];(0!==e||n>0)&&d.push(t,r,l),(e!==s-1||a<Math.PI)&&d.push(r,o,l)}this.setIndex(d),this.setAttribute("position",new gh(p,3)),this.setAttribute("normal",new gh(m,3)),this.setAttribute("uv",new gh(f,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Su(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class Mu extends ih{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new eh(0),this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.fog=e.fog,this}}class Au extends ih{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new eh(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 eh(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new ua(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new xl,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Nu extends Au{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new ua(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return ra(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(e){this.ior=(1+.4*e)/(1-.4*e)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new eh(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new eh(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new eh(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class Eu extends ih{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new eh(16777215),this.specular=new eh(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new eh(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new ua(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new xl,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Cu extends ih{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new eh(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new eh(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new ua(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class Ru extends ih{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new ua(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class Pu extends ih{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new eh(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new eh(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new ua(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new xl,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Bu extends ih{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new eh(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new ua(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Iu extends yu{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}class Du extends Ll{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new eh(e),this.intensity=t}dispose(){this.dispatchEvent({type:"dispose"})}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,t}}class Lu extends Du{constructor(e,t,s){super(e,s),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(Ll.DEFAULT_UP),this.updateMatrix(),this.groundColor=new eh(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}toJSON(e){const t=super.toJSON(e);return t.object.groundColor=this.groundColor.getHex(),t}}const Fu=new ll,Ou=new da,Vu=new da;class zu{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new ua(512,512),this.mapType=wn,this.map=null,this.mapPass=null,this.matrix=new ll,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new pu,this._frameExtents=new ua(1,1),this._viewportCount=1,this._viewports=[new Pa(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,s=this.matrix;Ou.setFromMatrixPosition(e.matrixWorld),t.position.copy(Ou),Vu.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Vu),t.updateMatrixWorld(),Fu.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Fu,t.coordinateSystem,t.reversedDepth),t.reversedDepth?s.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):s.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),s.multiply(Fu)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this}clone(){return(new this.constructor).copy(this)}toJSON(){const e={};return 1!==this.intensity&&(e.intensity=this.intensity),0!==this.bias&&(e.bias=this.bias),0!==this.normalBias&&(e.normalBias=this.normalBias),1!==this.radius&&(e.radius=this.radius),512===this.mapSize.x&&512===this.mapSize.y||(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}class ku extends zu{constructor(){super(new Wh(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){const t=this.camera,s=2*sa*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height*this.aspect,r=e.distance||t.far;s===t.fov&&i===t.aspect&&r===t.far||(t.fov=s,t.aspect=i,t.far=r,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}}class Uu extends Du{constructor(e,t,s=0,i=Math.PI/3,r=0,n=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(Ll.DEFAULT_UP),this.updateMatrix(),this.target=new Ll,this.distance=s,this.angle=i,this.penumbra=r,this.decay=n,this.map=null,this.shadow=new ku}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.map=e.map,this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.distance=this.distance,t.object.angle=this.angle,t.object.decay=this.decay,t.object.penumbra=this.penumbra,t.object.target=this.target.uuid,this.map&&this.map.isTexture&&(t.object.map=this.map.toJSON(e).uuid),t.object.shadow=this.shadow.toJSON(),t}}class Gu extends zu{constructor(){super(new Wh(90,1,.5,500)),this.isPointLightShadow=!0}}class ju extends Du{constructor(e,t,s=0,i=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=s,this.decay=i,this.shadow=new Gu}get power(){return 4*this.intensity*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.distance=this.distance,t.object.decay=this.decay,t.object.shadow=this.shadow.toJSON(),t}}class $u extends Uh{constructor(e=-1,t=1,s=1,i=-1,r=.1,n=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=s,this.bottom=i,this.near=r,this.far=n,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=null===e.view?null:Object.assign({},e.view),this}setViewOffset(e,t,s,i,r,n){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=s,this.view.offsetY=i,this.view.width=r,this.view.height=n,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),s=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let r=s-e,n=s+e,o=i+t,a=i-t;if(null!==this.view&&this.view.enabled){const e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=e*this.view.offsetX,n=r+e*this.view.width,o-=t*this.view.offsetY,a=o-t*this.view.height}this.projectionMatrix.makeOrthographic(r,n,o,a,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,null!==this.view&&(t.object.view=Object.assign({},this.view)),t}}class Wu extends zu{constructor(){super(new $u(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class Hu extends Du{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Ll.DEFAULT_UP),this.updateMatrix(),this.target=new Ll,this.shadow=new Wu}dispose(){super.dispose(),this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.shadow=this.shadow.toJSON(),t.object.target=this.target.uuid,t}}class qu extends Du{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class Xu extends Du{constructor(e,t,s=10,i=10){super(e,t),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=s,this.height=i}get power(){return this.intensity*this.width*this.height*Math.PI}set power(e){this.intensity=e/(this.width*this.height*Math.PI)}copy(e){return super.copy(e),this.width=e.width,this.height=e.height,this}toJSON(e){const t=super.toJSON(e);return t.object.width=this.width,t.object.height=this.height,t}}class Yu{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new da)}set(e){for(let t=0;t<9;t++)this.coefficients[t].copy(e[t]);return this}zero(){for(let e=0;e<9;e++)this.coefficients[e].set(0,0,0);return this}getAt(e,t){const s=e.x,i=e.y,r=e.z,n=this.coefficients;return t.copy(n[0]).multiplyScalar(.282095),t.addScaledVector(n[1],.488603*i),t.addScaledVector(n[2],.488603*r),t.addScaledVector(n[3],.488603*s),t.addScaledVector(n[4],s*i*1.092548),t.addScaledVector(n[5],i*r*1.092548),t.addScaledVector(n[6],.315392*(3*r*r-1)),t.addScaledVector(n[7],s*r*1.092548),t.addScaledVector(n[8],.546274*(s*s-i*i)),t}getIrradianceAt(e,t){const s=e.x,i=e.y,r=e.z,n=this.coefficients;return t.copy(n[0]).multiplyScalar(.886227),t.addScaledVector(n[1],1.023328*i),t.addScaledVector(n[2],1.023328*r),t.addScaledVector(n[3],1.023328*s),t.addScaledVector(n[4],.858086*s*i),t.addScaledVector(n[5],.858086*i*r),t.addScaledVector(n[6],.743125*r*r-.247708),t.addScaledVector(n[7],.858086*s*r),t.addScaledVector(n[8],.429043*(s*s-i*i)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let s=0;s<9;s++)this.coefficients[s].addScaledVector(e.coefficients[s],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let s=0;s<9;s++)this.coefficients[s].lerp(e.coefficients[s],t);return this}equals(e){for(let t=0;t<9;t++)if(!this.coefficients[t].equals(e.coefficients[t]))return!1;return!0}copy(e){return this.set(e.coefficients)}clone(){return(new this.constructor).copy(this)}fromArray(e,t=0){const s=this.coefficients;for(let i=0;i<9;i++)s[i].fromArray(e,t+3*i);return this}toArray(e=[],t=0){const s=this.coefficients;for(let i=0;i<9;i++)s[i].toArray(e,t+3*i);return e}static getBasisAt(e,t){const s=e.x,i=e.y,r=e.z;t[0]=.282095,t[1]=.488603*i,t[2]=.488603*r,t[3]=.488603*s,t[4]=1.092548*s*i,t[5]=1.092548*i*r,t[6]=.315392*(3*r*r-1),t[7]=1.092548*s*r,t[8]=.546274*(s*s-i*i)}}class Zu extends Du{constructor(e=new Yu,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}toJSON(e){const t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}}class Qu extends Wh{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class Ku extends eu{constructor(e,t,s=1){super(e,t),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=s}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}clone(e){const t=super.clone(e);return t.meshPerAttribute=this.meshPerAttribute,t}toJSON(e){const t=super.toJSON(e);return t.isInstancedInterleavedBuffer=!0,t.meshPerAttribute=this.meshPerAttribute,t}}class Ju{constructor(e,t,s,i){Ju.prototype.isMatrix2=!0,this.elements=[1,0,0,1],void 0!==e&&this.set(e,t,s,i)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let s=0;s<4;s++)this.elements[s]=e[s+t];return this}set(e,t,s,i){const r=this.elements;return r[0]=e,r[2]=t,r[1]=s,r[3]=i,this}}function ec(e,t,s,i){const r=function(e){switch(e){case wn:case vn:return{byteLength:1,components:1};case Sn:case Tn:case En:return{byteLength:2,components:1};case Cn:case Rn:return{byteLength:2,components:4};case An:case Mn:case Nn:return{byteLength:4,components:1};case Bn:case In:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${e}.`)}(i);switch(s){case 1021:return e*t;case Vn:case zn:return e*t/r.components*r.byteLength;case kn:case Un:return e*t*2/r.components*r.byteLength;case Dn:return e*t*3/r.components*r.byteLength;case Ln:case Gn:return e*t*4/r.components*r.byteLength;case jn:case $n:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Wn:case Hn:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Xn:case Zn:return Math.max(e,16)*Math.max(t,8)/4;case qn:case Yn:return Math.max(e,8)*Math.max(t,8)/2;case Qn:case Kn:case eo:case to:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Jn:case so:case io:case ro:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case no:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case oo:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case ao:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case lo:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case ho:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case uo:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case co:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case po:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case mo:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case fo:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case go:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case yo:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case xo:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case bo:case 36494:case 36495:return Math.ceil(e/4)*Math.ceil(t/4)*16;case _o:case wo:return Math.ceil(e/4)*Math.ceil(t/4)*8;case vo:case To:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw new Error(`Unable to determine texture byte length for ${s} format.`)}"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:Xr}})),"undefined"!=typeof window&&(window.__THREE__?Yo("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=Xr)
7
+ /**
8
+ * @license
9
+ * Copyright 2010-2025 Three.js Authors
10
+ * SPDX-License-Identifier: MIT
11
+ */;const tc=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","aoMapIntensity","attenuationColor","attenuationDistance","bumpMap","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dispersion","displacementMap","emissive","emissiveIntensity","emissiveMap","envMap","envMapIntensity","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","lightMap","lightMapIntensity","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","roughness","roughnessMap","sheen","sheenColor","sheenColorMap","sheenRoughnessMap","shininess","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","thickness","transmission","transmissionMap"],sc=new WeakMap;class ic{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=tc,this.renderId=0}firstInitialization(e){return!1===this.renderObjects.has(e)&&(this.getRenderObjectData(e),!0)}needsVelocity(e){const t=e.getMRT();return null!==t&&t.has("velocity")}getRenderObjectData(e){let t=this.renderObjects.get(e);if(void 0===t){const{geometry:s,material:i,object:r}=e;if(t={material:this.getMaterialData(i),geometry:{id:s.id,attributes:this.getAttributesData(s.attributes),indexVersion:s.index?s.index.version:null,drawRange:{start:s.drawRange.start,count:s.drawRange.count}},worldMatrix:r.matrixWorld.clone()},r.center&&(t.center=r.center.clone()),r.morphTargetInfluences&&(t.morphTargetInfluences=r.morphTargetInfluences.slice()),null!==e.bundle&&(t.version=e.bundle.version),t.material.transmission>0){const{width:s,height:i}=e.context;t.bufferWidth=s,t.bufferHeight=i}t.lights=this.getLightsData(e.lightsNode.getLights()),this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const s in e){const i=e[s];t[s]={version:i.version}}return t}containsNode(e){const t=e.material;for(const e in t)if(t[e]&&t[e].isNode)return!0;return!!(e.context.modelViewMatrix||e.context.modelNormalViewMatrix||e.context.getAO||e.context.getShadow)}getMaterialData(e){const t={};for(const s of this.refreshUniforms){const i=e[s];null!=i&&("object"==typeof i&&void 0!==i.clone?!0===i.isTexture?t[s]={id:i.id,version:i.version}:t[s]=i.clone():t[s]=i)}return t}equals(e,t){const{object:s,material:i,geometry:r}=e,n=this.getRenderObjectData(e);if(!0!==n.worldMatrix.equals(s.matrixWorld))return n.worldMatrix.copy(s.matrixWorld),!1;const o=n.material;for(const e in o){const t=o[e],s=i[e];if(void 0!==t.equals){if(!1===t.equals(s))return t.copy(s),!1}else if(!0===s.isTexture){if(t.id!==s.id||t.version!==s.version)return t.id=s.id,t.version=s.version,!1}else if(t!==s)return o[e]=s,!1}if(o.transmission>0){const{width:t,height:s}=e.context;if(n.bufferWidth!==t||n.bufferHeight!==s)return n.bufferWidth=t,n.bufferHeight=s,!1}const a=n.geometry,l=r.attributes,h=a.attributes,u=Object.keys(h),c=Object.keys(l);if(a.id!==r.id)return a.id=r.id,!1;if(u.length!==c.length)return n.geometry.attributes=this.getAttributesData(l),!1;for(const e of u){const t=h[e],s=l[e];if(void 0===s)return delete h[e],!1;if(t.version!==s.version)return t.version=s.version,!1}const d=r.index,p=a.indexVersion,m=d?d.version:null;if(p!==m)return a.indexVersion=m,!1;if(a.drawRange.start!==r.drawRange.start||a.drawRange.count!==r.drawRange.count)return a.drawRange.start=r.drawRange.start,a.drawRange.count=r.drawRange.count,!1;if(n.morphTargetInfluences){let e=!1;for(let t=0;t<n.morphTargetInfluences.length;t++)n.morphTargetInfluences[t]!==s.morphTargetInfluences[t]&&(n.morphTargetInfluences[t]=s.morphTargetInfluences[t],e=!0);if(e)return!1}if(n.lights)for(let e=0;e<t.length;e++)if(n.lights[e].map!==t[e].map)return!1;return n.center&&!1===n.center.equals(s.center)?(n.center.copy(s.center),!0):(null!==e.bundle&&(n.version=e.bundle.version),!0)}getLightsData(e){const t=[];for(const s of e)!0===s.isSpotLight&&null!==s.map&&t.push({map:s.map.version});return t}getLights(e,t){if(sc.has(e)){const s=sc.get(e);if(s.renderId===t)return s.lightsData}const s=this.getLightsData(e.getLights());return sc.set(e,{renderId:t,lightsData:s}),s}needsRefresh(e,t){if(this.hasNode||this.hasAnimation||this.firstInitialization(e)||this.needsVelocity(t.renderer))return!0;const{renderId:s}=t;if(this.renderId!==s)return this.renderId=s,!0;const i=!0===e.object.static,r=null!==e.bundle&&!0===e.bundle.static&&this.getRenderObjectData(e).version===e.bundle.version;if(i||r)return!1;const n=this.getLights(e.lightsNode,s);return!0!==this.equals(e,n)}}function rc(e,t=0){let s=3735928559^t,i=1103547991^t;if(e instanceof Array)for(let t,r=0;r<e.length;r++)t=e[r],s=Math.imul(s^t,2654435761),i=Math.imul(i^t,1597334677);else for(let t,r=0;r<e.length;r++)t=e.charCodeAt(r),s=Math.imul(s^t,2654435761),i=Math.imul(i^t,1597334677);return s=Math.imul(s^s>>>16,2246822507),s^=Math.imul(i^i>>>13,3266489909),i=Math.imul(i^i>>>16,2246822507),i^=Math.imul(s^s>>>13,3266489909),4294967296*(2097151&i)+(s>>>0)}const nc=e=>rc(e),oc=e=>rc(e),ac=(...e)=>rc(e),lc=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),hc=new WeakMap;function uc(e){return lc.get(e)}function cc(e){if(/[iu]?vec\d/.test(e))return e.startsWith("ivec")?Int32Array:e.startsWith("uvec")?Uint32Array:Float32Array;if(/mat\d/.test(e))return Float32Array;if(/float/.test(e))return Float32Array;if(/uint/.test(e))return Uint32Array;if(/int/.test(e))return Int32Array;throw new Error(`THREE.NodeUtils: Unsupported type: ${e}`)}function dc(e){return/float|int|uint/.test(e)?1:/vec2/.test(e)?2:/vec3/.test(e)?3:/vec4/.test(e)||/mat2/.test(e)?4:/mat3/.test(e)?9:/mat4/.test(e)?16:void Zo("TSL: Unsupported type:",e)}function pc(e){return/float|int|uint/.test(e)?1:/vec2/.test(e)?2:/vec3/.test(e)?3:/vec4/.test(e)||/mat2/.test(e)?4:/mat3/.test(e)?12:/mat4/.test(e)?16:void Zo("TSL: Unsupported type:",e)}function mc(e){return/float|int|uint/.test(e)?4:/vec2/.test(e)?8:/vec3/.test(e)||/vec4/.test(e)?16:/mat2/.test(e)?8:/mat3/.test(e)||/mat4/.test(e)?16:void Zo("TSL: Unsupported type:",e)}function fc(e){if(null==e)return null;const t=typeof e;return!0===e.isNode?"node":"number"===t?"float":"boolean"===t?"bool":"string"===t?"string":"function"===t?"shader":!0===e.isVector2?"vec2":!0===e.isVector3?"vec3":!0===e.isVector4?"vec4":!0===e.isMatrix2?"mat2":!0===e.isMatrix3?"mat3":!0===e.isMatrix4?"mat4":!0===e.isColor?"color":e instanceof ArrayBuffer?"ArrayBuffer":null}function gc(e,...t){const s=e?e.slice(-4):void 0;return 1===t.length&&("vec2"===s?t=[t[0],t[0]]:"vec3"===s?t=[t[0],t[0],t[0]]:"vec4"===s&&(t=[t[0],t[0],t[0],t[0]])),"color"===e?new eh(...t):"vec2"===s?new ua(...t):"vec3"===s?new da(...t):"vec4"===s?new Pa(...t):"mat2"===s?new Ju(...t):"mat3"===s?new fa(...t):"mat4"===s?new ll(...t):"bool"===e?t[0]||!1:"float"===e||"int"===e||"uint"===e?t[0]||0:"string"===e?t[0]||"":"ArrayBuffer"===e?bc(t[0]):null}function yc(e){let t=hc.get(e);return void 0===t&&(t={},hc.set(e,t)),t}function xc(e){let t="";const s=new Uint8Array(e);for(let e=0;e<s.length;e++)t+=String.fromCharCode(s[e]);return btoa(t)}function bc(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0)).buffer}const _c={VERTEX:"vertex",FRAGMENT:"fragment"},wc={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},vc={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},Tc=["fragment","vertex"],Sc=["setup","analyze","generate"],Mc=[...Tc,"compute"],Ac=["x","y","z","w"],Nc={analyze:"setup",generate:"analyze"};let Ec=0;class Cc extends Ko{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=wc.NONE,this.updateBeforeType=wc.NONE,this.updateAfterType=wc.NONE,this.uuid=ha.generateUUID(),this.version=0,this.name="",this.global=!1,this.parents=!1,this.isNode=!0,this._beforeNodes=null,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:Ec++})}set needsUpdate(e){!0===e&&this.version++}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this),this}onFrameUpdate(e){return this.onUpdate(e,wc.FRAME)}onRenderUpdate(e){return this.onUpdate(e,wc.RENDER)}onObjectUpdate(e){return this.onUpdate(e,wc.OBJECT)}onReference(e){return this.updateReference=e.bind(this),this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of this._getChildren())yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}_getChildren(e=new Set){const t=[];e.add(this);for(const s of Object.getOwnPropertyNames(this)){const i=this[s];if(!0!==s.startsWith("_")&&!e.has(i))if(!0===Array.isArray(i))for(let e=0;e<i.length;e++){const r=i[e];r&&!0===r.isNode&&t.push({property:s,index:e,childNode:r})}else if(i&&!0===i.isNode)t.push({property:s,childNode:i});else if(i&&Object.getPrototypeOf(i)===Object.prototype)for(const e in i){if(!0===e.startsWith("_"))continue;const r=i[e];r&&!0===r.isNode&&t.push({property:s,index:e,childNode:r})}}return t}getCacheKey(e=!1,t=null){if(!0===(e=e||this.version!==this._cacheKeyVersion)||null===this._cacheKey){null===t&&(t=new Set);const s=[];for(const{property:i,childNode:r}of this._getChildren(t))s.push(nc(i.slice(0,-4)),r.getCacheKey(e,t));this._cacheKey=ac(oc(s),this.customCacheKey()),this._cacheKeyVersion=this.version}return this._cacheKey}customCacheKey(){return this.id}getScope(){return this}getHash(){return this.uuid}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e){const t=e.getNodeProperties(this);return t.outputNode?t.outputNode.getNodeType(e):this.nodeType}getShared(e){const t=this.getHash(e);return e.getNodeFromHash(t)||this}getArrayCount(){return null}setup(e){const t=e.getNodeProperties(this);let s=0;for(const e of this.getChildren())t["node"+s++]=e;return t.outputNode||null}analyze(e,t=null){const s=e.increaseUsage(this);if(!0===this.parents){const s=e.getDataFromNode(this,"any");s.stages=s.stages||{},s.stages[e.shaderStage]=s.stages[e.shaderStage]||[],s.stages[e.shaderStage].push(t)}if(1===s){const t=e.getNodeProperties(this);for(const s of Object.values(t))s&&!0===s.isNode&&s.build(e,this)}}generate(e,t){const{outputNode:s}=e.getNodeProperties(this);if(s&&!0===s.isNode)return s.build(e,t)}updateBefore(){Yo("Abstract function.")}updateAfter(){Yo("Abstract function.")}update(){Yo("Abstract function.")}before(e){return null===this._beforeNodes&&(this._beforeNodes=[]),this._beforeNodes.push(e),this}build(e,t=null){const s=this.getShared(e);if(this!==s)return s.build(e,t);if(null!==this._beforeNodes){const s=this._beforeNodes;this._beforeNodes=null;for(const i of s)i.build(e,t);this._beforeNodes=s}const i=e.getDataFromNode(this);i.buildStages=i.buildStages||{},i.buildStages[e.buildStage]=!0;const r=Nc[e.buildStage];if(r&&!0!==i.buildStages[r]){const t=e.getBuildStage();e.setBuildStage(r),this.build(e),e.setBuildStage(t)}e.addNode(this),e.addChain(this);let n=null;const o=e.getBuildStage();if("setup"===o){this.updateReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized){t.initialized=!0,t.outputNode=this.setup(e)||t.outputNode||null;for(const s of Object.values(t))if(s&&!0===s.isNode){if(!0===s.parents){const t=e.getNodeProperties(s);t.parents=t.parents||[],t.parents.push(this)}s.build(e)}}n=t.outputNode}else if("analyze"===o)this.analyze(e,t);else if("generate"===o){if(this.generate.length<2){const s=this.getNodeType(e),i=e.getDataFromNode(this);n=i.snippet,void 0===n?void 0===i.generated?(i.generated=!0,n=this.generate(e)||"",i.snippet=n):(Yo("Node: Recursion detected.",this),n="/* Recursion detected. */"):void 0!==i.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),n=e.format(n,s,t)}else n=this.generate(e,t)||"";""===n&&null!==t&&"void"!==t&&"OutputType"!==t&&(Zo(`TSL: Invalid generated code, expected a "${t}".`),n=e.generateConst(t))}return e.removeChain(this),e.addSequentialNode(this),n}getSerializeChildren(){return this._getChildren()}serialize(e){const t=this.getSerializeChildren(),s={};for(const{property:i,index:r,childNode:n}of t)void 0!==r?(void 0===s[i]&&(s[i]=Number.isInteger(r)?[]:{}),s[i][r]=n.toJSON(e.meta).uuid):s[i]=n.toJSON(e.meta).uuid;Object.keys(s).length>0&&(e.inputNodes=s)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const s in e.inputNodes)if(Array.isArray(e.inputNodes[s])){const i=[];for(const r of e.inputNodes[s])i.push(t[r]);this[s]=i}else if("object"==typeof e.inputNodes[s]){const i={};for(const r in e.inputNodes[s]){const n=e.inputNodes[s][r];i[r]=t[n]}this[s]=i}else{const i=e.inputNodes[s];this[s]=t[i]}}}toJSON(e){const{uuid:t,type:s}=this,i=void 0===e||"string"==typeof e;i&&(e={textures:{},images:{},nodes:{}});let r=e.nodes[t];function n(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(void 0===r&&(r={uuid:t,type:s,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},!0!==i&&(e.nodes[r.uuid]=r),this.serialize(r),delete r.meta),i){const t=n(e.textures),s=n(e.images),i=n(e.nodes);t.length>0&&(r.textures=t),s.length>0&&(r.images=s),i.length>0&&(r.nodes=i)}return r}}class Rc extends Cc{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getElementType(e)}getMemberType(e,t){return this.node.getMemberType(e,t)}generate(e){const t=this.indexNode.getNodeType(e);return`${this.node.build(e)}[ ${this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint")} ]`}}class Pc extends Cc{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let s=null;for(const i of this.convertTo.split("|"))null!==s&&e.getTypeLength(t)!==e.getTypeLength(i)||(s=i);return s}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const s=this.node,i=this.getNodeType(e),r=s.build(e,i);return e.format(r,i,t)}}class Bc extends Cc{static get type(){return"TempNode"}constructor(e=null){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if("generate"===e.getBuildStage()){const s=e.getVectorType(this.getNodeType(e,t)),i=e.getDataFromNode(this);if(void 0!==i.propertyName)return e.format(i.propertyName,s,t);if("void"!==s&&"void"!==t&&this.hasDependencies(e)){const r=super.build(e,s),n=e.getVarFromNode(this,null,s),o=e.getPropertyName(n);return e.addLineFlowCode(`${o} = ${r}`,this),i.snippet=r,i.propertyName=o,e.format(i.propertyName,s,t)}}return super.build(e,t)}}class Ic extends Bc{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}getNodeType(e){return null!==this.nodeType?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce((t,s)=>t+e.getTypeLength(s.getNodeType(e)),0))}generate(e,t){const s=this.getNodeType(e),i=e.getTypeLength(s),r=this.nodes,n=e.getComponentType(s),o=[];let a=0;for(const t of r){if(a>=i){Zo(`TSL: Length of parameters exceeds maximum length of function '${s}()' type.`);break}let r,l=t.getNodeType(e),h=e.getTypeLength(l);a+h>i&&(Zo(`TSL: Length of '${s}()' data exceeds maximum length of output type.`),h=i-a,l=e.getTypeFromLength(h)),a+=h,r=t.build(e,l);if(e.getComponentType(l)!==n){const t=e.getTypeFromLength(h,n);r=e.format(r,l,t)}o.push(r)}const l=`${e.getType(s)}( ${o.join(", ")} )`;return e.format(l,s,t)}}const Dc=Ac.join("");class Lc extends Cc{static get type(){return"SplitNode"}constructor(e,t="x"){super(),this.node=e,this.components=t,this.isSplitNode=!0}getVectorLength(){let e=this.components.length;for(const t of this.components)e=Math.max(Ac.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}getScope(){return this.node.getScope()}generate(e,t){const s=this.node,i=e.getTypeLength(s.getNodeType(e));let r=null;if(i>1){let n=null;this.getVectorLength()>=i&&(n=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const o=s.build(e,n);r=this.components.length===i&&this.components===Dc.slice(0,this.components.length)?e.format(o,n,t):e.format(`${o}.${this.components}`,this.getNodeType(e),t)}else r=s.build(e,t);return r}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class Fc extends Bc{static get type(){return"SetNode"}constructor(e,t,s){super(),this.sourceNode=e,this.components=t,this.targetNode=s}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:s,targetNode:i}=this,r=this.getNodeType(e),n=e.getComponentType(i.getNodeType(e)),o=e.getTypeFromLength(s.length,n),a=i.build(e,o),l=t.build(e,r),h=e.getTypeLength(r),u=[];for(let e=0;e<h;e++){const t=Ac[e];t===s[0]?(u.push(a),e+=s.length-1):u.push(l+"."+t)}return`${e.getType(r)}( ${u.join(", ")} )`}}class Oc extends Bc{static get type(){return"FlipNode"}constructor(e,t){super(),this.sourceNode=e,this.components=t}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{components:t,sourceNode:s}=this,i=this.getNodeType(e),r=s.build(e),n=e.getVarFromNode(this),o=e.getPropertyName(n);e.addLineFlowCode(o+" = "+r,this);const a=e.getTypeLength(i),l=[];let h=0;for(let e=0;e<a;e++){const s=Ac[e];s===t[h]?(l.push("1.0 - "+o+"."+s),h++):l.push(o+"."+s)}return`${e.getType(i)}( ${l.join(", ")} )`}}class Vc extends Cc{static get type(){return"InputNode"}constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}getNodeType(){return null===this.nodeType?fc(this.value):this.nodeType}getInputType(e){return this.getNodeType(e)}setPrecision(e){return this.precision=e,this}serialize(e){super.serialize(e),e.value=this.value,this.value&&this.value.toArray&&(e.value=this.value.toArray()),e.valueType=fc(this.value),e.nodeType=this.nodeType,"ArrayBuffer"===e.valueType&&(e.value=xc(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?gc(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){Yo("Abstract function.")}}const zc=/float|u?int/;class kc extends Vc{static get type(){return"ConstNode"}constructor(e,t=null){super(e,t),this.isConstNode=!0}generateConst(e){return e.generateConst(this.getNodeType(e),this.value)}generate(e,t){const s=this.getNodeType(e);return zc.test(s)&&zc.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),s,t)}}class Uc extends Cc{static get type(){return"MemberNode"}constructor(e,t){super(),this.structNode=e,this.property=t,this.isMemberNode=!0}hasMember(e){return(!this.structNode.isMemberNode||!1!==this.structNode.hasMember(e))&&"void"!==this.structNode.getMemberType(e,this.property)}getNodeType(e){return!1===this.hasMember(e)?"float":this.structNode.getMemberType(e,this.property)}getMemberType(e,t){if(!1===this.hasMember(e))return"float";const s=this.getNodeType(e);return e.getStructTypeNode(s).getMemberType(e,t)}generate(e){if(!1===this.hasMember(e)){Yo(`TSL: Member "${this.property}" does not exist in struct.`);const t=this.getNodeType(e);return e.generateConst(t)}return this.structNode.build(e)+"."+this.property}}let Gc=null;const jc=new Map;function $c(e,t){if(jc.has(e))Yo(`TSL: Redefinition of method chaining '${e}'.`);else{if("function"!=typeof t)throw new Error(`THREE.TSL: Node element ${e} is not a function`);jc.set(e,t),"assign"!==e&&(Cc.prototype[e]=function(...e){return this.isStackNode?this.addToStack(t(...e)):t(this,...e)},Cc.prototype[e+"Assign"]=function(...e){return this.isStackNode?this.assign(e[0],t(...e)):this.assign(t(this,...e))})}}const Wc=e=>(e=>e.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"))(e).split("").sort().join("");Cc.prototype.assign=function(...e){if(!0!==this.isStackNode)return null!==Gc?Gc.assign(this,...e):Zo("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn()."),this;{const t=jc.get("assign");return this.addToStack(t(...e))}},Cc.prototype.toVarIntent=function(){return this},Cc.prototype.get=function(e){return new Uc(this,e)};const Hc={};function qc(e,t,s){Hc[e]=Hc[t]=Hc[s]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new Lc(this,e),this._cache[e]=t),t},set(t){this[e].assign(bd(t))}};const i=e.toUpperCase(),r=t.toUpperCase(),n=s.toUpperCase();Cc.prototype["set"+i]=Cc.prototype["set"+r]=Cc.prototype["set"+n]=function(t){const s=Wc(e);return new Fc(this,s,bd(t))},Cc.prototype["flip"+i]=Cc.prototype["flip"+r]=Cc.prototype["flip"+n]=function(){const t=Wc(e);return new Oc(this,t)}}const Xc=["x","y","z","w"],Yc=["r","g","b","a"],Zc=["s","t","p","q"];for(let e=0;e<4;e++){let t=Xc[e],s=Yc[e],i=Zc[e];qc(t,s,i);for(let r=0;r<4;r++){t=Xc[e]+Xc[r],s=Yc[e]+Yc[r],i=Zc[e]+Zc[r],qc(t,s,i);for(let n=0;n<4;n++){t=Xc[e]+Xc[r]+Xc[n],s=Yc[e]+Yc[r]+Yc[n],i=Zc[e]+Zc[r]+Zc[n],qc(t,s,i);for(let o=0;o<4;o++)t=Xc[e]+Xc[r]+Xc[n]+Xc[o],s=Yc[e]+Yc[r]+Yc[n]+Yc[o],i=Zc[e]+Zc[r]+Zc[n]+Zc[o],qc(t,s,i)}}}for(let e=0;e<32;e++)Hc[e]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new Rc(this,new kc(e,"uint")),this._cache[e]=t),t},set(t){this[e].assign(bd(t))}};Object.defineProperties(Cc.prototype,Hc);const Qc=new WeakMap,Kc=function(e,t=null){for(const s in e)e[s]=bd(e[s],t);return e},Jc=function(e,t=null){const s=e.length;for(let i=0;i<s;i++)e[i]=bd(e[i],t);return e},ed=function(e,t=null,s=null,i=null){function r(e){return null!==i?(e=bd(Object.assign(e,i)),!0===i.intent&&(e=e.toVarIntent())):e=bd(e),e}let n,o,a,l=t;function h(t){let s;return s=l?/[a-z]/i.test(l)?l+"()":l:e.type,void 0!==o&&t.length<o?(Zo(`TSL: "${s}" parameter length is less than minimum required.`),t.concat(new Array(o-t.length).fill(0))):void 0!==a&&t.length>a?(Zo(`TSL: "${s}" parameter length exceeds limit.`),t.slice(0,a)):t}return null===t?n=(...t)=>r(new e(...vd(h(t)))):null!==s?(s=bd(s),n=(...i)=>r(new e(t,...vd(h(i)),s))):n=(...s)=>r(new e(t,...vd(h(s)))),n.setParameterLength=(...e)=>(1===e.length?o=a=e[0]:2===e.length&&([o,a]=e),n),n.setName=e=>(l=e,n),n},td=function(e,...t){return new e(...vd(t))};class sd extends Cc{constructor(e,t){super(),this.shaderNode=e,this.rawInputs=t,this.isShaderCallNodeInternal=!0}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getElementType(e){return this.getOutputNode(e).getElementType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,rawInputs:s}=this,i=e.getNodeProperties(t),r=e.getClosestSubBuild(t.subBuilds)||"",n=r||"default";if(i[n])return i[n];const o=e.subBuildFn,a=e.fnCall;e.subBuildFn=r,e.fnCall=this;let l=null;if(t.layout){let i=Qc.get(e.constructor);void 0===i&&(i=new WeakMap,Qc.set(e.constructor,i));let r=i.get(t);void 0===r&&(r=bd(e.buildFunctionNode(t)),i.set(t,r)),e.addInclude(r);const n=s?function(e){let t;wd(e);t=e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)?[...e]:e[0];return t}(s):null;l=bd(r.call(n))}else{const i=new Proxy(e,{get:(e,t,s)=>{let i;return i=Symbol.iterator===t?function*(){yield}:Reflect.get(e,t,s),i}}),r=s?function(e){let t=0;return wd(e),new Proxy(e,{get:(s,i,r)=>{let n;if("length"===i)return n=e.length,n;if(Symbol.iterator===i)n=function*(){for(const t of e)yield bd(t)};else{if(e.length>0)if(Object.getPrototypeOf(e[0])===Object.prototype){const s=e[0];n=void 0===s[i]?s[t++]:Reflect.get(s,i,r)}else e[0]instanceof Cc&&(n=void 0===e[i]?e[t++]:Reflect.get(e,i,r));else n=Reflect.get(s,i,r);n=bd(n)}return n}})}(s):null,n=Array.isArray(s)?s.length>0:null!==s,o=t.jsFunc,a=n||o.length>1?o(r,i):o(i);l=bd(a)}return e.subBuildFn=o,e.fnCall=a,t.once&&(i[n]=l),l}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),s=e.getSubBuildOutput(this);return t[s]=t[s]||this.setupOutput(e),t[s].subBuild=e.getClosestSubBuild(this),t[s]}build(e,t=null){let s=null;const i=e.getBuildStage(),r=e.getNodeProperties(this),n=e.getSubBuildOutput(this),o=this.getOutputNode(e),a=e.fnCall;if(e.fnCall=this,"setup"===i){const t=e.getSubBuildProperty("initialized",this);if(!0!==r[t]&&(r[t]=!0,r[n]=this.getOutputNode(e),r[n].build(e),this.shaderNode.subBuilds))for(const t of e.chaining){const s=e.getDataFromNode(t,"any");s.subBuilds=s.subBuilds||new Set;for(const e of this.shaderNode.subBuilds)s.subBuilds.add(e)}s=r[n]}else"analyze"===i?o.build(e,t):"generate"===i&&(s=o.build(e,t)||"");return e.fnCall=a,s}}class id extends Cc{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}getLayout(){return this.layout}call(e=null){return new sd(this,e)}setup(){return this.call()}}const rd=[!1,!0],nd=[0,1,2,3],od=[-1,-2],ad=[.5,1.5,1/3,1e-6,1e6,Math.PI,2*Math.PI,1/Math.PI,2/Math.PI,1/(2*Math.PI),Math.PI/2],ld=new Map;for(const e of rd)ld.set(e,new kc(e));const hd=new Map;for(const e of nd)hd.set(e,new kc(e,"uint"));const ud=new Map([...hd].map(e=>new kc(e.value,"int")));for(const e of od)ud.set(e,new kc(e,"int"));const cd=new Map([...ud].map(e=>new kc(e.value)));for(const e of ad)cd.set(e,new kc(e));for(const e of ad)cd.set(-e,new kc(-e));const dd={bool:ld,uint:hd,ints:ud,float:cd},pd=new Map([...ld,...cd]),md=(e,t)=>pd.has(e)?pd.get(e):!0===e.isNode?e:new kc(e,t),fd=function(e,t=null){return(...s)=>{for(const t of s)if(void 0===t)return Zo(`TSL: Invalid parameter for the type "${e}".`),new kc(0,e);if((0===s.length||!["bool","float","int","uint"].includes(e)&&s.every(e=>{const t=typeof e;return"object"!==t&&"function"!==t}))&&(s=[gc(e,...s)]),1===s.length&&null!==t&&t.has(s[0]))return _d(t.get(s[0]));if(1===s.length){const t=md(s[0],e);return t.nodeType===e?_d(t):_d(new Pc(t,e))}const i=s.map(e=>md(e));return _d(new Ic(i,e))}},gd=e=>"object"==typeof e&&null!==e?e.value:e,yd=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function xd(e,t){return new id(e,t)}const bd=(e,t=null)=>function(e,t=null){const s=fc(e);return"node"===s?e:null===t&&("float"===s||"boolean"===s)||s&&"shader"!==s&&"string"!==s?bd(md(e,t)):"shader"===s?e.isFn?e:Ed(e):e}(e,t),_d=(e,t=null)=>bd(e,t).toVarIntent(),wd=(e,t=null)=>new Kc(e,t),vd=(e,t=null)=>new Jc(e,t),Td=(e,t=null,s=null,i=null)=>new ed(e,t,s,i),Sd=(e,...t)=>new td(e,...t),Md=(e,t=null,s=null,i={})=>new ed(e,t,s,{...i,intent:!0});let Ad=0;class Nd extends Cc{constructor(e,t=null){super();let s=null;null!==t&&("object"==typeof t?s=t.return:("string"==typeof t?s=t:Zo("TSL: Invalid layout type."),t=null)),this.shaderNode=new xd(e,s),null!==t&&this.setLayout(t),this.isFn=!0}setLayout(e){const t=this.shaderNode.nodeType;if("object"!=typeof e.inputs){const s={name:"fn"+Ad++,type:t,inputs:[]};for(const t in e)"return"!==t&&s.inputs.push({name:t,type:e[t]});e=s}return this.shaderNode.setLayout(e),this}getNodeType(e){return this.shaderNode.getNodeType(e)||"float"}call(...e){const t=this.shaderNode.call(e);return"void"===this.shaderNode.nodeType&&t.toStack(),t.toVarIntent()}once(e=null){return this.shaderNode.once=!0,this.shaderNode.subBuilds=e,this}generate(e){const t=this.getNodeType(e);return Zo('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".'),e.generateConst(t)}}function Ed(e,t=null){const s=new Nd(e,t);return new Proxy(()=>{},{apply:(e,t,i)=>s.call(...i),get:(e,t,i)=>Reflect.get(s,t,i),set:(e,t,i,r)=>Reflect.set(s,t,i,r)})}const Cd=e=>{Gc=e},Rd=()=>Gc,Pd=(...e)=>Gc.If(...e);function Bd(e){return Gc&&Gc.addToStack(e),e}$c("toStack",Bd);const Id=new fd("color"),Dd=new fd("float",dd.float),Ld=new fd("int",dd.ints),Fd=new fd("uint",dd.uint),Od=new fd("bool",dd.bool),Vd=new fd("vec2"),zd=new fd("ivec2"),kd=new fd("uvec2"),Ud=new fd("bvec2"),Gd=new fd("vec3"),jd=new fd("ivec3"),$d=new fd("uvec3"),Wd=new fd("bvec3"),Hd=new fd("vec4"),qd=new fd("ivec4"),Xd=new fd("uvec4"),Yd=new fd("bvec4"),Zd=new fd("mat2"),Qd=new fd("mat3"),Kd=new fd("mat4");$c("toColor",Id),$c("toFloat",Dd),$c("toInt",Ld),$c("toUint",Fd),$c("toBool",Od),$c("toVec2",Vd),$c("toIVec2",zd),$c("toUVec2",kd),$c("toBVec2",Ud),$c("toVec3",Gd),$c("toIVec3",jd),$c("toUVec3",$d),$c("toBVec3",Wd),$c("toVec4",Hd),$c("toIVec4",qd),$c("toUVec4",Xd),$c("toBVec4",Yd),$c("toMat2",Zd),$c("toMat3",Qd),$c("toMat4",Kd);const Jd=Td(Rc).setParameterLength(2),ep=(e,t)=>bd(new Pc(bd(e),t));$c("element",Jd),$c("convert",ep);$c("append",e=>(Yo("TSL: .append() has been renamed to .toStack()."),Bd(e)));class tp extends Cc{static get type(){return"PropertyNode"}constructor(e,t=null,s=!1){super(e),this.name=t,this.varying=s,this.isPropertyNode=!0,this.global=!0}customCacheKey(){return nc(this.type+":"+(this.name||"")+":"+(this.varying?"1":"0"))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;return!0===this.varying?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const sp=(e,t)=>new tp(e,t),ip=(e,t)=>new tp(e,t,!0),rp=Sd(tp,"vec4","DiffuseColor"),np=Sd(tp,"vec3","DiffuseContribution"),op=Sd(tp,"vec3","EmissiveColor"),ap=Sd(tp,"float","Roughness"),lp=Sd(tp,"float","Metalness"),hp=Sd(tp,"float","Clearcoat"),up=Sd(tp,"float","ClearcoatRoughness"),cp=Sd(tp,"vec3","Sheen"),dp=Sd(tp,"float","SheenRoughness"),pp=Sd(tp,"float","Iridescence"),mp=Sd(tp,"float","IridescenceIOR"),fp=Sd(tp,"float","IridescenceThickness"),gp=Sd(tp,"float","AlphaT"),yp=Sd(tp,"float","Anisotropy"),xp=Sd(tp,"vec3","AnisotropyT"),bp=Sd(tp,"vec3","AnisotropyB"),_p=Sd(tp,"color","SpecularColor"),wp=Sd(tp,"color","SpecularColorBlended"),vp=Sd(tp,"float","SpecularF90"),Tp=Sd(tp,"float","Shininess"),Sp=Sd(tp,"vec4","Output"),Mp=Sd(tp,"float","dashSize"),Ap=Sd(tp,"float","gapSize"),Np=Sd(tp,"float","pointWidth"),Ep=Sd(tp,"float","IOR"),Cp=Sd(tp,"float","Transmission"),Rp=Sd(tp,"float","Thickness"),Pp=Sd(tp,"float","AttenuationDistance"),Bp=Sd(tp,"color","AttenuationColor"),Ip=Sd(tp,"float","Dispersion");class Dp extends Cc{static get type(){return"UniformGroupNode"}constructor(e,t=!1,s=1){super("string"),this.name=e,this.shared=t,this.order=s,this.isUniformGroup=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const Lp=e=>new Dp(e),Fp=(e,t=0)=>new Dp(e,!0,t),Op=Fp("frame"),Vp=Fp("render"),zp=Lp("object");class kp extends Vc{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=zp}setName(e){return this.name=e,this}label(e){return Yo('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){return e=e.bind(this),super.onUpdate(t=>{const s=e(t,this);void 0!==s&&(this.value=s)},t)}getInputType(e){let t=super.getInputType(e);return"bool"===t&&(t="uint"),t}generate(e,t){const s=this.getNodeType(e),i=this.getUniformHash(e);let r=e.getNodeFromHash(i);void 0===r&&(e.setHashNode(this,i),r=this);const n=r.getInputType(e),o=e.getUniformFromNode(r,n,e.shaderStage,this.name||e.context.nodeName),a=e.getPropertyName(o);void 0!==e.context.nodeName&&delete e.context.nodeName;let l=a;if("bool"===s){const t=e.getDataFromNode(this);let i=t.propertyName;if(void 0===i){const r=e.getVarFromNode(this,null,"bool");i=e.getPropertyName(r),t.propertyName=i,l=e.format(a,n,s),e.addLineFlowCode(`${i} = ${l}`,this)}l=i}return e.format(l,s,t)}}const Up=(e,t)=>{const s=yd(t||e);if(s===e&&(e=gc(s)),e&&!0===e.isNode){let t=e.value;e.traverse(e=>{!0===e.isConstNode&&(t=e.value)}),e=t}return new kp(e,s)};class Gp extends Bc{static get type(){return"ArrayNode"}constructor(e,t,s=null){super(e),this.count=t,this.values=s,this.isArrayNode=!0}getArrayCount(){return this.count}getNodeType(e){return null===this.nodeType?this.values[0].getNodeType(e):this.nodeType}getElementType(e){return this.getNodeType(e)}getMemberType(e,t){return null===this.nodeType?this.values[0].getMemberType(e,t):super.getMemberType(e,t)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}const jp=(...e)=>{let t;if(1===e.length){const s=e[0];t=new Gp(null,s.length,s)}else{const s=e[0],i=e[1];t=new Gp(s,i)}return bd(t)};$c("toArray",(e,t)=>jp(Array(t).fill(e)));class $p extends Bc{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}getNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(!1===e.isAvailable("swizzleAssign")&&t.isSplitNode&&t.components.length>1){const s=e.getTypeLength(t.node.getNodeType(e));return Ac.join("").slice(0,s)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:s}=this,i=t.getScope();e.getDataFromNode(i).assign=!0;const r=e.getNodeProperties(this);r.sourceNode=s,r.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:s,sourceNode:i}=e.getNodeProperties(this),r=this.needsSplitAssign(e),n=s.build(e),o=s.getNodeType(e),a=i.build(e,o),l=i.getNodeType(e),h=e.getDataFromNode(this);let u;if(!0===h.initialized)"void"!==t&&(u=n);else if(r){const i=e.getVarFromNode(this,null,o),r=e.getPropertyName(i);e.addLineFlowCode(`${r} = ${a}`,this);const l=s.node,h=l.node.context({assign:!0}).build(e);for(let t=0;t<l.components.length;t++){const s=l.components[t];e.addLineFlowCode(`${h}.${s} = ${r}[ ${t} ]`,this)}"void"!==t&&(u=n)}else u=`${n} = ${a}`,"void"!==t&&"void"!==l||(e.addLineFlowCode(u,this),"void"!==t&&(u=n));return h.initialized=!0,e.format(u,o,t)}}const Wp=Td($p).setParameterLength(2);$c("assign",Wp);class Hp extends Bc{static get type(){return"FunctionCallNode"}constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}getNodeType(e){return this.functionNode.getNodeType(e)}getMemberType(e,t){return this.functionNode.getMemberType(e,t)}generate(e){const t=[],s=this.functionNode,i=s.getInputs(e),r=this.parameters,n=(t,s)=>{const i=s.type;let r;return r="pointer"===i?"&"+t.build(e):t.build(e,i),r};if(Array.isArray(r)){if(r.length>i.length)Zo("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),r.length=i.length;else if(r.length<i.length)for(Zo("TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");r.length<i.length;)r.push(Dd(0));for(let e=0;e<r.length;e++)t.push(n(r[e],i[e]))}else for(const e of i){const s=r[e.name];void 0!==s?t.push(n(s,e)):(Zo(`TSL: Input '${e.name}' not found in 'Fn()'.`),t.push(n(Dd(0),e)))}return`${s.build(e,"property")}( ${t.join(", ")} )`}}const qp=(e,...t)=>(t=t.length>1||t[0]&&!0===t[0].isNode?vd(t):wd(t[0]),new Hp(bd(e),t));$c("call",qp);const Xp={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class Yp extends Bc{static get type(){return"OperatorNode"}constructor(e,t,s,...i){if(super(),i.length>0){let r=new Yp(e,t,s);for(let t=0;t<i.length-1;t++)r=new Yp(e,r,i[t]);t=r,s=i[i.length-1]}this.op=e,this.aNode=t,this.bNode=s,this.isOperatorNode=!0}getOperatorMethod(e,t){return e.getMethod(Xp[this.op],t)}getNodeType(e,t=null){const s=this.op,i=this.aNode,r=this.bNode,n=i.getNodeType(e),o=r?r.getNodeType(e):null;if("void"===n||"void"===o)return t||"void";if("%"===s)return n;if("~"===s||"&"===s||"|"===s||"^"===s||">>"===s||"<<"===s)return e.getIntegerType(n);if("!"===s||"&&"===s||"||"===s||"^^"===s)return"bool";if("=="===s||"!="===s||"<"===s||">"===s||"<="===s||">="===s){const t=Math.max(e.getTypeLength(n),e.getTypeLength(o));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(n)){if("float"===o)return n;if(e.isVector(o))return e.getVectorFromMatrix(n);if(e.isMatrix(o))return n}else if(e.isMatrix(o)){if("float"===n)return o;if(e.isVector(n))return e.getVectorFromMatrix(o)}return e.getTypeLength(o)>e.getTypeLength(n)?o:n}generate(e,t){const s=this.op,{aNode:i,bNode:r}=this,n=this.getNodeType(e,t);let o=null,a=null;"void"!==n?(o=i.getNodeType(e),a=r?r.getNodeType(e):null,"<"===s||">"===s||"<="===s||">="===s||"=="===s||"!="===s?e.isVector(o)?a=o:e.isVector(a)?o=a:o!==a&&(o=a="float"):">>"===s||"<<"===s?(o=n,a=e.changeComponentType(a,"uint")):"%"===s?(o=n,a=e.isInteger(o)&&e.isInteger(a)?a:o):e.isMatrix(o)?"float"===a?a="float":e.isVector(a)?a=e.getVectorFromMatrix(o):e.isMatrix(a)||(o=a=n):o=e.isMatrix(a)?"float"===o?"float":e.isVector(o)?e.getVectorFromMatrix(a):a=n:a=n):o=a=n;const l=i.build(e,o),h=r?r.build(e,a):null,u=e.getFunctionOperator(s);if("void"!==t){const i=e.renderer.coordinateSystem===ko;if("=="===s||"!="===s||"<"===s||">"===s||"<="===s||">="===s)return i&&e.isVector(o)?e.format(`${this.getOperatorMethod(e,t)}( ${l}, ${h} )`,n,t):e.format(`( ${l} ${s} ${h} )`,n,t);if("%"===s)return e.isInteger(a)?e.format(`( ${l} % ${h} )`,n,t):e.format(`${this.getOperatorMethod(e,n)}( ${l}, ${h} )`,n,t);if("!"===s||"~"===s)return e.format(`(${s}${l})`,o,t);if(u)return e.format(`${u}( ${l}, ${h} )`,n,t);if(e.isMatrix(o)&&"float"===a)return e.format(`( ${h} ${s} ${l} )`,n,t);if("float"===o&&e.isMatrix(a))return e.format(`${l} ${s} ${h}`,n,t);{let r=`( ${l} ${s} ${h} )`;return!i&&"bool"===n&&e.isVector(o)&&e.isVector(a)&&(r=`all${r}`),e.format(r,n,t)}}if("void"!==o)return u?e.format(`${u}( ${l}, ${h} )`,n,t):e.isMatrix(o)&&"float"===a?e.format(`${h} ${s} ${l}`,n,t):e.format(`${l} ${s} ${h}`,n,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const Zp=Md(Yp,"+").setParameterLength(2,1/0).setName("add"),Qp=Md(Yp,"-").setParameterLength(2,1/0).setName("sub"),Kp=Md(Yp,"*").setParameterLength(2,1/0).setName("mul"),Jp=Md(Yp,"/").setParameterLength(2,1/0).setName("div"),em=Md(Yp,"%").setParameterLength(2).setName("mod"),tm=Md(Yp,"==").setParameterLength(2).setName("equal"),sm=Md(Yp,"!=").setParameterLength(2).setName("notEqual"),im=Md(Yp,"<").setParameterLength(2).setName("lessThan"),rm=Md(Yp,">").setParameterLength(2).setName("greaterThan"),nm=Md(Yp,"<=").setParameterLength(2).setName("lessThanEqual"),om=Md(Yp,">=").setParameterLength(2).setName("greaterThanEqual"),am=Md(Yp,"&&").setParameterLength(2,1/0).setName("and"),lm=Md(Yp,"||").setParameterLength(2,1/0).setName("or"),hm=Md(Yp,"!").setParameterLength(1).setName("not"),um=Md(Yp,"^^").setParameterLength(2).setName("xor"),cm=Md(Yp,"&").setParameterLength(2).setName("bitAnd"),dm=Md(Yp,"~").setParameterLength(1).setName("bitNot"),pm=Md(Yp,"|").setParameterLength(2).setName("bitOr"),mm=Md(Yp,"^").setParameterLength(2).setName("bitXor"),fm=Md(Yp,"<<").setParameterLength(2).setName("shiftLeft"),gm=Md(Yp,">>").setParameterLength(2).setName("shiftRight"),ym=Ed(([e])=>(e.addAssign(1),e)),xm=Ed(([e])=>(e.subAssign(1),e)),bm=Ed(([e])=>{const t=Ld(e).toConst();return e.addAssign(1),t}),_m=Ed(([e])=>{const t=Ld(e).toConst();return e.subAssign(1),t});$c("add",Zp),$c("sub",Qp),$c("mul",Kp),$c("div",Jp),$c("mod",em),$c("equal",tm),$c("notEqual",sm),$c("lessThan",im),$c("greaterThan",rm),$c("lessThanEqual",nm),$c("greaterThanEqual",om),$c("and",am),$c("or",lm),$c("not",hm),$c("xor",um),$c("bitAnd",cm),$c("bitNot",dm),$c("bitOr",pm),$c("bitXor",mm),$c("shiftLeft",fm),$c("shiftRight",gm),$c("incrementBefore",ym),$c("decrementBefore",xm),$c("increment",bm),$c("decrement",_m);const wm=(e,t)=>(Yo('TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.'),em(Ld(e),Ld(t)));$c("modInt",wm);class vm extends Bc{static get type(){return"MathNode"}constructor(e,t,s=null,i=null){if(super(),(e===vm.MAX||e===vm.MIN)&&arguments.length>3){let r=new vm(e,t,s);for(let t=2;t<arguments.length-1;t++)r=new vm(e,r,arguments[t]);t=r,s=arguments[arguments.length-1],i=null}this.method=e,this.aNode=t,this.bNode=s,this.cNode=i,this.isMathNode=!0}getInputType(e){const t=this.aNode.getNodeType(e),s=this.bNode?this.bNode.getNodeType(e):null,i=this.cNode?this.cNode.getNodeType(e):null,r=e.isMatrix(t)?0:e.getTypeLength(t),n=e.isMatrix(s)?0:e.getTypeLength(s),o=e.isMatrix(i)?0:e.getTypeLength(i);return r>n&&r>o?t:n>o?s:o>r?i:t}getNodeType(e){const t=this.method;return t===vm.LENGTH||t===vm.DISTANCE||t===vm.DOT?"float":t===vm.CROSS?"vec3":t===vm.ALL||t===vm.ANY?"bool":t===vm.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:s,method:i}=this;let r=null;if(i===vm.ONE_MINUS)r=Qp(1,t);else if(i===vm.RECIPROCAL)r=Jp(1,t);else if(i===vm.DIFFERENCE)r=Ym(Qp(t,s));else if(i===vm.TRANSFORM_DIRECTION){let i=t,n=s;e.isMatrix(i.getNodeType(e))?n=Hd(Gd(n),0):i=Hd(Gd(i),0);const o=Kp(i,n).xyz;r=Um(o)}return null!==r?r:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let s=this.method;const i=this.getNodeType(e),r=this.getInputType(e),n=this.aNode,o=this.bNode,a=this.cNode,l=e.renderer.coordinateSystem;if(s===vm.NEGATE)return e.format("( - "+n.build(e,r)+" )",i,t);{const h=[];return s===vm.CROSS?h.push(n.build(e,i),o.build(e,i)):l===ko&&s===vm.STEP?h.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":r),o.build(e,r)):l!==ko||s!==vm.MIN&&s!==vm.MAX?s===vm.REFRACT?h.push(n.build(e,r),o.build(e,r),a.build(e,"float")):s===vm.MIX?h.push(n.build(e,r),o.build(e,r),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":r)):(l===Uo&&s===vm.ATAN&&null!==o&&(s="atan2"),"fragment"===e.shaderStage||s!==vm.DFDX&&s!==vm.DFDY||(Yo(`TSL: '${s}' is not supported in the ${e.shaderStage} stage.`),s="/*"+s+"*/"),h.push(n.build(e,r)),null!==o&&h.push(o.build(e,r)),null!==a&&h.push(a.build(e,r))):h.push(n.build(e,r),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":r)),e.format(`${e.getMethod(s,i)}( ${h.join(", ")} )`,i,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}vm.ALL="all",vm.ANY="any",vm.RADIANS="radians",vm.DEGREES="degrees",vm.EXP="exp",vm.EXP2="exp2",vm.LOG="log",vm.LOG2="log2",vm.SQRT="sqrt",vm.INVERSE_SQRT="inversesqrt",vm.FLOOR="floor",vm.CEIL="ceil",vm.NORMALIZE="normalize",vm.FRACT="fract",vm.SIN="sin",vm.COS="cos",vm.TAN="tan",vm.ASIN="asin",vm.ACOS="acos",vm.ATAN="atan",vm.ABS="abs",vm.SIGN="sign",vm.LENGTH="length",vm.NEGATE="negate",vm.ONE_MINUS="oneMinus",vm.DFDX="dFdx",vm.DFDY="dFdy",vm.ROUND="round",vm.RECIPROCAL="reciprocal",vm.TRUNC="trunc",vm.FWIDTH="fwidth",vm.TRANSPOSE="transpose",vm.DETERMINANT="determinant",vm.INVERSE="inverse",vm.EQUALS="equals",vm.MIN="min",vm.MAX="max",vm.STEP="step",vm.REFLECT="reflect",vm.DISTANCE="distance",vm.DIFFERENCE="difference",vm.DOT="dot",vm.CROSS="cross",vm.POW="pow",vm.TRANSFORM_DIRECTION="transformDirection",vm.MIX="mix",vm.CLAMP="clamp",vm.REFRACT="refract",vm.SMOOTHSTEP="smoothstep",vm.FACEFORWARD="faceforward";const Tm=Dd(1e-6),Sm=Dd(1e6),Mm=Dd(Math.PI),Am=Dd(2*Math.PI),Nm=Dd(2*Math.PI),Em=Dd(.5*Math.PI),Cm=Md(vm,vm.ALL).setParameterLength(1),Rm=Md(vm,vm.ANY).setParameterLength(1),Pm=Md(vm,vm.RADIANS).setParameterLength(1),Bm=Md(vm,vm.DEGREES).setParameterLength(1),Im=Md(vm,vm.EXP).setParameterLength(1),Dm=Md(vm,vm.EXP2).setParameterLength(1),Lm=Md(vm,vm.LOG).setParameterLength(1),Fm=Md(vm,vm.LOG2).setParameterLength(1),Om=Md(vm,vm.SQRT).setParameterLength(1),Vm=Md(vm,vm.INVERSE_SQRT).setParameterLength(1),zm=Md(vm,vm.FLOOR).setParameterLength(1),km=Md(vm,vm.CEIL).setParameterLength(1),Um=Md(vm,vm.NORMALIZE).setParameterLength(1),Gm=Md(vm,vm.FRACT).setParameterLength(1),jm=Md(vm,vm.SIN).setParameterLength(1),$m=Md(vm,vm.COS).setParameterLength(1),Wm=Md(vm,vm.TAN).setParameterLength(1),Hm=Md(vm,vm.ASIN).setParameterLength(1),qm=Md(vm,vm.ACOS).setParameterLength(1),Xm=Md(vm,vm.ATAN).setParameterLength(1,2),Ym=Md(vm,vm.ABS).setParameterLength(1),Zm=Md(vm,vm.SIGN).setParameterLength(1),Qm=Md(vm,vm.LENGTH).setParameterLength(1),Km=Md(vm,vm.NEGATE).setParameterLength(1),Jm=Md(vm,vm.ONE_MINUS).setParameterLength(1),ef=Md(vm,vm.DFDX).setParameterLength(1),tf=Md(vm,vm.DFDY).setParameterLength(1),sf=Md(vm,vm.ROUND).setParameterLength(1),rf=Md(vm,vm.RECIPROCAL).setParameterLength(1),nf=Md(vm,vm.TRUNC).setParameterLength(1),of=Md(vm,vm.FWIDTH).setParameterLength(1),af=Md(vm,vm.TRANSPOSE).setParameterLength(1),lf=Md(vm,vm.DETERMINANT).setParameterLength(1),hf=Md(vm,vm.INVERSE).setParameterLength(1),uf=(e,t)=>(Yo('TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"'),tm(e,t)),cf=Md(vm,vm.MIN).setParameterLength(2,1/0),df=Md(vm,vm.MAX).setParameterLength(2,1/0),pf=Md(vm,vm.STEP).setParameterLength(2),mf=Md(vm,vm.REFLECT).setParameterLength(2),ff=Md(vm,vm.DISTANCE).setParameterLength(2),gf=Md(vm,vm.DIFFERENCE).setParameterLength(2),yf=Md(vm,vm.DOT).setParameterLength(2),xf=Md(vm,vm.CROSS).setParameterLength(2),bf=Md(vm,vm.POW).setParameterLength(2),_f=e=>Kp(e,e),wf=e=>Kp(e,e,e),vf=e=>Kp(e,e,e,e),Tf=Md(vm,vm.TRANSFORM_DIRECTION).setParameterLength(2),Sf=e=>Kp(Zm(e),bf(Ym(e),1/3)),Mf=e=>yf(e,e),Af=Md(vm,vm.MIX).setParameterLength(3),Nf=(e,t=0,s=1)=>bd(new vm(vm.CLAMP,bd(e),bd(t),bd(s))),Ef=e=>Nf(e),Cf=Md(vm,vm.REFRACT).setParameterLength(3),Rf=Md(vm,vm.SMOOTHSTEP).setParameterLength(3),Pf=Md(vm,vm.FACEFORWARD).setParameterLength(3),Bf=Ed(([e])=>{const t=yf(e.xy,Vd(12.9898,78.233)),s=em(t,Mm);return Gm(jm(s).mul(43758.5453))}),If=(e,t,s)=>Af(t,s,e),Df=(e,t,s)=>Rf(t,s,e),Lf=(e,t)=>pf(t,e),Ff=(e,t)=>(Yo('TSL: "atan2" is overloaded. Use "atan" instead.'),Xm(e,t)),Of=Pf,Vf=Vm;$c("all",Cm),$c("any",Rm),$c("equals",uf),$c("radians",Pm),$c("degrees",Bm),$c("exp",Im),$c("exp2",Dm),$c("log",Lm),$c("log2",Fm),$c("sqrt",Om),$c("inverseSqrt",Vm),$c("floor",zm),$c("ceil",km),$c("normalize",Um),$c("fract",Gm),$c("sin",jm),$c("cos",$m),$c("tan",Wm),$c("asin",Hm),$c("acos",qm),$c("atan",Xm),$c("abs",Ym),$c("sign",Zm),$c("length",Qm),$c("lengthSq",Mf),$c("negate",Km),$c("oneMinus",Jm),$c("dFdx",ef),$c("dFdy",tf),$c("round",sf),$c("reciprocal",rf),$c("trunc",nf),$c("fwidth",of),$c("atan2",Ff),$c("min",cf),$c("max",df),$c("step",Lf),$c("reflect",mf),$c("distance",ff),$c("dot",yf),$c("cross",xf),$c("pow",bf),$c("pow2",_f),$c("pow3",wf),$c("pow4",vf),$c("transformDirection",Tf),$c("mix",If),$c("clamp",Nf),$c("refract",Cf),$c("smoothstep",Df),$c("faceForward",Pf),$c("difference",gf),$c("saturate",Ef),$c("cbrt",Sf),$c("transpose",af),$c("determinant",lf),$c("inverse",hf),$c("rand",Bf);class zf extends Cc{static get type(){return"ConditionalNode"}constructor(e,t,s=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=s}getNodeType(e){const{ifNode:t,elseNode:s}=e.getNodeProperties(this);if(void 0===t)return e.flowBuildStage(this,"setup"),this.getNodeType(e);const i=t.getNodeType(e);if(null!==s){const t=s.getNodeType(e);if(e.getTypeLength(t)>e.getTypeLength(i))return t}return i}setup(e){const t=this.condNode,s=this.ifNode.isolate(),i=this.elseNode?this.elseNode.isolate():null,r=e.context.nodeBlock;e.getDataFromNode(s).parentNodeBlock=r,null!==i&&(e.getDataFromNode(i).parentNodeBlock=r);const n=e.context.uniformFlow,o=e.getNodeProperties(this);o.condNode=t,o.ifNode=n?s:s.context({nodeBlock:s}),o.elseNode=i?n?i:i.context({nodeBlock:i}):null}generate(e,t){const s=this.getNodeType(e),i=e.getDataFromNode(this);if(void 0!==i.nodeProperty)return i.nodeProperty;const{condNode:r,ifNode:n,elseNode:o}=e.getNodeProperties(this),a=e.currentFunctionNode,l="void"!==t,h=l?sp(s).build(e):"";i.nodeProperty=h;const u=r.build(e,"bool");if(e.context.uniformFlow&&null!==o){const i=n.build(e,s),r=o.build(e,s),a=e.getTernary(u,i,r);return e.format(a,s,t)}e.addFlowCode(`\n${e.tab}if ( ${u} ) {\n\n`).addFlowTab();let c=n.build(e,s);if(c&&(l?c=h+" = "+c+";":(c="return "+c+";",null===a&&(Yo("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),c="// "+c))),e.removeFlowTab().addFlowCode(e.tab+"\t"+c+"\n\n"+e.tab+"}"),null!==o){e.addFlowCode(" else {\n\n").addFlowTab();let t=o.build(e,s);t&&(l?t=h+" = "+t+";":(t="return "+t+";",null===a&&(Yo("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),t="// "+t))),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(h,s,t)}}const kf=Td(zf).setParameterLength(2,3);$c("select",kf);class Uf extends Cc{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}getFlowContextData(){const e=[];return this.traverse(t=>{!0===t.isContextNode&&e.push(t.value)}),Object.assign({},...e)}getMemberType(e,t){return this.node.getMemberType(e,t)}analyze(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}setup(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}generate(e,t){const s=e.addContext(this.value),i=this.node.build(e,t);return e.setContext(s),i}}const Gf=(e=null,t={})=>{let s=e;return null!==s&&!0===s.isNode||(t=s||t,s=null),new Uf(s,t)},jf=e=>Gf(e,{uniformFlow:!0}),$f=(e,t)=>Gf(e,{nodeName:t});function Wf(e,t,s=null){return Gf(s,{getShadow:({light:s,shadowColorNode:i})=>t===s?i.mul(e):i})}function Hf(e,t=null){return Gf(t,{getAO:(t,{material:s})=>!0===s.transparent?t:null!==t?t.mul(e):e})}function qf(e,t){return Yo('TSL: "label()" has been deprecated. Use "setName()" instead.'),$f(e,t)}$c("context",Gf),$c("label",qf),$c("uniformFlow",jf),$c("setName",$f),$c("builtinShadowContext",(e,t,s)=>Wf(t,s,e)),$c("builtinAOContext",(e,t)=>Hf(t,e));class Xf extends Cc{static get type(){return"VarNode"}constructor(e,t=null,s=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=s,this.parents=!0,this.intent=!1}setIntent(e){return this.intent=e,this}isIntent(e){return!0!==e.getDataFromNode(this).forceDeclaration&&this.intent}getIntent(){return this.intent}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}isAssign(e){return e.getDataFromNode(this).assign}build(...e){const t=e[0];if(!1===this._hasStack(t)&&"setup"===t.buildStage&&(t.context.nodeLoop||t.context.nodeBlock)){let e=!1;if(this.node.isShaderCallNodeInternal&&null===this.node.shaderNode.getLayout()&&t.fnCall&&t.fnCall.shaderNode){if(t.getDataFromNode(this.node.shaderNode).hasLoop){t.getDataFromNode(this).forceDeclaration=!0,e=!0}}const s=t.getBaseStack();e?s.addToStackBefore(this):s.addToStack(this)}return this.isIntent(t)&&!0!==this.isAssign(t)?this.node.build(...e):super.build(...e)}generate(e){const{node:t,name:s,readOnly:i}=this,{renderer:r}=e,n=!0===r.backend.isWebGPUBackend;let o=!1,a=!1;i&&(o=e.isDeterministic(t),a=n?i:o);const l=this.getNodeType(e);if("void"==l){!0!==this.isIntent(e)&&Zo('TSL: ".toVar()" can not be used with void type.');return t.build(e)}const h=e.getVectorType(l),u=t.build(e,h),c=e.getVarFromNode(this,s,h,void 0,a),d=e.getPropertyName(c);let p=d;if(a)if(n)p=o?`const ${d}`:`let ${d}`;else{const s=t.getArrayCount(e);p=`const ${e.getVar(c.type,d,s)}`}return e.addLineFlowCode(`${p} = ${u}`,this),d}_hasStack(e){return void 0!==e.getDataFromNode(this).stack}}const Yf=Td(Xf),Zf=(e,t=null)=>Yf(e,t).toStack(),Qf=(e,t=null)=>Yf(e,t,!0).toStack(),Kf=e=>Yf(e).setIntent(!0).toStack();$c("toVar",Zf),$c("toConst",Qf),$c("toVarIntent",Kf);class Jf extends Cc{static get type(){return"SubBuild"}constructor(e,t,s=null){super(s),this.node=e,this.name=t,this.isSubBuildNode=!0}getNodeType(e){if(null!==this.nodeType)return this.nodeType;e.addSubBuild(this.name);const t=this.node.getNodeType(e);return e.removeSubBuild(),t}build(e,...t){e.addSubBuild(this.name);const s=this.node.build(e,...t);return e.removeSubBuild(),s}}const eg=(e,t,s=null)=>bd(new Jf(bd(e),t,s));class tg extends Cc{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let s=t.varying;if(void 0===s){const i=this.name,r=this.getNodeType(e),n=this.interpolationType,o=this.interpolationSampling;t.varying=s=e.getVaryingFromNode(this,i,r,n,o),t.node=eg(this.node,"VERTEX")}return s.needsInterpolation||(s.needsInterpolation="fragment"===e.shaderStage),s}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(_c.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(_c.VERTEX,this.node)}generate(e){const t=e.getSubBuildProperty("property",e.currentStack),s=e.getNodeProperties(this),i=this.setupVarying(e);if(void 0===s[t]){const r=this.getNodeType(e),n=e.getPropertyName(i,_c.VERTEX);e.flowNodeFromShaderStage(_c.VERTEX,s.node,r,n),s[t]=n}return e.getPropertyName(i)}}const sg=Td(tg).setParameterLength(1,2),ig=e=>sg(e);$c("toVarying",sg),$c("toVertexStage",ig),$c("varying",(...e)=>(Yo("TSL: .varying() has been renamed to .toVarying()."),sg(...e))),$c("vertexStage",(...e)=>(Yo("TSL: .vertexStage() has been renamed to .toVertexStage()."),sg(...e)));const rg=Ed(([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),s=e.mul(.0773993808),i=e.lessThanEqual(.04045);return Af(t,s,i)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),ng=Ed(([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),s=e.mul(12.92),i=e.lessThanEqual(.0031308);return Af(t,s,i)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),og="WorkingColorSpace";class ag extends Bc{static get type(){return"ColorSpaceNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this.source=t,this.target=s}resolveColorSpace(e,t){return t===og?_a.workingColorSpace:"OutputColorSpace"===t?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,s=this.resolveColorSpace(e,this.source),i=this.resolveColorSpace(e,this.target);let r=t;return!1!==_a.enabled&&s!==i&&s&&i?(_a.getTransfer(s)===Eo&&(r=Hd(rg(r.rgb),r.a)),_a.getPrimaries(s)!==_a.getPrimaries(i)&&(r=Hd(Qd(_a._getMatrix(new fa,s,i)).mul(r.rgb),r.a)),_a.getTransfer(i)===Eo&&(r=Hd(ng(r.rgb),r.a)),r):r}}const lg=(e,t)=>bd(new ag(bd(e),og,t)),hg=(e,t)=>bd(new ag(bd(e),t,og));$c("workingToColorSpace",lg),$c("colorSpaceToWorking",hg);let ug=class extends Rc{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),s=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,s,i)}};class cg extends Cc{static get type(){return"ReferenceBaseNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.updateType=wc.OBJECT}setGroup(e){return this.group=e,this}element(e){return new ug(this,bd(e))}setNodeType(e){const t=Up(null,e);null!==this.group&&t.setGroup(this.group),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let s=e[t[0]];for(let e=1;e<t.length;e++)s=s[t[e]];return s}updateReference(e){return this.reference=null!==this.object?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){null===this.node&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}class dg extends cg{static get type(){return"RendererReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.renderer=s,this.setGroup(Vp)}updateReference(e){return this.reference=null!==this.renderer?this.renderer:e.renderer,this.reference}}const pg=(e,t,s=null)=>new dg(e,t,s);class mg extends Bc{static get type(){return"ToneMappingNode"}constructor(e,t=gg,s=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=s}customCacheKey(){return ac(this._toneMapping)}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup(e){const t=this.colorNode||e.context.color,s=this._toneMapping;if(0===s)return t;let i=null;const r=e.renderer.library.getToneMappingFunction(s);return null!==r?i=Hd(r(t.rgb,this.exposureNode),t.a):(Zo("ToneMappingNode: Unsupported Tone Mapping configuration.",s),i=t),i}}const fg=(e,t,s)=>bd(new mg(e,bd(t),bd(s))),gg=pg("toneMappingExposure","float");$c("toneMapping",(e,t,s)=>fg(t,s,e));const yg=new WeakMap;function xg(e,t){let s=yg.get(e);return void 0===s&&(s=new eu(e,t),yg.set(e,s)),s}class bg extends Vc{static get type(){return"BufferAttributeNode"}constructor(e,t=null,s=0,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=s,this.bufferOffset=i,this.usage=Vo,this.instanced=!1,this.attribute=null,this.global=!0,e&&!0===e.isBufferAttribute&&e.itemSize<=4&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){if(0===this.bufferStride&&0===this.bufferOffset){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getNodeType(e){return null===this.bufferType&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(null!==this.attribute)return;const t=this.getNodeType(e),s=e.getTypeLength(t),i=this.value,r=this.bufferStride||s,n=this.bufferOffset;let o;o=!0===i.isInterleavedBuffer?i:!0===i.isBufferAttribute?xg(i.array,r):xg(i,r);const a=new su(o,s,n);o.setUsage(this.usage),this.attribute=a,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),s=e.getBufferAttributeFromNode(this,t),i=e.getPropertyName(s);let r=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=i,r=i;else{r=sg(this).build(e,t)}return r}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this.attribute&&!0===this.attribute.isBufferAttribute&&(this.attribute.usage=e),this}setInstanced(e){return this.instanced=e,this}}function _g(e,t=null,s=0,i=0,r=35044,n=!1){return"mat3"===t||null===t&&9===e.itemSize?Qd(new bg(e,"vec3",9,0).setUsage(r).setInstanced(n),new bg(e,"vec3",9,3).setUsage(r).setInstanced(n),new bg(e,"vec3",9,6).setUsage(r).setInstanced(n)):"mat4"===t||null===t&&16===e.itemSize?Kd(new bg(e,"vec4",16,0).setUsage(r).setInstanced(n),new bg(e,"vec4",16,4).setUsage(r).setInstanced(n),new bg(e,"vec4",16,8).setUsage(r).setInstanced(n),new bg(e,"vec4",16,12).setUsage(r).setInstanced(n)):new bg(e,t,s,i)}const wg=(e,t=null,s=0,i=0)=>_g(e,t,s,i),vg=(e,t=null,s=0,i=0)=>_g(e,t,s,i,Vo,!0),Tg=(e,t=null,s=0,i=0)=>_g(e,t,s,i,zo,!0);$c("toAttribute",e=>wg(e.value));class Sg extends Cc{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.version=1,this.name="",this.updateBeforeType=wc.OBJECT,this.onInitFunction=null}setCount(e){return this.count=e,this}getCount(){return this.count}dispose(){this.dispatchEvent({type:"dispose"})}setName(e){return this.name=e,this}label(e){return Yo('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){const t=this.computeNode.build(e);if(t){e.getNodeProperties(this).outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){const{shaderStage:s}=e;if("compute"===s){const t=this.computeNode.build(e,"void");""!==t&&e.addLineFlowCode(t,this)}else{const s=e.getNodeProperties(this).outputComputeNode;if(s)return s.build(e,t)}}}const Mg=(e,t=[64])=>{(0===t.length||t.length>3)&&Zo("TSL: compute() workgroupSize must have 1, 2, or 3 elements");for(let e=0;e<t.length;e++){const s=t[e];("number"!=typeof s||s<=0||!Number.isInteger(s))&&Zo(`TSL: compute() workgroupSize element at index [ ${e} ] must be a positive integer`)}for(;t.length<3;)t.push(1);return bd(new Sg(bd(e),t))},Ag=(e,t,s)=>Mg(e,s).setCount(t);$c("compute",Ag),$c("computeKernel",Mg);class Ng extends Cc{static get type(){return"IsolateNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isIsolateNode=!0}getNodeType(e){const t=e.getCache(),s=e.getCacheFromNode(this,this.parent);e.setCache(s);const i=this.node.getNodeType(e);return e.setCache(t),i}build(e,...t){const s=e.getCache(),i=e.getCacheFromNode(this,this.parent);e.setCache(i);const r=this.node.build(e,...t);return e.setCache(s),r}setParent(e){return this.parent=e,this}getParent(){return this.parent}}const Eg=e=>new Ng(bd(e));function Cg(e,t=!0){return Yo('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),Eg(e).setParent(t)}$c("cache",Cg),$c("isolate",Eg);class Rg extends Cc{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}getNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return""!==t&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}const Pg=Td(Rg).setParameterLength(2);$c("bypass",Pg);class Bg extends Cc{static get type(){return"RemapNode"}constructor(e,t,s,i=Dd(0),r=Dd(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=s,this.outLowNode=i,this.outHighNode=r,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:s,outLowNode:i,outHighNode:r,doClamp:n}=this;let o=e.sub(t).div(s.sub(t));return!0===n&&(o=o.clamp()),o.mul(r.sub(i)).add(i)}}const Ig=Td(Bg,null,null,{doClamp:!1}).setParameterLength(3,5),Dg=Td(Bg).setParameterLength(3,5);$c("remap",Ig),$c("remapClamp",Dg);class Lg extends Cc{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const s=this.getNodeType(e),i=this.snippet;if("void"!==s)return e.format(i,s,t);e.addLineFlowCode(i,this)}}const Fg=Td(Lg).setParameterLength(1,2),Og=e=>(e?kf(e,Fg("discard")):Fg("discard")).toStack();$c("discard",Og);class Vg extends Bc{static get type(){return"RenderOutputNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this._toneMapping=t,this.outputColorSpace=s,this.isRenderOutputNode=!0}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup({context:e}){let t=this.colorNode||e.color;const s=(null!==this._toneMapping?this._toneMapping:e.toneMapping)||0,i=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||So;return 0!==s&&(t=t.toneMapping(s)),i!==So&&i!==_a.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}const zg=(e,t=null,s=null)=>bd(new Vg(bd(e),t,s));$c("renderOutput",zg);class kg extends Bc{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}getNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,s=this.node.build(e),i="--- TSL debug - "+e.shaderStage+" shader ---",r="-".repeat(i.length);let n="";return n+="// #"+i+"#\n",n+=e.flow.code.replace(/^\t/gm,"")+"\n",n+="/* ... */ "+s+" /* ... */\n",n+="// #"+r+"#\n",null!==t?t(e,n):Xo(n),s}}const Ug=(e,t=null)=>bd(new kg(bd(e),t)).toStack();$c("debug",Ug);class Gg{constructor(){this._renderer=null,this.currentFrame=null}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}init(){}begin(){}finish(){}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}}class jg extends Cc{static get type(){return"InspectorNode"}constructor(e,t="",s=null){super(),this.node=e,this.name=t,this.callback=s,this.updateType=wc.FRAME,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(e){e.renderer.inspector.inspect(this)}getNodeType(e){return this.node.getNodeType(e)}setup(e){let t=this.node;return!0===e.context.inspector&&null!==this.callback&&(t=this.callback(t)),!0!==e.renderer.backend.isWebGPUBackend&&e.renderer.inspector.constructor!==Gg&&Qo('TSL: ".toInspector()" is only available with WebGPU.'),t}}function $g(e,t="",s=null){return(e=bd(e)).before(new jg(e,t,s))}$c("toInspector",$g);class Wg extends Cc{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}getNodeType(e){let t=this.nodeType;if(null===t){const s=this.getAttributeName(e);if(e.hasGeometryAttribute(s)){const i=e.geometry.getAttribute(s);t=e.getTypeFromAttribute(i)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),s=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const i=e.geometry.getAttribute(t),r=e.getTypeFromAttribute(i),n=e.getAttribute(t,r);if("vertex"===e.shaderStage)return e.format(n.name,r,s);return sg(this).build(e,s)}return Yo(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(s)}serialize(e){super.serialize(e),e.global=this.global,e._attributeName=this._attributeName}deserialize(e){super.deserialize(e),this.global=e.global,this._attributeName=e._attributeName}}const Hg=(e,t=null)=>new Wg(e,t),qg=(e=0)=>Hg("uv"+(e>0?e:""),"vec2");class Xg extends Cc{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const s=this.textureNode.build(e,"property"),i=null===this.levelNode?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${s}, ${i} )`,this.getNodeType(e),t)}}const Yg=Td(Xg).setParameterLength(1,2);class Zg extends kp{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=wc.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,s=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(s&&void 0!==s.width){const{width:e,height:t}=s;this.value=Math.log2(Math.max(e,t))}}}const Qg=Td(Zg).setParameterLength(1),Kg=new Ra;class Jg extends kp{static get type(){return"TextureNode"}constructor(e=Kg,t=null,s=null,i=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=s,this.biasNode=i,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=wc.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}getNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===An?"uvec4":this.value.type===Mn?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return qg(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=Up(this.value.matrix)),this._matrixUniform.mul(Gd(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(null===this._flipYUniform&&(this._flipYUniform=Up(!1)),t=t.toVar(),t=this.sampler?this._flipYUniform.select(t.flipY(),t):this._flipYUniform.select(t.setY(Ld(Yg(this,this.levelNode).y).sub(t.y).sub(1)),t)),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const s=this.value;if(!s||!0!==s.isTexture)throw new Error("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().");const i=Ed(()=>{let t=this.uvNode;return null!==t&&!0!==e.context.forceUVContext||!e.context.getUV||(t=e.context.getUV(this,e)),t||(t=this.getDefaultUV()),!0===this.updateMatrix&&(t=this.getTransformedUV(t)),t=this.setupUV(e,t),this.updateType=null!==this._matrixUniform||null!==this._flipYUniform?wc.OBJECT:wc.NONE,t})();let r=this.levelNode;null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this)),t.uvNode=i,t.levelNode=r,t.biasNode=this.biasNode,t.compareNode=this.compareNode,t.gradNode=this.gradNode,t.depthNode=this.depthNode,t.offsetNode=this.offsetNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateOffset(e,t){return t.build(e,"ivec2")}generateSnippet(e,t,s,i,r,n,o,a,l){const h=this.value;let u;return u=r?e.generateTextureBias(h,t,s,r,n,l):a?e.generateTextureGrad(h,t,s,a,n,l):o?e.generateTextureCompare(h,t,s,o,n,l):!1===this.sampler?e.generateTextureLoad(h,t,s,i,n,l):i?e.generateTextureLevel(h,t,s,i,n,l):e.generateTexture(h,t,s,n,l),u}generate(e,t){const s=this.value,i=e.getNodeProperties(this),r=super.generate(e,"property");if(/^sampler/.test(t))return r+"_sampler";if(e.isReference(t))return r;{const n=e.getDataFromNode(this);let o=n.propertyName;if(void 0===o){const{uvNode:t,levelNode:s,biasNode:a,compareNode:l,depthNode:h,gradNode:u,offsetNode:c}=i,d=this.generateUV(e,t),p=s?s.build(e,"float"):null,m=a?a.build(e,"float"):null,f=h?h.build(e,"int"):null,g=l?l.build(e,"float"):null,y=u?[u[0].build(e,"vec2"),u[1].build(e,"vec2")]:null,x=c?this.generateOffset(e,c):null,b=e.getVarFromNode(this);o=e.getPropertyName(b);const _=this.generateSnippet(e,r,d,p,m,f,g,y,x);e.addLineFlowCode(`${o} = ${_}`,this),n.snippet=_,n.propertyName=o}let a=o;const l=this.getNodeType(e);return e.needsToWorkingColorSpace(s)&&(a=hg(Fg(a,l),s.colorSpace).setup(e).build(e,l)),e.format(a,l,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){return Yo("TextureNode: .uv() has been renamed. Use .sample() instead."),this.sample(e)}sample(e){const t=this.clone();return t.uvNode=bd(e),t.referenceNode=this.getBase(),bd(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=bd(e).mul(Qg(t)),t.referenceNode=this.getBase();const s=t.value;return!1===t.generateMipmaps&&(s&&!1===s.generateMipmaps||s.minFilter===fn||s.magFilter===fn)&&(Yo("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),bd(t)}level(e){const t=this.clone();return t.levelNode=bd(e),t.referenceNode=this.getBase(),bd(t)}size(e){return Yg(this,e)}bias(e){const t=this.clone();return t.biasNode=bd(e),t.referenceNode=this.getBase(),bd(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=bd(e),t.referenceNode=this.getBase(),bd(t)}grad(e,t){const s=this.clone();return s.gradNode=[bd(e),bd(t)],s.referenceNode=this.getBase(),bd(s)}depth(e){const t=this.clone();return t.depthNode=bd(e),t.referenceNode=this.getBase(),bd(t)}offset(e){const t=this.clone();return t.offsetNode=bd(e),t.referenceNode=this.getBase(),bd(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;null!==t&&(t.value=e.matrix),!0===e.matrixAutoUpdate&&e.updateMatrix();const s=this._flipYUniform;null!==s&&(s.value=e.image instanceof ImageBitmap&&!0===e.flipY||!0===e.isRenderTargetTexture||!0===e.isFramebufferTexture||!0===e.isDepthTexture)}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}const ey=Td(Jg).setParameterLength(1,4).setName("texture"),ty=(e=Kg,t=null,s=null,i=null)=>{let r;return e&&!0===e.isTextureNode?(r=bd(e.clone()),r.referenceNode=e.getBase(),null!==t&&(r.uvNode=bd(t)),null!==s&&(r.levelNode=bd(s)),null!==i&&(r.biasNode=bd(i))):r=ey(e,t,s,i),r},sy=(...e)=>ty(...e).setSampler(!1);class iy extends kp{static get type(){return"BufferNode"}constructor(e,t,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=s,this.updateRanges=[]}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const ry=(e,t,s)=>new iy(e,t,s);class ny extends Rc{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),s=this.getNodeType(),i=this.node.getPaddedType();return e.format(t,i,s)}}class oy extends iy{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?fc(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=wc.RENDER,this.isArrayBufferNode=!0}getNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){const{array:e,value:t}=this,s=this.elementType;if("float"===s||"int"===s||"uint"===s)for(let s=0;s<e.length;s++){t[4*s]=e[s]}else if("color"===s)for(let s=0;s<e.length;s++){const i=4*s,r=e[s];t[i]=r.r,t[i+1]=r.g,t[i+2]=r.b||0}else if("mat2"===s)for(let s=0;s<e.length;s++){const i=4*s,r=e[s];t[i]=r.elements[0],t[i+1]=r.elements[1],t[i+2]=r.elements[2],t[i+3]=r.elements[3]}else if("mat3"===s)for(let s=0;s<e.length;s++){const i=16*s,r=e[s];t[i]=r.elements[0],t[i+1]=r.elements[1],t[i+2]=r.elements[2],t[i+4]=r.elements[3],t[i+5]=r.elements[4],t[i+6]=r.elements[5],t[i+8]=r.elements[6],t[i+9]=r.elements[7],t[i+10]=r.elements[8],t[i+15]=1}else if("mat4"===s)for(let s=0;s<e.length;s++){const i=16*s,r=e[s];for(let e=0;e<r.elements.length;e++)t[i+e]=r.elements[e]}else for(let s=0;s<e.length;s++){const i=4*s,r=e[s];t[i]=r.x,t[i+1]=r.y,t[i+2]=r.z||0,t[i+3]=r.w||0}}setup(e){const t=this.array.length,s=this.elementType;let i=Float32Array;const r=this.paddedType,n=e.getTypeLength(r);return"i"===s.charAt(0)&&(i=Int32Array),"u"===s.charAt(0)&&(i=Uint32Array),this.value=new i(t*n),this.bufferCount=t,this.bufferType=r,super.setup(e)}element(e){return new ny(this,bd(e))}}const ay=(e,t)=>new oy(e,t);const ly=Td(class extends Cc{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}).setParameterLength(1);let hy,uy;class cy extends Cc{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this._output=null,this.isViewportNode=!0}getNodeType(){return this.scope===cy.DPR?"float":this.scope===cy.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=wc.NONE;return this.scope!==cy.SIZE&&this.scope!==cy.VIEWPORT&&this.scope!==cy.DPR||(e=wc.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===cy.VIEWPORT?null!==t?uy.copy(t.viewport):(e.getViewport(uy),uy.multiplyScalar(e.getPixelRatio())):this.scope===cy.DPR?this._output.value=e.getPixelRatio():null!==t?(hy.width=t.width,hy.height=t.height):e.getDrawingBufferSize(hy)}setup(){const e=this.scope;let t=null;return t=e===cy.SIZE?Up(hy||(hy=new ua)):e===cy.VIEWPORT?Up(uy||(uy=new Pa)):e===cy.DPR?Up(1):Vd(fy.div(my)),this._output=t,t}generate(e){if(this.scope===cy.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const s=e.getNodeProperties(my).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${s}.y - ${t}.y )`}return t}return super.generate(e)}}cy.COORDINATE="coordinate",cy.VIEWPORT="viewport",cy.SIZE="size",cy.UV="uv",cy.DPR="dpr";const dy=Sd(cy,cy.DPR),py=Sd(cy,cy.UV),my=Sd(cy,cy.SIZE),fy=Sd(cy,cy.COORDINATE),gy=Sd(cy,cy.VIEWPORT),yy=gy.zw,xy=fy.sub(gy.xy),by=xy.div(yy),_y=Ed(()=>(Yo('TSL: "viewportResolution" is deprecated. Use "screenSize" instead.'),my),"vec2").once()(),wy=Up(0,"uint").setName("u_cameraIndex").setGroup(Fp("cameraIndex")).toVarying("v_cameraIndex"),vy=Up("float").setName("cameraNear").setGroup(Vp).onRenderUpdate(({camera:e})=>e.near),Ty=Up("float").setName("cameraFar").setGroup(Vp).onRenderUpdate(({camera:e})=>e.far),Sy=Ed(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.projectionMatrix);t=ay(s).setGroup(Vp).setName("cameraProjectionMatrices").element(e.isMultiViewCamera?ly("gl_ViewID_OVR"):wy).toConst("cameraProjectionMatrix")}else t=Up("mat4").setName("cameraProjectionMatrix").setGroup(Vp).onRenderUpdate(({camera:e})=>e.projectionMatrix);return t}).once()(),My=Ed(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.projectionMatrixInverse);t=ay(s).setGroup(Vp).setName("cameraProjectionMatricesInverse").element(e.isMultiViewCamera?ly("gl_ViewID_OVR"):wy).toConst("cameraProjectionMatrixInverse")}else t=Up("mat4").setName("cameraProjectionMatrixInverse").setGroup(Vp).onRenderUpdate(({camera:e})=>e.projectionMatrixInverse);return t}).once()(),Ay=Ed(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.matrixWorldInverse);t=ay(s).setGroup(Vp).setName("cameraViewMatrices").element(e.isMultiViewCamera?ly("gl_ViewID_OVR"):wy).toConst("cameraViewMatrix")}else t=Up("mat4").setName("cameraViewMatrix").setGroup(Vp).onRenderUpdate(({camera:e})=>e.matrixWorldInverse);return t}).once()(),Ny=Ed(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.matrixWorld);t=ay(s).setGroup(Vp).setName("cameraWorldMatrices").element(e.isMultiViewCamera?ly("gl_ViewID_OVR"):wy).toConst("cameraWorldMatrix")}else t=Up("mat4").setName("cameraWorldMatrix").setGroup(Vp).onRenderUpdate(({camera:e})=>e.matrixWorld);return t}).once()(),Ey=Ed(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.normalMatrix);t=ay(s).setGroup(Vp).setName("cameraNormalMatrices").element(e.isMultiViewCamera?ly("gl_ViewID_OVR"):wy).toConst("cameraNormalMatrix")}else t=Up("mat3").setName("cameraNormalMatrix").setGroup(Vp).onRenderUpdate(({camera:e})=>e.normalMatrix);return t}).once()(),Cy=Ed(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(let t=0,i=e.cameras.length;t<i;t++)s.push(new da);t=ay(s).setGroup(Vp).setName("cameraPositions").onRenderUpdate(({camera:e},t)=>{const s=e.cameras,i=t.array;for(let e=0,t=s.length;e<t;e++)i[e].setFromMatrixPosition(s[e].matrixWorld)}).element(e.isMultiViewCamera?ly("gl_ViewID_OVR"):wy).toConst("cameraPosition")}else t=Up(new da).setName("cameraPosition").setGroup(Vp).onRenderUpdate(({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld));return t}).once()(),Ry=Ed(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.viewport);t=ay(s,"vec4").setGroup(Vp).setName("cameraViewports").element(wy).toConst("cameraViewport")}else t=Hd(0,0,my.x,my.y).toConst("cameraViewport");return t}).once()(),Py=new Ja;class By extends Cc{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=wc.OBJECT,this.uniformNode=new kp(null)}getNodeType(){const e=this.scope;return e===By.WORLD_MATRIX?"mat4":e===By.POSITION||e===By.VIEW_POSITION||e===By.DIRECTION||e===By.SCALE?"vec3":e===By.RADIUS?"float":void 0}update(e){const t=this.object3d,s=this.uniformNode,i=this.scope;if(i===By.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===By.POSITION)s.value=s.value||new da,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===By.SCALE)s.value=s.value||new da,s.value.setFromMatrixScale(t.matrixWorld);else if(i===By.DIRECTION)s.value=s.value||new da,t.getWorldDirection(s.value);else if(i===By.VIEW_POSITION){const i=e.camera;s.value=s.value||new da,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(i.matrixWorldInverse)}else if(i===By.RADIUS){const i=e.object.geometry;null===i.boundingSphere&&i.computeBoundingSphere(),Py.copy(i.boundingSphere).applyMatrix4(t.matrixWorld),s.value=Py.radius}}generate(e){const t=this.scope;return t===By.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===By.POSITION||t===By.VIEW_POSITION||t===By.DIRECTION||t===By.SCALE?this.uniformNode.nodeType="vec3":t===By.RADIUS&&(this.uniformNode.nodeType="float"),this.uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}By.WORLD_MATRIX="worldMatrix",By.POSITION="position",By.SCALE="scale",By.VIEW_POSITION="viewPosition",By.DIRECTION="direction",By.RADIUS="radius";const Iy=Td(By,By.DIRECTION).setParameterLength(1),Dy=Td(By,By.WORLD_MATRIX).setParameterLength(1),Ly=Td(By,By.POSITION).setParameterLength(1),Fy=Td(By,By.SCALE).setParameterLength(1),Oy=Td(By,By.VIEW_POSITION).setParameterLength(1),Vy=Td(By,By.RADIUS).setParameterLength(1);class zy extends By{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const ky=Sd(zy,zy.DIRECTION),Uy=Sd(zy,zy.WORLD_MATRIX),Gy=Sd(zy,zy.POSITION),jy=Sd(zy,zy.SCALE),$y=Sd(zy,zy.VIEW_POSITION),Wy=Sd(zy,zy.RADIUS),Hy=Up(new fa).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),qy=Up(new ll).onObjectUpdate(({object:e},t)=>t.value.copy(e.matrixWorld).invert()),Xy=Ed(e=>e.context.modelViewMatrix||Yy).once()().toVar("modelViewMatrix"),Yy=Ay.mul(Uy),Zy=Ed(e=>(e.context.isHighPrecisionModelViewMatrix=!0,Up("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),Qy=Ed(e=>{const t=e.context.isHighPrecisionModelViewMatrix;return Up("mat3").onObjectUpdate(({object:e,camera:s})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),Ky=Hg("position","vec3"),Jy=Ky.toVarying("positionLocal"),ex=Ky.toVarying("positionPrevious"),tx=Ed(e=>Uy.mul(Jy).xyz.toVarying(e.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),sx=Ed(()=>Jy.transformDirection(Uy).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),ix=Ed(e=>e.context.setupPositionView().toVarying("v_positionView"),"vec3").once(["POSITION"])(),rx=Ed(e=>{let t;return t=e.camera.isOrthographicCamera?Gd(0,0,1):ix.negate().toVarying("v_positionViewDirection").normalize(),t.toVar("positionViewDirection")},"vec3").once(["POSITION"])();class nx extends Cc{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if("fragment"!==e.shaderStage)return"true";const{material:t}=e;return 1===t.side?"false":e.getFrontFacing()}}const ox=Sd(nx),ax=Dd(ox).mul(2).sub(1),lx=Ed(([e],{material:t})=>{const s=t.side;return 1===s?e=e.mul(-1):2===s&&(e=e.mul(ax)),e}),hx=Hg("normal","vec3"),ux=Ed(e=>!1===e.geometry.hasAttribute("normal")?(Yo('TSL: Vertex attribute "normal" not found on geometry.'),Gd(0,1,0)):hx,"vec3").once()().toVar("normalLocal"),cx=ix.dFdx().cross(ix.dFdy()).normalize().toVar("normalFlat"),dx=Ed(e=>{let t;return t=!0===e.material.flatShading?cx:xx(ux).toVarying("v_normalViewGeometry").normalize(),t},"vec3").once()().toVar("normalViewGeometry"),px=Ed(e=>{let t=dx.transformDirection(Ay);return!0!==e.material.flatShading&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")},"vec3").once()(),mx=Ed(({subBuildFn:e,material:t,context:s})=>{let i;return"NORMAL"===e||"VERTEX"===e?(i=dx,!0!==t.flatShading&&(i=lx(i))):i=s.setupNormal().context({getUV:null}),i},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),fx=mx.transformDirection(Ay).toVar("normalWorld"),gx=Ed(({subBuildFn:e,context:t})=>{let s;return s="NORMAL"===e||"VERTEX"===e?mx:t.setupClearcoatNormal().context({getUV:null}),s},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),yx=Ed(([e,t=Uy])=>{const s=Qd(t),i=e.div(Gd(s[0].dot(s[0]),s[1].dot(s[1]),s[2].dot(s[2])));return s.mul(i).xyz}),xx=Ed(([e],t)=>{const s=t.context.modelNormalViewMatrix;if(s)return s.transformDirection(e);const i=Hy.mul(e);return Ay.transformDirection(i)}),bx=Ed(()=>(Yo('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),mx)).once(["NORMAL","VERTEX"])(),_x=Ed(()=>(Yo('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),fx)).once(["NORMAL","VERTEX"])(),wx=Ed(()=>(Yo('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),gx)).once(["NORMAL","VERTEX"])(),vx=new xl,Tx=new ll,Sx=Up(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),Mx=Up(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),Ax=Up(new ll).onReference(function(e){return e.material}).onObjectUpdate(function({material:e,scene:t}){const s=null!==t.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation;return s?(vx.copy(s),Tx.makeRotationFromEuler(vx)):Tx.identity(),Tx}),Nx=rx.negate().reflect(mx),Ex=rx.negate().refract(mx,Sx),Cx=Nx.transformDirection(Ay).toVar("reflectVector"),Rx=Ex.transformDirection(Ay).toVar("reflectVector"),Px=new Xh;class Bx extends Jg{static get type(){return"CubeTextureNode"}constructor(e,t=null,s=null,i=null){super(e,t,s,i),this.isCubeTextureNode=!0}getInputType(){return!0===this.value.isDepthTexture?"cubeDepthTexture":"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===un?Cx:e.mapping===cn?Rx:(Zo('CubeTextureNode: Mapping "%s" not supported.',e.mapping),Gd(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return!0===s.isDepthTexture?e.renderer.coordinateSystem===Uo?Gd(t.x,t.y.negate(),t.z):t:(e.renderer.coordinateSystem!==Uo&&s.isRenderTargetTexture||(t=Gd(t.x.negate(),t.yz)),Ax.mul(t))}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}}const Ix=Td(Bx).setParameterLength(1,4).setName("cubeTexture"),Dx=(e=Px,t=null,s=null,i=null)=>{let r;return e&&!0===e.isCubeTextureNode?(r=bd(e.clone()),r.referenceNode=e,null!==t&&(r.uvNode=bd(t)),null!==s&&(r.levelNode=bd(s)),null!==i&&(r.biasNode=bd(i))):r=Ix(e,t,s,i),r};class Lx extends Rc{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),s=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,s,i)}}class Fx extends Cc{static get type(){return"ReferenceNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.name=null,this.updateType=wc.OBJECT}element(e){return new Lx(this,bd(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return Yo('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;t=null!==this.count?ry(null,e,this.count):Array.isArray(this.getValueFromReference())?ay(null,e):"texture"===e?ty(null):"cubeTexture"===e?Dx(null):Up(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.setName(this.name),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let s=e[t[0]];for(let e=1;e<t.length;e++)s=s[t[e]];return s}updateReference(e){return this.reference=null!==this.object?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){null===this.node&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}const Ox=(e,t,s)=>new Fx(e,t,s),Vx=(e,t,s,i)=>new Fx(e,t,i,s);class zx extends Fx{static get type(){return"MaterialReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.material=s,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const kx=(e,t,s=null)=>new zx(e,t,s),Ux=qg(),Gx=ix.dFdx(),jx=ix.dFdy(),$x=Ux.dFdx(),Wx=Ux.dFdy(),Hx=mx,qx=jx.cross(Hx),Xx=Hx.cross(Gx),Yx=qx.mul($x.x).add(Xx.mul(Wx.x)),Zx=qx.mul($x.y).add(Xx.mul(Wx.y)),Qx=Yx.dot(Yx).max(Zx.dot(Zx)),Kx=Qx.equal(0).select(0,Qx.inverseSqrt()),Jx=Yx.mul(Kx).toVar("tangentViewFrame"),eb=Zx.mul(Kx).toVar("bitangentViewFrame"),tb=Hg("tangent","vec4"),sb=tb.xyz.toVar("tangentLocal"),ib=Ed(({subBuildFn:e,geometry:t,material:s})=>{let i;return i="VERTEX"===e||t.hasAttribute("tangent")?Xy.mul(Hd(sb,0)).xyz.toVarying("v_tangentView").normalize():Jx,!0!==s.flatShading&&(i=lx(i)),i},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),rb=ib.transformDirection(Ay).toVarying("v_tangentWorld").normalize().toVar("tangentWorld"),nb=Ed(([e,t],{subBuildFn:s,material:i})=>{let r=e.mul(tb.w).xyz;return"NORMAL"===s&&!0!==i.flatShading&&(r=r.toVarying(t)),r}).once(["NORMAL"]),ob=nb(hx.cross(tb),"v_bitangentGeometry").normalize().toVar("bitangentGeometry"),ab=nb(ux.cross(sb),"v_bitangentLocal").normalize().toVar("bitangentLocal"),lb=Ed(({subBuildFn:e,geometry:t,material:s})=>{let i;return i="VERTEX"===e||t.hasAttribute("tangent")?nb(mx.cross(ib),"v_bitangentView").normalize():eb,!0!==s.flatShading&&(i=lx(i)),i},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),hb=nb(fx.cross(rb),"v_bitangentWorld").normalize().toVar("bitangentWorld"),ub=Qd(ib,lb,mx).toVar("TBNViewMatrix"),cb=rx.mul(ub),db=Ed(()=>{let e=bp.cross(rx);return e=e.cross(bp).normalize(),e=Af(e,mx,yp.mul(ap.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()(),pb=e=>bd(e).mul(.5).add(.5),mb=e=>Gd(e,Om(Ef(Dd(1).sub(yf(e,e)))));class fb extends Bc{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0,this.unpackNormalMode=""}setup({material:e}){const{normalMapType:t,scaleNode:s,unpackNormalMode:i}=this;let r=this.node.mul(2).sub(1);if(0===t?"rg"===i?r=mb(r.xy):"ga"===i?r=mb(r.yw):""!==i&&console.error(`THREE.NodeMaterial: Unexpected unpack normal mode: ${i}`):""!==i&&console.error(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${i}'`),null!==s){let t=s;!0===e.flatShading&&(t=lx(t)),r=Gd(r.xy.mul(t),r.z)}let n=null;return 1===t?n=xx(r):0===t?n=ub.mul(r).normalize():(Zo(`NodeMaterial: Unsupported normal map type: ${t}`),n=mx),n}}const gb=Td(fb).setParameterLength(1,2),yb=Ed(({textureNode:e,bumpScale:t})=>{const s=t=>e.isolate().context({getUV:e=>t(e.uvNode||qg()),forceUVContext:!0}),i=Dd(s(e=>e));return Vd(Dd(s(e=>e.add(e.dFdx()))).sub(i),Dd(s(e=>e.add(e.dFdy()))).sub(i)).mul(t)}),xb=Ed(e=>{const{surf_pos:t,surf_norm:s,dHdxy:i}=e,r=t.dFdx().normalize(),n=s,o=t.dFdy().normalize().cross(n),a=n.cross(r),l=r.dot(o).mul(ax),h=l.sign().mul(i.x.mul(o).add(i.y.mul(a)));return l.abs().mul(s).sub(h).normalize()});class bb extends Bc{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=null!==this.scaleNode?this.scaleNode:1,t=yb({textureNode:this.textureNode,bumpScale:e});return xb({surf_pos:ix,surf_norm:mx,dHdxy:t})}}const _b=Td(bb).setParameterLength(1,2),wb=new Map;class vb extends Cc{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let s=wb.get(e);return void 0===s&&(s=kx(e,t),wb.set(e,s)),s}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache("map"===e?"map":e+"Map","texture")}setup(e){const t=e.context.material,s=this.scope;let i=null;if(s===vb.COLOR){const e=void 0!==t.color?this.getColor(s):Gd();i=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(s===vb.OPACITY){const e=this.getFloat(s);i=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(s===vb.SPECULAR_STRENGTH)i=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:Dd(1);else if(s===vb.SPECULAR_INTENSITY){const e=this.getFloat(s);i=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(s).a):e}else if(s===vb.SPECULAR_COLOR){const e=this.getColor(s);i=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(s).rgb):e}else if(s===vb.ROUGHNESS){const e=this.getFloat(s);i=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(s).g):e}else if(s===vb.METALNESS){const e=this.getFloat(s);i=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(s).b):e}else if(s===vb.EMISSIVE){const e=this.getFloat("emissiveIntensity"),r=this.getColor(s).mul(e);i=t.emissiveMap&&!0===t.emissiveMap.isTexture?r.mul(this.getTexture(s)):r}else if(s===vb.NORMAL)t.normalMap?(i=gb(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType,t.normalMap.format!=kn&&t.normalMap.format!=vo&&t.normalMap.format!=so||(i.unpackNormalMode="rg")):i=t.bumpMap?_b(this.getTexture("bump").r,this.getFloat("bumpScale")):mx;else if(s===vb.CLEARCOAT){const e=this.getFloat(s);i=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===vb.CLEARCOAT_ROUGHNESS){const e=this.getFloat(s);i=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===vb.CLEARCOAT_NORMAL)i=t.clearcoatNormalMap?gb(this.getTexture(s),this.getCache(s+"Scale","vec2")):mx;else if(s===vb.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));i=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(s===vb.SHEEN_ROUGHNESS){const e=this.getFloat(s);i=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(s).a):e,i=i.clamp(1e-4,1)}else if(s===vb.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(s);i=Zd(o_.x,o_.y,o_.y.negate(),o_.x).mul(e.rg.mul(2).sub(Vd(1)).normalize().mul(e.b))}else i=o_;else if(s===vb.IRIDESCENCE_THICKNESS){const e=Ox("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=Ox("0","float",t.iridescenceThicknessRange);i=e.sub(r).mul(this.getTexture(s).g).add(r)}else i=e}else if(s===vb.TRANSMISSION){const e=this.getFloat(s);i=t.transmissionMap?e.mul(this.getTexture(s).r):e}else if(s===vb.THICKNESS){const e=this.getFloat(s);i=t.thicknessMap?e.mul(this.getTexture(s).g):e}else if(s===vb.IOR)i=this.getFloat(s);else if(s===vb.LIGHT_MAP)i=this.getTexture(s).rgb.mul(this.getFloat("lightMapIntensity"));else if(s===vb.AO)i=this.getTexture(s).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(s===vb.LINE_DASH_OFFSET)i=t.dashOffset?this.getFloat(s):Dd(0);else{const t=this.getNodeType(e);i=this.getCache(s,t)}return i}}vb.ALPHA_TEST="alphaTest",vb.COLOR="color",vb.OPACITY="opacity",vb.SHININESS="shininess",vb.SPECULAR="specular",vb.SPECULAR_STRENGTH="specularStrength",vb.SPECULAR_INTENSITY="specularIntensity",vb.SPECULAR_COLOR="specularColor",vb.REFLECTIVITY="reflectivity",vb.ROUGHNESS="roughness",vb.METALNESS="metalness",vb.NORMAL="normal",vb.CLEARCOAT="clearcoat",vb.CLEARCOAT_ROUGHNESS="clearcoatRoughness",vb.CLEARCOAT_NORMAL="clearcoatNormal",vb.EMISSIVE="emissive",vb.ROTATION="rotation",vb.SHEEN="sheen",vb.SHEEN_ROUGHNESS="sheenRoughness",vb.ANISOTROPY="anisotropy",vb.IRIDESCENCE="iridescence",vb.IRIDESCENCE_IOR="iridescenceIOR",vb.IRIDESCENCE_THICKNESS="iridescenceThickness",vb.IOR="ior",vb.TRANSMISSION="transmission",vb.THICKNESS="thickness",vb.ATTENUATION_DISTANCE="attenuationDistance",vb.ATTENUATION_COLOR="attenuationColor",vb.LINE_SCALE="scale",vb.LINE_DASH_SIZE="dashSize",vb.LINE_GAP_SIZE="gapSize",vb.LINE_WIDTH="linewidth",vb.LINE_DASH_OFFSET="dashOffset",vb.POINT_SIZE="size",vb.DISPERSION="dispersion",vb.LIGHT_MAP="light",vb.AO="ao";const Tb=Sd(vb,vb.ALPHA_TEST),Sb=Sd(vb,vb.COLOR),Mb=Sd(vb,vb.SHININESS),Ab=Sd(vb,vb.EMISSIVE),Nb=Sd(vb,vb.OPACITY),Eb=Sd(vb,vb.SPECULAR),Cb=Sd(vb,vb.SPECULAR_INTENSITY),Rb=Sd(vb,vb.SPECULAR_COLOR),Pb=Sd(vb,vb.SPECULAR_STRENGTH),Bb=Sd(vb,vb.REFLECTIVITY),Ib=Sd(vb,vb.ROUGHNESS),Db=Sd(vb,vb.METALNESS),Lb=Sd(vb,vb.NORMAL),Fb=Sd(vb,vb.CLEARCOAT),Ob=Sd(vb,vb.CLEARCOAT_ROUGHNESS),Vb=Sd(vb,vb.CLEARCOAT_NORMAL),zb=Sd(vb,vb.ROTATION),kb=Sd(vb,vb.SHEEN),Ub=Sd(vb,vb.SHEEN_ROUGHNESS),Gb=Sd(vb,vb.ANISOTROPY),jb=Sd(vb,vb.IRIDESCENCE),$b=Sd(vb,vb.IRIDESCENCE_IOR),Wb=Sd(vb,vb.IRIDESCENCE_THICKNESS),Hb=Sd(vb,vb.TRANSMISSION),qb=Sd(vb,vb.THICKNESS),Xb=Sd(vb,vb.IOR),Yb=Sd(vb,vb.ATTENUATION_DISTANCE),Zb=Sd(vb,vb.ATTENUATION_COLOR),Qb=Sd(vb,vb.LINE_SCALE),Kb=Sd(vb,vb.LINE_DASH_SIZE),Jb=Sd(vb,vb.LINE_GAP_SIZE),e_=Sd(vb,vb.LINE_WIDTH),t_=Sd(vb,vb.LINE_DASH_OFFSET),s_=Sd(vb,vb.POINT_SIZE),i_=Sd(vb,vb.DISPERSION),r_=Sd(vb,vb.LIGHT_MAP),n_=Sd(vb,vb.AO),o_=Up(new ua).onReference(function(e){return e.material}).onRenderUpdate(function({material:e}){this.value.set(e.anisotropy*Math.cos(e.anisotropyRotation),e.anisotropy*Math.sin(e.anisotropyRotation))}),a_=Ed(e=>e.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class l_ extends Rc{static get type(){return"StorageArrayElementNode"}constructor(e,t){super(e,t),this.isStorageArrayElementNode=!0}set storageBufferNode(e){this.node=e}get storageBufferNode(){return this.node}getMemberType(e,t){const s=this.storageBufferNode.structTypeNode;return s?s.getMemberType(e,t):"void"}setup(e){return!1===e.isAvailable("storageBuffer")&&!0===this.node.isPBO&&e.setupPBO(this.node),super.setup(e)}generate(e,t){let s;const i=e.context.assign;if(s=!1===e.isAvailable("storageBuffer")?!0!==this.node.isPBO||!0===i||!this.node.value.isInstancedBufferAttribute&&"compute"===e.shaderStage?this.node.build(e):e.generatePBO(this):super.generate(e),!0!==i){const i=this.getNodeType(e);s=e.format(s,i,t)}return s}}const h_=Td(l_).setParameterLength(2);class u_ extends iy{static get type(){return"StorageBufferNode"}constructor(e,t=null,s=0){let i,r=null;t&&t.isStruct?(i="struct",r=t.layout,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(s=e.count)):null===t&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(i=uc(e.itemSize),s=e.count):i=t,super(e,i,s),this.isStorageBufferNode=!0,this.structTypeNode=r,this.access=vc.READ_WRITE,this.isAtomic=!1,this.isPBO=!1,this._attribute=null,this._varying=null,this.global=!0,!0!==e.isStorageBufferAttribute&&!0!==e.isStorageInstancedBufferAttribute&&(e.isInstancedBufferAttribute?e.isStorageInstancedBufferAttribute=!0:e.isStorageBufferAttribute=!0)}getHash(e){if(0===this.bufferCount){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return h_(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(vc.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=wg(this.value),this._varying=sg(this._attribute)),{attribute:this._attribute,varying:this._varying}}getNodeType(e){if(null!==this.structTypeNode)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.getNodeType(e);const{attribute:t}=this.getAttributeData();return t.getNodeType(e)}getMemberType(e,t){return null!==this.structTypeNode?this.structTypeNode.getMemberType(e,t):"void"}generate(e){if(null!==this.structTypeNode&&this.structTypeNode.build(e),e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generate(e);const{attribute:t,varying:s}=this.getAttributeData(),i=s.build(e);return e.registerTransform(i,t),i}}const c_=(e,t=null,s=0)=>new u_(e,t,s);class d_ extends Cc{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),s=this.scope;let i,r;if(s===d_.VERTEX)i=e.getVertexIndex();else if(s===d_.INSTANCE)i=e.getInstanceIndex();else if(s===d_.DRAW)i=e.getDrawIndex();else if(s===d_.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(s===d_.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else{if(s!==d_.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+s);i=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=i;else{r=sg(this).build(e,t)}return r}}d_.VERTEX="vertex",d_.INSTANCE="instance",d_.SUBGROUP="subgroup",d_.INVOCATION_LOCAL="invocationLocal",d_.INVOCATION_SUBGROUP="invocationSubgroup",d_.DRAW="draw";const p_=Sd(d_,d_.VERTEX),m_=Sd(d_,d_.INSTANCE),f_=Sd(d_,d_.SUBGROUP),g_=Sd(d_,d_.INVOCATION_SUBGROUP),y_=Sd(d_,d_.INVOCATION_LOCAL),x_=Sd(d_,d_.DRAW);class b_ extends Cc{static get type(){return"InstanceNode"}constructor(e,t,s=null){super("void"),this.count=e,this.instanceMatrix=t,this.instanceColor=s,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=wc.FRAME,this.buffer=null,this.bufferColor=null}get isStorageMatrix(){const{instanceMatrix:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}get isStorageColor(){const{instanceColor:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}setup(e){const{instanceMatrix:t,instanceColor:s,isStorageMatrix:i,isStorageColor:r}=this,{count:n}=t;let{instanceMatrixNode:o,instanceColorNode:a}=this;if(null===o){if(i)o=c_(t,"mat4",Math.max(n,1)).element(m_);else if(n<=1e3)o=ry(t.array,"mat4",Math.max(n,1)).element(m_);else{const e=new Ku(t.array,16,1);this.buffer=e;const s=t.usage===zo?Tg:vg,i=[s(e,"vec4",16,0),s(e,"vec4",16,4),s(e,"vec4",16,8),s(e,"vec4",16,12)];o=Kd(...i)}this.instanceMatrixNode=o}if(s&&null===a){if(r)a=c_(s,"vec3",Math.max(s.count,1)).element(m_);else{const e=new nu(s.array,3),t=s.usage===zo?Tg:vg;this.bufferColor=e,a=Gd(t(e,"vec3",3,0))}this.instanceColorNode=a}const l=o.mul(Jy).xyz;if(Jy.assign(l),e.hasGeometryAttribute("normal")){const e=yx(ux,o);ux.assign(e)}null!==this.instanceColorNode&&ip("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){null!==this.buffer&&!0!==this.isStorageMatrix&&(this.buffer.clearUpdateRanges(),this.buffer.updateRanges.push(...this.instanceMatrix.updateRanges),this.instanceMatrix.usage!==zo&&this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version)),this.instanceColor&&null!==this.bufferColor&&!0!==this.isStorageColor&&(this.bufferColor.clearUpdateRanges(),this.bufferColor.updateRanges.push(...this.instanceColor.updateRanges),this.instanceColor.usage!==zo&&this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version))}}const __=Td(b_).setParameterLength(2,3);class w_ extends b_{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:s,instanceColor:i}=e;super(t,s,i),this.instancedMesh=e}}const v_=Td(w_).setParameterLength(1);class T_ extends Cc{static get type(){return"BatchNode"}constructor(e){super("void"),this.batchMesh=e,this.batchingIdNode=null}setup(e){null===this.batchingIdNode&&(null===e.getDrawIndex()?this.batchingIdNode=m_:this.batchingIdNode=x_);const t=Ed(([e])=>{const t=Ld(Yg(sy(this.batchMesh._indirectTexture),0).x).toConst(),s=Ld(e).mod(t).toConst(),i=Ld(e).div(t).toConst();return sy(this.batchMesh._indirectTexture,zd(s,i)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]})(Ld(this.batchingIdNode)),s=this.batchMesh._matricesTexture,i=Ld(Yg(sy(s),0).x).toConst(),r=Dd(t).mul(4).toInt().toConst(),n=r.mod(i).toConst(),o=r.div(i).toConst(),a=Kd(sy(s,zd(n,o)),sy(s,zd(n.add(1),o)),sy(s,zd(n.add(2),o)),sy(s,zd(n.add(3),o))),l=this.batchMesh._colorsTexture;if(null!==l){const e=Ed(([e])=>{const t=Ld(Yg(sy(l),0).x).toConst(),s=e,i=s.mod(t).toConst(),r=s.div(t).toConst();return sy(l,zd(i,r)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]})(t);ip("vec3","vBatchColor").assign(e)}const h=Qd(a);Jy.assign(a.mul(Jy));const u=ux.div(Gd(h[0].dot(h[0]),h[1].dot(h[1]),h[2].dot(h[2]))),c=h.mul(u).xyz;ux.assign(c),e.hasGeometryAttribute("tangent")&&sb.mulAssign(h)}}const S_=Td(T_).setParameterLength(1),M_=new WeakMap;class A_ extends Cc{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=wc.OBJECT,this.skinIndexNode=Hg("skinIndex","uvec4"),this.skinWeightNode=Hg("skinWeight","vec4"),this.bindMatrixNode=Ox("bindMatrix","mat4"),this.bindMatrixInverseNode=Ox("bindMatrixInverse","mat4"),this.boneMatricesNode=Vx("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=Jy,this.toPositionNode=Jy,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:n}=this,o=e.element(s.x),a=e.element(s.y),l=e.element(s.z),h=e.element(s.w),u=r.mul(t),c=Zp(o.mul(i.x).mul(u),a.mul(i.y).mul(u),l.mul(i.z).mul(u),h.mul(i.w).mul(u));return n.mul(c).xyz}getSkinnedNormal(e=this.boneMatricesNode,t=ux){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:n}=this,o=e.element(s.x),a=e.element(s.y),l=e.element(s.z),h=e.element(s.w);let u=Zp(i.x.mul(o),i.y.mul(a),i.z.mul(l),i.w.mul(h));return u=n.mul(u).mul(r),u.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=Vx("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,ex)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")||!0===yc(e.object).useVelocity}setup(e){this.needsPreviousBoneMatrices(e)&&ex.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();ux.assign(t),e.hasGeometryAttribute("tangent")&&sb.assign(t)}return t}generate(e,t){if("void"!==t)return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;M_.get(t)!==e.frameId&&(M_.set(t,e.frameId),null!==this.previousBoneMatricesNode&&(null===t.previousBoneMatrices&&(t.previousBoneMatrices=new Float32Array(t.boneMatrices)),t.previousBoneMatrices.set(t.boneMatrices)),t.update())}}const N_=e=>new A_(e);class E_ extends Cc{static get type(){return"LoopNode"}constructor(e=[]){super("void"),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt(0)+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const s={};for(let e=0,t=this.params.length-1;e<t;e++){const t=this.params[e],i=!0!==t.isNode&&t.name||this.getVarName(e),r=!0!==t.isNode&&t.type||"int";s[i]=Fg(i,r)}const i=e.addStack(),r=this.params[this.params.length-1](s);t.returnsNode=r.context({nodeLoop:r}),t.stackNode=i;const n=this.params[0];if(!0!==n.isNode&&"function"==typeof n.update){const e=Ed(this.params[0].update)(s);t.updateNode=e.context({nodeLoop:e})}return e.removeStack(),t}setup(e){if(this.getProperties(e),e.fnCall){e.getDataFromNode(e.fnCall.shaderNode).hasLoop=!0}}generate(e){const t=this.getProperties(e),s=this.params,i=t.stackNode;for(let i=0,r=s.length-1;i<r;i++){const r=s[i];let n,o=!1,a=null,l=null,h=null,u=null,c=null,d=null;if(r.isNode?"bool"===r.getNodeType(e)?(o=!0,u="bool",l=r.build(e,u)):(u="int",h=this.getVarName(i),a="0",l=r.build(e,u),c="<"):(u=r.type||"int",h=r.name||this.getVarName(i),a=r.start,l=r.end,c=r.condition,d=r.update,"number"==typeof a?a=e.generateConst(u,a):a&&a.isNode&&(a=a.build(e,u)),"number"==typeof l?l=e.generateConst(u,l):l&&l.isNode&&(l=l.build(e,u)),void 0!==a&&void 0===l?(a+=" - 1",l="0",c=">="):void 0!==l&&void 0===a&&(a="0",c="<"),void 0===c&&(c=Number(a)>Number(l)?">=":"<")),o)n=`while ( ${l} )`;else{const s={start:a,end:l},i=s.start,r=s.end;let o;const p=()=>c.includes("<")?"+=":"-=";if(null!=d)switch(typeof d){case"function":o=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":o=h+" "+p()+" "+e.generateConst(u,d);break;case"string":o=h+" "+d;break;default:d.isNode?o=h+" "+p()+" "+d.build(e):(Zo("TSL: 'Loop( { update: ... } )' is not a function, string or number."),o="break /* invalid update */")}else d="int"===u||"uint"===u?c.includes("<")?"++":"--":p()+" 1.",o=h+" "+d;n=`for ( ${e.getVar(u,h)+" = "+i}; ${h+" "+c+" "+r}; ${o} )`}e.addFlowCode((0===i?"\n":"")+e.tab+n+" {\n\n").addFlowTab()}const r=i.build(e,"void");t.returnsNode.build(e,"void"),e.removeFlowTab().addFlowCode("\n"+e.tab+r);for(let t=0,s=this.params.length-1;t<s;t++)e.addFlowCode((0===t?"":e.tab)+"}\n\n").removeFlowTab();e.addFlowTab()}}const C_=(...e)=>new E_(vd(e,"int")).toStack(),R_=()=>Fg("break").toStack(),P_=new WeakMap,B_=new Pa,I_=Ed(({bufferMap:e,influence:t,stride:s,width:i,depth:r,offset:n})=>{const o=Ld(p_).mul(s).add(n),a=o.div(i),l=o.sub(a.mul(i));return sy(e,zd(l,a)).depth(r).xyz.mul(t)});class D_ extends Cc{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=Up(1),this.updateType=wc.OBJECT}setup(e){const{geometry:t}=e,s=void 0!==t.morphAttributes.position,i=t.hasAttribute("normal")&&void 0!==t.morphAttributes.normal,r=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,n=void 0!==r?r.length:0,{texture:o,stride:a,size:l}=function(e){const t=void 0!==e.morphAttributes.position,s=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,r=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,n=void 0!==r?r.length:0;let o=P_.get(e);if(void 0===o||o.count!==n){let r=function(){f.dispose(),P_.delete(e),e.removeEventListener("dispose",r)};void 0!==o&&o.texture.dispose();const a=e.morphAttributes.position||[],l=e.morphAttributes.normal||[],h=e.morphAttributes.color||[];let u=0;!0===t&&(u=1),!0===s&&(u=2),!0===i&&(u=3);let c=e.attributes.position.count*u,d=1;const p=4096;c>p&&(d=Math.ceil(c/p),c=p);const m=new Float32Array(c*d*4*n),f=new Da(m,c,d,n);f.type=Nn,f.needsUpdate=!0;const g=4*u;for(let e=0;e<n;e++){const r=a[e],n=l[e],o=h[e],u=c*d*4*e;for(let e=0;e<r.count;e++){const a=e*g;!0===t&&(B_.fromBufferAttribute(r,e),m[u+a+0]=B_.x,m[u+a+1]=B_.y,m[u+a+2]=B_.z,m[u+a+3]=0),!0===s&&(B_.fromBufferAttribute(n,e),m[u+a+4]=B_.x,m[u+a+5]=B_.y,m[u+a+6]=B_.z,m[u+a+7]=0),!0===i&&(B_.fromBufferAttribute(o,e),m[u+a+8]=B_.x,m[u+a+9]=B_.y,m[u+a+10]=B_.z,m[u+a+11]=4===o.itemSize?B_.w:1)}}o={count:n,texture:f,stride:u,size:new ua(c,d)},P_.set(e,o),e.addEventListener("dispose",r)}return o}(t);!0===s&&Jy.mulAssign(this.morphBaseInfluence),!0===i&&ux.mulAssign(this.morphBaseInfluence);const h=Ld(l.width);C_(n,({i:e})=>{const t=Dd(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(sy(this.mesh.morphTexture,zd(Ld(e).add(1),Ld(m_))).r):t.assign(Ox("morphTargetInfluences","float").element(e).toVar()),Pd(t.notEqual(0),()=>{!0===s&&Jy.addAssign(I_({bufferMap:o,influence:t,stride:a,width:h,depth:e,offset:Ld(0)})),!0===i&&ux.addAssign(I_({bufferMap:o,influence:t,stride:a,width:h,depth:e,offset:Ld(1)}))})})}update(){const e=this.morphBaseInfluence;this.mesh.geometry.morphTargetsRelative?e.value=1:e.value=1-this.mesh.morphTargetInfluences.reduce((e,t)=>e+t,0)}}const L_=Td(D_).setParameterLength(1);class F_ extends Cc{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class O_ extends F_{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class V_ extends Uf{static get type(){return"LightingContextNode"}constructor(e,t=null,s=null,i=null){super(e),this.lightingModel=t,this.backdropNode=s,this.backdropAlphaNode=i,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,s={directDiffuse:Gd().toVar("directDiffuse"),directSpecular:Gd().toVar("directSpecular"),indirectDiffuse:Gd().toVar("indirectDiffuse"),indirectSpecular:Gd().toVar("indirectSpecular")};return{radiance:Gd().toVar("radiance"),irradiance:Gd().toVar("irradiance"),iblIrradiance:Gd().toVar("iblIrradiance"),ambientOcclusion:Dd(1).toVar("ambientOcclusion"),reflectedLight:s,backdrop:e,backdropAlpha:t}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const z_=Td(V_);class k_ extends F_{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const U_=new ua;class G_ extends Jg{static get type(){return"ViewportTextureNode"}constructor(e=py,t=null,s=null){let i=null;null===s?(i=new bu,i.minFilter=_n,s=i):i=s,super(s,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=i,this.isOutputTextureNode=!0,this.updateBeforeType=wc.FRAME,this._cacheTextures=new WeakMap}getTextureForReference(e=null){let t,s;if(this.referenceNode?(t=this.referenceNode.defaultFramebuffer,s=this.referenceNode._cacheTextures):(t=this.defaultFramebuffer,s=this._cacheTextures),null===e)return t;if(!1===s.has(e)){const i=t.clone();s.set(e,i)}return s.get(e)}updateReference(e){const t=e.renderer.getRenderTarget();return this.value=this.getTextureForReference(t),this.value}updateBefore(e){const t=e.renderer,s=t.getRenderTarget();null===s?t.getDrawingBufferSize(U_):U_.set(s.width,s.height);const i=this.getTextureForReference(s);i.image.width===U_.width&&i.image.height===U_.height||(i.image.width=U_.width,i.image.height=U_.height,i.needsUpdate=!0);const r=i.generateMipmaps;i.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(i),i.generateMipmaps=r}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const j_=Td(G_).setParameterLength(0,3),$_=Td(G_,null,null,{generateMipmaps:!0}).setParameterLength(0,3);let W_=null;class H_ extends G_{static get type(){return"ViewportDepthTextureNode"}constructor(e=py,t=null){null===W_&&(W_=new _u),super(e,t,W_)}getTextureForReference(){return W_}}const q_=Td(H_).setParameterLength(0,2);class X_ extends Cc{static get type(){return"ViewportDepthNode"}constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(e){const{scope:t}=this;return t===X_.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,s=this.valueNode;let i=null;if(t===X_.DEPTH_BASE)null!==s&&(i=J_().assign(s));else if(t===X_.DEPTH)i=e.isPerspectiveCamera?Z_(ix.z,vy,Ty):Y_(ix.z,vy,Ty);else if(t===X_.LINEAR_DEPTH)if(null!==s)if(e.isPerspectiveCamera){const e=Q_(s,vy,Ty);i=Y_(e,vy,Ty)}else i=s;else i=Y_(ix.z,vy,Ty);return i}}X_.DEPTH_BASE="depthBase",X_.DEPTH="depth",X_.LINEAR_DEPTH="linearDepth";const Y_=(e,t,s)=>e.add(t).div(t.sub(s)),Z_=(e,t,s)=>t.add(e).mul(s).div(s.sub(t).mul(e)),Q_=(e,t,s)=>t.mul(s).div(s.sub(t).mul(e).sub(s)),K_=(e,t,s)=>{t=t.max(1e-6).toVar();const i=Fm(e.negate().div(t)),r=Fm(s.div(t));return i.div(r)},J_=Td(X_,X_.DEPTH_BASE),ew=Sd(X_,X_.DEPTH),tw=Td(X_,X_.LINEAR_DEPTH).setParameterLength(0,1),sw=tw(q_());ew.assign=e=>J_(e);class iw extends Cc{static get type(){return"ClippingNode"}constructor(e=iw.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:s,unionPlanes:i}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===iw.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(s,i):this.scope===iw.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(s,i)}setupAlphaToCoverage(e,t){return Ed(()=>{const s=Dd().toVar("distanceToPlane"),i=Dd().toVar("distanceToGradient"),r=Dd(1).toVar("clipOpacity"),n=t.length;if(!1===this.hardwareClipping&&n>0){const e=ay(t).setGroup(Vp);C_(n,({i:t})=>{const n=e.element(t);s.assign(ix.dot(n.xyz).negate().add(n.w)),i.assign(s.fwidth().div(2)),r.mulAssign(Rf(i.negate(),i,s))})}const o=e.length;if(o>0){const t=ay(e).setGroup(Vp),n=Dd(1).toVar("intersectionClipOpacity");C_(o,({i:e})=>{const r=t.element(e);s.assign(ix.dot(r.xyz).negate().add(r.w)),i.assign(s.fwidth().div(2)),n.mulAssign(Rf(i.negate(),i,s).oneMinus())}),r.mulAssign(n.oneMinus())}rp.a.mulAssign(r),rp.a.equal(0).discard()})()}setupDefault(e,t){return Ed(()=>{const s=t.length;if(!1===this.hardwareClipping&&s>0){const e=ay(t).setGroup(Vp);C_(s,({i:t})=>{const s=e.element(t);ix.dot(s.xyz).greaterThan(s.w).discard()})}const i=e.length;if(i>0){const t=ay(e).setGroup(Vp),s=Od(!0).toVar("clipped");C_(i,({i:e})=>{const i=t.element(e);s.assign(ix.dot(i.xyz).greaterThan(i.w).and(s))}),s.discard()}})()}setupHardwareClipping(e,t){const s=e.length;return t.enableHardwareClipping(s),Ed(()=>{const i=ay(e).setGroup(Vp),r=ly(t.getClipDistance());C_(s,({i:e})=>{const t=i.element(e),s=ix.dot(t.xyz).sub(t.w).negate();r.element(e).assign(s)})})()}}iw.ALPHA_TO_COVERAGE="alphaToCoverage",iw.DEFAULT="default",iw.HARDWARE="hardware";const rw=Ed(([e])=>Gm(Kp(1e4,jm(Kp(17,e.x).add(Kp(.1,e.y)))).mul(Zp(.1,Ym(jm(Kp(13,e.y).add(e.x))))))),nw=Ed(([e])=>rw(Vd(rw(e.xy),e.z))),ow=Ed(([e])=>{const t=df(Qm(ef(e.xyz)),Qm(tf(e.xyz))),s=Dd(1).div(Dd(.05).mul(t)).toVar("pixScale"),i=Vd(Dm(zm(Fm(s))),Dm(km(Fm(s)))),r=Vd(nw(zm(i.x.mul(e.xyz))),nw(zm(i.y.mul(e.xyz)))),n=Gm(Fm(s)),o=Zp(Kp(n.oneMinus(),r.x),Kp(n,r.y)),a=cf(n,n.oneMinus()),l=Gd(o.mul(o).div(Kp(2,a).mul(Qp(1,a))),o.sub(Kp(.5,a)).div(Qp(1,a)),Qp(1,Qp(1,o).mul(Qp(1,o)).div(Kp(2,a).mul(Qp(1,a))))),h=o.lessThan(a.oneMinus()).select(o.lessThan(a).select(l.x,l.y),l.z);return Nf(h,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class aw extends Wg{static get type(){return"VertexColorNode"}constructor(e){super(null,"vec4"),this.isVertexColorNode=!0,this.index=e}getAttributeName(){const e=this.index;return"color"+(e>0?e:"")}generate(e){const t=this.getAttributeName(e);let s;return s=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new Pa(1,1,1,1)),s}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const lw=(e=0)=>new aw(e),hw=Ed(([e,t])=>cf(1,e.oneMinus().div(t)).oneMinus()).setLayout({name:"blendBurn",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),uw=Ed(([e,t])=>cf(e.div(t.oneMinus()),1)).setLayout({name:"blendDodge",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),cw=Ed(([e,t])=>e.oneMinus().mul(t.oneMinus()).oneMinus()).setLayout({name:"blendScreen",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),dw=Ed(([e,t])=>Af(e.mul(2).mul(t),e.oneMinus().mul(2).mul(t.oneMinus()).oneMinus(),pf(.5,e))).setLayout({name:"blendOverlay",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),pw=Ed(([e,t])=>{const s=t.a.add(e.a.mul(t.a.oneMinus()));return Hd(t.rgb.mul(t.a).add(e.rgb.mul(e.a).mul(t.a.oneMinus())).div(s),s)}).setLayout({name:"blendColor",type:"vec4",inputs:[{name:"base",type:"vec4"},{name:"blend",type:"vec4"}]}),mw=Ed(([e])=>Hd(e.rgb.mul(e.a),e.a),{color:"vec4",return:"vec4"}),fw=Ed(([e])=>(Pd(e.a.equal(0),()=>Hd(0)),Hd(e.rgb.div(e.a),e.a)),{color:"vec4",return:"vec4"});class gw extends ih{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,this.contextNode=null,Object.defineProperty(this,"shadowPositionNode",{get:()=>this.receivedShadowPositionNode,set:e=>{Yo('NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".'),this.receivedShadowPositionNode=e}})}_getNodeChildren(){const e=[];for(const t of Object.getOwnPropertyNames(this)){if(!0===t.startsWith("_"))continue;const s=this[t];s&&!0===s.isNode&&e.push({property:t,childNode:s})}return e}customProgramCacheKey(){const e=[];for(const{property:t,childNode:s}of this._getNodeChildren())e.push(nc(t.slice(0,-4)),s.getCacheKey());return this.type+oc(e)}build(e){this.setup(e)}setupObserver(e){return new ic(e)}setup(e){e.context.setupNormal=()=>eg(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,s=t.getRenderTarget();!0===t.contextNode.isContextNode?e.context={...e.context,...t.contextNode.getFlowContextData()}:Zo('NodeMaterial: "renderer.contextNode" must be an instance of `context()`.'),null!==this.contextNode&&(!0===this.contextNode.isContextNode?e.context={...e.context,...this.contextNode.getFlowContextData()}:Zo('NodeMaterial: "material.contextNode" must be an instance of `context()`.')),e.addStack();const i=eg(this.setupVertex(e),"VERTEX"),r=this.vertexNode||i;let n;e.stack.outputNode=r,this.setupHardwareClipping(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const o=this.setupClipping(e);if(!0!==this.depthWrite&&!0!==this.depthTest||(null!==s?!0===s.depthBuffer&&this.setupDepth(e):!0===t.depth&&this.setupDepth(e)),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupVariants(e);const i=this.setupLighting(e);null!==o&&e.stack.addToStack(o);const r=Hd(i,rp.a).max(0);n=this.setupOutput(e,r),Sp.assign(n);const a=null!==this.outputNode;if(a&&(n=this.outputNode),e.context.getOutput&&(n=e.context.getOutput(n,e)),null!==s){const e=t.getMRT(),s=this.mrtNode;null!==e?(a&&Sp.assign(n),n=e,null!==s&&(n=e.merge(s))):null!==s&&(n=s)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=Hd(t)),n=this.setupOutput(e,t)}e.stack.outputNode=n,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{unionPlanes:t,intersectionPlanes:s}=e.clippingContext;let i=null;if(t.length>0||s.length>0){const t=e.renderer.currentSamples;this.alphaToCoverage&&t>1?i=new iw(iw.ALPHA_TO_COVERAGE):e.stack.addToStack(new iw)}return i}setupHardwareClipping(e){if(this.hardwareClipping=!1,null===e.clippingContext)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.addToStack(new iw(iw.HARDWARE)),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:s}=e;let i=this.depthNode;if(null===i){const e=t.getMRT();e&&e.has("depth")?i=e.get("depth"):!0===t.logarithmicDepthBuffer&&(i=s.isPerspectiveCamera?K_(ix.z,vy,Ty):Y_(ix.z,vy,Ty))}null!==i&&ew.assign(i).toStack()}setupPositionView(){return Xy.mul(Jy).xyz}setupModelViewProjection(){return Sy.mul(ix)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.vertex=e.removeStack(),a_}setupPosition(e){const{object:t,geometry:s}=e;if((s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color)&&L_(t).toStack(),!0===t.isSkinnedMesh&&N_(t).toStack(),this.displacementMap){const e=kx("displacementMap","texture"),t=kx("displacementScale","float"),s=kx("displacementBias","float");Jy.addAssign(ux.normalize().mul(e.x.mul(t).add(s)))}return t.isBatchedMesh&&S_(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&v_(t).toStack(),null!==this.positionNode&&Jy.assign(eg(this.positionNode,"POSITION","vec3")),Jy}setupDiffuseColor(e){const{object:t,geometry:s}=e;null!==this.maskNode&&Od(this.maskNode).not().discard();let i=this.colorNode?Hd(this.colorNode):Sb;if(!0===this.vertexColors&&s.hasAttribute("color")&&(i=i.mul(lw())),t.instanceColor){i=ip("vec3","vInstanceColor").mul(i)}if(t.isBatchedMesh&&t._colorsTexture){i=ip("vec3","vBatchColor").mul(i)}rp.assign(i);const r=this.opacityNode?Dd(this.opacityNode):Nb;rp.a.assign(rp.a.mul(r));let n=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(n=null!==this.alphaTestNode?Dd(this.alphaTestNode):Tb,!0===this.alphaToCoverage?(rp.a=Rf(n,n.add(of(rp.a)),rp.a),rp.a.lessThanEqual(0).discard()):rp.a.lessThanEqual(n).discard()),!0===this.alphaHash&&rp.a.lessThan(ow(Jy)).discard(),e.isOpaque()&&rp.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?Gd(0):rp.rgb}setupNormal(){return this.normalNode?Gd(this.normalNode):Lb}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?kx("envMap","cubeTexture"):kx("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new k_(r_)),t}setupLights(e){const t=[],s=this.setupEnvironment(e);s&&s.isLightingNode&&t.push(s);const i=this.setupLightMap(e);i&&i.isLightingNode&&t.push(i);let r=this.aoNode;null===r&&e.material.aoMap&&(r=n_),e.context.getAO&&(r=e.context.getAO(r,e)),r&&t.push(new O_(r));let n=this.lightsNode||e.lightsNode;return t.length>0&&(n=e.renderer.lighting.createNode([...n.getLights(),...t])),n}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:s,backdropAlphaNode:i,emissiveNode:r}=this,n=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let o=this.setupOutgoingLight(e);if(n&&n.getScope().hasLights){const t=this.setupLightingModel(e)||null;o=z_(n,t,s,i)}else null!==s&&(o=Gd(null!==i?Af(o,s,i):s));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(op.assign(Gd(r||Ab)),o=o.add(op)),o}setupFog(e,t){const s=e.fogNode;return s&&(Sp.assign(t),t=Hd(s.toVar())),t}setupPremultipliedAlpha(e,t){return mw(t)}setupOutput(e,t){return!0===this.fog&&(t=this.setupFog(e,t)),!0===this.premultipliedAlpha&&(t=this.setupPremultipliedAlpha(e,t)),t}setDefaultValues(e){for(const t in e){const s=e[t];void 0===this[t]&&(this[t]=s,s&&s.clone&&(this[t]=s.clone()))}const t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(const e in t)void 0===Object.getOwnPropertyDescriptor(this.constructor.prototype,e)&&void 0!==t[e].get&&Object.defineProperty(this.constructor.prototype,e,t[e])}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{},nodes:{}});const s=ih.prototype.toJSON.call(this,e);s.inputNodes={};for(const{property:t,childNode:i}of this._getNodeChildren())s.inputNodes[t]=i.toJSON(e).uuid;function i(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(t){const t=i(e.textures),r=i(e.images),n=i(e.nodes);t.length>0&&(s.textures=t),r.length>0&&(s.images=r),n.length>0&&(s.nodes=n)}return s}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.aoNode=e.aoNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,this.contextNode=e.contextNode,super.copy(e)}}const yw=new yu;class xw extends gw{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(yw),this.setValues(e)}}const bw=new Iu;class _w extends gw{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(bw),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?Dd(this.offsetNode):t_,t=this.dashScaleNode?Dd(this.dashScaleNode):Qb,s=this.dashSizeNode?Dd(this.dashSizeNode):Kb,i=this.gapSizeNode?Dd(this.gapSizeNode):Jb;Mp.assign(s),Ap.assign(i);const r=sg(Hg("lineDistance").mul(t));(e?r.add(e):r).mod(Mp.add(Ap)).greaterThan(Mp).discard()}}let ww=null;class vw extends G_{static get type(){return"ViewportSharedTextureNode"}constructor(e=py,t=null){null===ww&&(ww=new bu),super(e,t,ww)}getTextureForReference(){return ww}updateReference(){return this}}const Tw=Td(vw).setParameterLength(0,2),Sw=new Ru;class Mw extends gw{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(Sw),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?Dd(this.opacityNode):Nb;rp.assign(hg(Hd(pb(mx),e),Mo))}}const Aw=Ed(([e=sx])=>{const t=e.z.atan(e.x).mul(1/(2*Math.PI)).add(.5),s=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return Vd(t,s)});class Nw extends Yh{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!0}fromEquirectangularTexture(e,t){const s=t.minFilter,i=t.generateMipmaps;t.generateMipmaps=!0,this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const r=new Vh(5,5,5),n=Aw(sx),o=new gw;o.colorNode=ty(t,n,0),o.side=1,o.blending=0;const a=new Fh(r,o),l=new Jh;l.add(a),t.minFilter===_n&&(t.minFilter=xn);const h=new qh(1,10,this),u=e.getMRT();return e.setMRT(null),h.update(e,l),e.setMRT(u),t.minFilter=s,t.currentGenerateMipmaps=i,a.geometry.dispose(),a.material.dispose(),this}}const Ew=new WeakMap;class Cw extends Bc{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=Dx(null);const t=new Xh;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=wc.RENDER}updateBefore(e){const{renderer:t,material:s}=e,i=this.envNode;if(i.isTextureNode||i.isMaterialReferenceNode){const e=i.isTextureNode?i.value:s[i.property];if(e&&e.isTexture){const s=e.mapping;if(303===s||304===s){if(Ew.has(e)){const t=Ew.get(e);Pw(t,e.mapping),this._cubeTexture=t}else{const s=e.image;if(function(e){return null!=e&&e.height>0}(s)){const i=new Nw(s.height);i.fromEquirectangularTexture(t,e),Pw(i.texture,e.mapping),this._cubeTexture=i.texture,Ew.set(e,i.texture),e.addEventListener("dispose",Rw)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function Rw(e){const t=e.target;t.removeEventListener("dispose",Rw);const s=Ew.get(t);void 0!==s&&(Ew.delete(t),s.dispose())}function Pw(e,t){303===t?e.mapping=un:304===t&&(e.mapping=cn)}const Bw=Td(Cw).setParameterLength(1);class Iw extends F_{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=Bw(this.envNode)}}class Dw extends F_{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=Dd(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class Lw{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Fw extends Lw{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,s=e.reflectedLight,i=e.irradianceLightMap;s.indirectDiffuse.assign(Hd(0)),i?s.indirectDiffuse.addAssign(i):s.indirectDiffuse.addAssign(Hd(1,1,1,0)),s.indirectDiffuse.mulAssign(t),s.indirectDiffuse.mulAssign(rp.rgb)}finish(e){const{material:t,context:s}=e,i=s.outgoingLight,r=e.context.environment;if(r)switch(t.combine){case 0:i.rgb.assign(Af(i.rgb,i.rgb.mul(r.rgb),Pb.mul(Bb)));break;case 1:i.rgb.assign(Af(i.rgb,r.rgb,Pb.mul(Bb)));break;case 2:i.rgb.addAssign(r.rgb.mul(Pb.mul(Bb)));break;default:Yo("BasicLightingModel: Unsupported .combine value:",t.combine)}}}const Ow=new rh;class Vw extends gw{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Ow),this.setValues(e)}setupNormal(){return lx(dx)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Iw(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Dw(r_)),t}setupOutgoingLight(){return rp.rgb}setupLightingModel(){return new Fw}}const zw=Ed(({f0:e,f90:t,dotVH:s})=>{const i=s.mul(-5.55473).sub(6.98316).mul(s).exp2();return e.mul(i.oneMinus()).add(t.mul(i))}),kw=Ed(e=>e.diffuseColor.mul(1/Math.PI)),Uw=Ed(({dotNH:e})=>Tp.mul(Dd(.5)).add(1).mul(Dd(1/Math.PI)).mul(e.pow(Tp))),Gw=Ed(({lightDirection:e})=>{const t=e.add(rx).normalize(),s=mx.dot(t).clamp(),i=rx.dot(t).clamp(),r=zw({f0:_p,f90:1,dotVH:i}),n=Dd(.25),o=Uw({dotNH:s});return r.mul(n).mul(o)});class jw extends Fw{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=mx.dot(e).clamp().mul(t);s.directDiffuse.addAssign(i.mul(kw({diffuseColor:rp.rgb}))),!0===this.specular&&s.directSpecular.addAssign(i.mul(Gw({lightDirection:e})).mul(Pb))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(kw({diffuseColor:rp}))),i.indirectDiffuse.mulAssign(t)}}const $w=new Pu;class Ww extends gw{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues($w),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Iw(t):null}setupLightingModel(){return new jw(!1)}}const Hw=new Eu;class qw extends gw{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(Hw),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Iw(t):null}setupLightingModel(){return new jw}setupVariants(){const e=(this.shininessNode?Dd(this.shininessNode):Mb).max(1e-4);Tp.assign(e);const t=this.specularNode||Eb;_p.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const Xw=Ed(e=>{if(!1===e.geometry.hasAttribute("normal"))return Dd(0);const t=dx.dFdx().abs().max(dx.dFdy().abs());return t.x.max(t.y).max(t.z)}),Yw=Ed(e=>{const{roughness:t}=e,s=Xw();let i=t.max(.0525);return i=i.add(s),i=i.min(1),i}),Zw=Ed(({alpha:e,dotNL:t,dotNV:s})=>{const i=e.pow2(),r=t.mul(i.add(i.oneMinus().mul(s.pow2())).sqrt()),n=s.mul(i.add(i.oneMinus().mul(t.pow2())).sqrt());return Jp(.5,r.add(n).max(Tm))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),Qw=Ed(({alphaT:e,alphaB:t,dotTV:s,dotBV:i,dotTL:r,dotBL:n,dotNV:o,dotNL:a})=>{const l=a.mul(Gd(e.mul(s),t.mul(i),o).length()),h=o.mul(Gd(e.mul(r),t.mul(n),a).length());return Jp(.5,l.add(h))}).setLayout({name:"V_GGX_SmithCorrelated_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotTV",type:"float",qualifier:"in"},{name:"dotBV",type:"float",qualifier:"in"},{name:"dotTL",type:"float",qualifier:"in"},{name:"dotBL",type:"float",qualifier:"in"},{name:"dotNV",type:"float",qualifier:"in"},{name:"dotNL",type:"float",qualifier:"in"}]}),Kw=Ed(({alpha:e,dotNH:t})=>{const s=e.pow2(),i=t.pow2().mul(s.oneMinus()).oneMinus();return s.div(i.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),Jw=Dd(1/Math.PI),ev=Ed(({alphaT:e,alphaB:t,dotNH:s,dotTH:i,dotBH:r})=>{const n=e.mul(t),o=Gd(t.mul(i),e.mul(r),n.mul(s)),a=o.dot(o),l=n.div(a);return Jw.mul(n.mul(l.pow2()))}).setLayout({name:"D_GGX_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotNH",type:"float",qualifier:"in"},{name:"dotTH",type:"float",qualifier:"in"},{name:"dotBH",type:"float",qualifier:"in"}]}),tv=Ed(({lightDirection:e,f0:t,f90:s,roughness:i,f:r,normalView:n=mx,USE_IRIDESCENCE:o,USE_ANISOTROPY:a})=>{const l=i.pow2(),h=e.add(rx).normalize(),u=n.dot(e).clamp(),c=n.dot(rx).clamp(),d=n.dot(h).clamp(),p=rx.dot(h).clamp();let m,f,g=zw({f0:t,f90:s,dotVH:p});if(gd(o)&&(g=pp.mix(g,r)),gd(a)){const t=xp.dot(e),s=xp.dot(rx),i=xp.dot(h),r=bp.dot(e),n=bp.dot(rx),o=bp.dot(h);m=Qw({alphaT:gp,alphaB:l,dotTV:s,dotBV:n,dotTL:t,dotBL:r,dotNV:c,dotNL:u}),f=ev({alphaT:gp,alphaB:l,dotNH:d,dotTH:i,dotBH:o})}else m=Zw({alpha:l,dotNL:u,dotNV:c}),f=Kw({alpha:l,dotNH:d});return g.mul(m).mul(f)}),sv=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let iv=null;const rv=Ed(({roughness:e,dotNV:t})=>{null===iv&&(iv=new ru(sv,16,16,kn,En),iv.name="DFG_LUT",iv.minFilter=xn,iv.magFilter=xn,iv.wrapS=pn,iv.wrapT=pn,iv.generateMipmaps=!1,iv.needsUpdate=!0);const s=Vd(e,t);return ty(iv,s).rg}),nv=Ed(({lightDirection:e,f0:t,f90:s,roughness:i,f:r,USE_IRIDESCENCE:n,USE_ANISOTROPY:o})=>{const a=tv({lightDirection:e,f0:t,f90:s,roughness:i,f:r,USE_IRIDESCENCE:n,USE_ANISOTROPY:o}),l=mx.dot(e).clamp(),h=mx.dot(rx).clamp(),u=rv({roughness:i,dotNV:h}),c=rv({roughness:i,dotNV:l}),d=t.mul(u.x).add(s.mul(u.y)),p=t.mul(c.x).add(s.mul(c.y)),m=u.x.add(u.y),f=c.x.add(c.y),g=Dd(1).sub(m),y=Dd(1).sub(f),x=t.add(t.oneMinus().mul(.047619)),b=d.mul(p).mul(x).div(Dd(1).sub(g.mul(y).mul(x).mul(x)).add(Tm)),_=g.mul(y),w=b.mul(_);return a.add(w)}),ov=Ed(e=>{const{dotNV:t,specularColor:s,specularF90:i,roughness:r}=e,n=rv({dotNV:t,roughness:r});return s.mul(n.x).add(i.mul(n.y))}),av=Ed(({f:e,f90:t,dotVH:s})=>{const i=s.oneMinus().saturate(),r=i.mul(i),n=i.mul(r,r).clamp(0,.9999);return e.sub(Gd(t).mul(n)).div(n.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),lv=Ed(({roughness:e,dotNH:t})=>{const s=e.pow2(),i=Dd(1).div(s),r=t.pow2().oneMinus().max(.0078125);return Dd(2).add(i).mul(r.pow(i.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),hv=Ed(({dotNV:e,dotNL:t})=>Dd(1).div(Dd(4).mul(t.add(e).sub(t.mul(e))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),uv=Ed(({lightDirection:e})=>{const t=e.add(rx).normalize(),s=mx.dot(e).clamp(),i=mx.dot(rx).clamp(),r=mx.dot(t).clamp(),n=lv({roughness:dp,dotNH:r}),o=hv({dotNV:i,dotNL:s});return cp.mul(n).mul(o)}),cv=Ed(({N:e,V:t,roughness:s})=>{const i=e.dot(t).saturate(),r=Vd(s,i.oneMinus().sqrt());return r.assign(r.mul(.984375).add(.0078125)),r}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),dv=Ed(({f:e})=>{const t=e.length();return df(t.mul(t).add(e.z).div(t.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),pv=Ed(({v1:e,v2:t})=>{const s=e.dot(t),i=s.abs().toVar(),r=i.mul(.0145206).add(.4965155).mul(i).add(.8543985).toVar(),n=i.add(4.1616724).mul(i).add(3.417594).toVar(),o=r.div(n),a=s.greaterThan(0).select(o,df(s.mul(s).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(o));return e.cross(t).mul(a)}).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),mv=Ed(({N:e,V:t,P:s,mInv:i,p0:r,p1:n,p2:o,p3:a})=>{const l=n.sub(r).toVar(),h=a.sub(r).toVar(),u=l.cross(h),c=Gd().toVar();return Pd(u.dot(s.sub(r)).greaterThanEqual(0),()=>{const l=t.sub(e.mul(t.dot(e))).normalize(),h=e.cross(l).negate(),u=i.mul(Qd(l,h,e).transpose()).toVar(),d=u.mul(r.sub(s)).normalize().toVar(),p=u.mul(n.sub(s)).normalize().toVar(),m=u.mul(o.sub(s)).normalize().toVar(),f=u.mul(a.sub(s)).normalize().toVar(),g=Gd(0).toVar();g.addAssign(pv({v1:d,v2:p})),g.addAssign(pv({v1:p,v2:m})),g.addAssign(pv({v1:m,v2:f})),g.addAssign(pv({v1:f,v2:d})),c.assign(Gd(dv({f:g})))}),c}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"P",type:"vec3"},{name:"mInv",type:"mat3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),fv=1/6,gv=e=>Kp(fv,Kp(e,Kp(e,e.negate().add(3)).sub(3)).add(1)),yv=e=>Kp(fv,Kp(e,Kp(e,Kp(3,e).sub(6))).add(4)),xv=e=>Kp(fv,Kp(e,Kp(e,Kp(-3,e).add(3)).add(3)).add(1)),bv=e=>Kp(fv,bf(e,3)),_v=e=>gv(e).add(yv(e)),wv=e=>xv(e).add(bv(e)),vv=e=>Zp(-1,yv(e).div(gv(e).add(yv(e)))),Tv=e=>Zp(1,bv(e).div(xv(e).add(bv(e)))),Sv=(e,t,s)=>{const i=e.uvNode,r=Kp(i,t.zw).add(.5),n=zm(r),o=Gm(r),a=_v(o.x),l=wv(o.x),h=vv(o.x),u=Tv(o.x),c=vv(o.y),d=Tv(o.y),p=Vd(n.x.add(h),n.y.add(c)).sub(.5).mul(t.xy),m=Vd(n.x.add(u),n.y.add(c)).sub(.5).mul(t.xy),f=Vd(n.x.add(h),n.y.add(d)).sub(.5).mul(t.xy),g=Vd(n.x.add(u),n.y.add(d)).sub(.5).mul(t.xy),y=_v(o.y).mul(Zp(a.mul(e.sample(p).level(s)),l.mul(e.sample(m).level(s)))),x=wv(o.y).mul(Zp(a.mul(e.sample(f).level(s)),l.mul(e.sample(g).level(s))));return y.add(x)},Mv=Ed(([e,t])=>{const s=Vd(e.size(Ld(t))),i=Vd(e.size(Ld(t.add(1)))),r=Jp(1,s),n=Jp(1,i),o=Sv(e,Hd(r,s),zm(t)),a=Sv(e,Hd(n,i),km(t));return Gm(t).mix(o,a)}),Av=Ed(([e,t])=>{const s=t.mul(Qg(e));return Mv(e,s)}),Nv=Ed(([e,t,s,i,r])=>{const n=Gd(Cf(t.negate(),Um(e),Jp(1,i))),o=Gd(Qm(r[0].xyz),Qm(r[1].xyz),Qm(r[2].xyz));return Um(n).mul(s.mul(o))}).setLayout({name:"getVolumeTransmissionRay",type:"vec3",inputs:[{name:"n",type:"vec3"},{name:"v",type:"vec3"},{name:"thickness",type:"float"},{name:"ior",type:"float"},{name:"modelMatrix",type:"mat4"}]}),Ev=Ed(([e,t])=>e.mul(Nf(t.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),Cv=$_(),Rv=$_(),Pv=Ed(([e,t,s],{material:i})=>{const r=(1===i.side?Cv:Rv).sample(e),n=Fm(my.x).mul(Ev(t,s));return Mv(r,n)}),Bv=Ed(([e,t,s])=>(Pd(s.notEqual(0),()=>{const i=Lm(t).negate().div(s);return Im(i.negate().mul(e))}),Gd(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),Iv=Ed(([e,t,s,i,r,n,o,a,l,h,u,c,d,p,m])=>{let f,g;if(m){f=Hd().toVar(),g=Gd().toVar();const r=u.sub(1).mul(m.mul(.025)),n=Gd(u.sub(r),u,u.add(r));C_({start:0,end:3},({i:r})=>{const u=n.element(r),m=Nv(e,t,c,u,a),y=o.add(m),x=h.mul(l.mul(Hd(y,1))),b=Vd(x.xy.div(x.w)).toVar();b.addAssign(1),b.divAssign(2),b.assign(Vd(b.x,b.y.oneMinus()));const _=Pv(b,s,u);f.element(r).assign(_.element(r)),f.a.addAssign(_.a),g.element(r).assign(i.element(r).mul(Bv(Qm(m),d,p).element(r)))}),f.a.divAssign(3)}else{const r=Nv(e,t,c,u,a),n=o.add(r),m=h.mul(l.mul(Hd(n,1))),y=Vd(m.xy.div(m.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(Vd(y.x,y.y.oneMinus())),f=Pv(y,s,u),g=i.mul(Bv(Qm(r),d,p))}const y=g.rgb.mul(f.rgb),x=e.dot(t).clamp(),b=Gd(ov({dotNV:x,specularColor:r,specularF90:n,roughness:s})),_=g.r.add(g.g,g.b).div(3);return Hd(b.oneMinus().mul(y),f.a.oneMinus().mul(_).oneMinus())}),Dv=Qd(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),Lv=(e,t)=>e.sub(t).div(e.add(t)).pow2(),Fv=Ed(({outsideIOR:e,eta2:t,cosTheta1:s,thinFilmThickness:i,baseF0:r})=>{const n=Af(e,t,Rf(0,.03,i)),o=e.div(n).pow2().mul(s.pow2().oneMinus()).oneMinus();Pd(o.lessThan(0),()=>Gd(1));const a=o.sqrt(),l=Lv(n,e),h=zw({f0:l,f90:1,dotVH:s}),u=h.oneMinus(),c=n.lessThan(e).select(Math.PI,0),d=Dd(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return Gd(1).add(t).div(Gd(1).sub(t))})(r.clamp(0,.9999)),m=Lv(p,n.toVec3()),f=zw({f0:m,f90:1,dotVH:a}),g=Gd(p.x.lessThan(n).select(Math.PI,0),p.y.lessThan(n).select(Math.PI,0),p.z.lessThan(n).select(Math.PI,0)),y=n.mul(i,a,2),x=Gd(d).add(g),b=h.mul(f).clamp(1e-5,.9999),_=b.sqrt(),w=u.pow2().mul(f).div(Gd(1).sub(b)),v=h.add(w).toVar(),T=w.sub(u).toVar();return C_({start:1,end:2,condition:"<=",name:"m"},({m:e})=>{T.mulAssign(_);const t=((e,t)=>{const s=e.mul(2*Math.PI*1e-9),i=Gd(54856e-17,44201e-17,52481e-17),r=Gd(1681e3,1795300,2208400),n=Gd(43278e5,93046e5,66121e5),o=Dd(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(s.mul(2239900).add(t.x).cos()).mul(s.pow2().mul(-45282e5).exp());let a=i.mul(n.mul(2*Math.PI).sqrt()).mul(r.mul(s).add(t).cos()).mul(s.pow2().negate().mul(n).exp());return a=Gd(a.x.add(o),a.y,a.z).div(1.0685e-7),Dv.mul(a)})(Dd(e).mul(y),Dd(e).mul(x)).mul(2);v.addAssign(T.mul(t))}),v.max(Gd(0))}).setLayout({name:"evalIridescence",type:"vec3",inputs:[{name:"outsideIOR",type:"float"},{name:"eta2",type:"float"},{name:"cosTheta1",type:"float"},{name:"thinFilmThickness",type:"float"},{name:"baseF0",type:"vec3"}]}),Ov=Ed(({normal:e,viewDir:t,roughness:s})=>{const i=e.dot(t).saturate(),r=s.mul(s),n=s.add(.1).reciprocal(),o=Dd(-1.9362).add(s.mul(1.0678)).add(r.mul(.4573)).sub(n.mul(.8469)),a=Dd(-.6014).add(s.mul(.5538)).sub(r.mul(.467)).sub(n.mul(.1255));return o.mul(i).add(a).exp().saturate()}),Vv=Gd(.04),zv=Dd(1);class kv extends Lw{constructor(e=!1,t=!1,s=!1,i=!1,r=!1,n=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=s,this.anisotropy=i,this.transmission=r,this.dispersion=n,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null,this.iridescenceF0Dielectric=null,this.iridescenceF0Metallic=null}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=Gd().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=Gd().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=Gd().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=Gd().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=Gd().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=mx.dot(rx).clamp(),t=Fv({outsideIOR:Dd(1),eta2:mp,cosTheta1:e,thinFilmThickness:fp,baseF0:_p}),s=Fv({outsideIOR:Dd(1),eta2:mp,cosTheta1:e,thinFilmThickness:fp,baseF0:rp.rgb});this.iridescenceFresnel=Af(t,s,lp),this.iridescenceF0Dielectric=av({f:t,f90:1,dotVH:e}),this.iridescenceF0Metallic=av({f:s,f90:1,dotVH:e}),this.iridescenceF0=Af(this.iridescenceF0Dielectric,this.iridescenceF0Metallic,lp)}if(!0===this.transmission){const t=tx,s=Cy.sub(tx).normalize(),i=fx,r=e.context;r.backdrop=Iv(i,s,ap,np,wp,vp,t,Uy,Ay,Sy,Ep,Rp,Bp,Pp,this.dispersion?Ip:null),r.backdropAlpha=Cp,rp.a.mulAssign(Af(1,r.backdrop.a,Cp))}super.start(e)}computeMultiscattering(e,t,s,i,r=null){const n=mx.dot(rx).clamp(),o=rv({roughness:ap,dotNV:n}),a=r?pp.mix(i,r):i,l=a.mul(o.x).add(s.mul(o.y)),h=o.x.add(o.y).oneMinus(),u=a.add(a.oneMinus().mul(.047619)),c=l.mul(u).div(h.mul(u).oneMinus());e.addAssign(l),t.addAssign(c.mul(h))}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=mx.dot(e).clamp().mul(t).toVar();if(!0===this.sheen){this.sheenSpecularDirect.addAssign(i.mul(uv({lightDirection:e})));const t=Ov({normal:mx,viewDir:rx,roughness:dp}),s=Ov({normal:mx,viewDir:e,roughness:dp}),r=cp.r.max(cp.g).max(cp.b).mul(t.max(s)).oneMinus();i.mulAssign(r)}if(!0===this.clearcoat){const s=gx.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(s.mul(tv({lightDirection:e,f0:Vv,f90:zv,roughness:up,normalView:gx})))}s.directDiffuse.addAssign(i.mul(kw({diffuseColor:np}))),s.directSpecular.addAssign(i.mul(nv({lightDirection:e,f0:wp,f90:1,roughness:ap,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:s,halfHeight:i,reflectedLight:r,ltc_1:n,ltc_2:o}){const a=t.add(s).sub(i),l=t.sub(s).sub(i),h=t.sub(s).add(i),u=t.add(s).add(i),c=mx,d=rx,p=ix.toVar(),m=cv({N:c,V:d,roughness:ap}),f=n.sample(m).toVar(),g=o.sample(m).toVar(),y=Qd(Gd(f.x,0,f.y),Gd(0,1,0),Gd(f.z,0,f.w)).toVar(),x=wp.mul(g.x).add(wp.oneMinus().mul(g.y)).toVar();r.directSpecular.addAssign(e.mul(x).mul(mv({N:c,V:d,P:p,mInv:y,p0:a,p1:l,p2:h,p3:u}))),r.directDiffuse.addAssign(e.mul(np).mul(mv({N:c,V:d,P:p,mInv:Qd(1,0,0,0,1,0,0,0,1),p0:a,p1:l,p2:h,p3:u})))}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:s}=e.context,i=t.mul(kw({diffuseColor:np})).toVar();if(!0===this.sheen){const e=Ov({normal:mx,viewDir:rx,roughness:dp}),t=cp.r.max(cp.g).max(cp.b).mul(e).oneMinus();i.mulAssign(t)}s.indirectDiffuse.addAssign(i)}indirectSpecular(e){const{radiance:t,iblIrradiance:s,reflectedLight:i}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(s.mul(cp,Ov({normal:mx,viewDir:rx,roughness:dp}))),!0===this.clearcoat){const e=gx.dot(rx).clamp(),t=ov({dotNV:e,specularColor:Vv,specularF90:zv,roughness:up});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const r=Gd().toVar("singleScatteringDielectric"),n=Gd().toVar("multiScatteringDielectric"),o=Gd().toVar("singleScatteringMetallic"),a=Gd().toVar("multiScatteringMetallic");this.computeMultiscattering(r,n,vp,_p,this.iridescenceF0Dielectric),this.computeMultiscattering(o,a,vp,rp.rgb,this.iridescenceF0Metallic);const l=Af(r,o,lp),h=Af(n,a,lp),u=r.add(n),c=np.mul(u.oneMinus()),d=s.mul(1/Math.PI),p=t.mul(l).add(h.mul(d)).toVar(),m=c.mul(d).toVar();if(!0===this.sheen){const e=Ov({normal:mx,viewDir:rx,roughness:dp}),t=cp.r.max(cp.g).max(cp.b).mul(e).oneMinus();p.mulAssign(t),m.mulAssign(t)}i.indirectSpecular.addAssign(p),i.indirectDiffuse.addAssign(m)}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:s}=e.context,i=mx.dot(rx).clamp().add(t),r=ap.mul(-16).oneMinus().negate().exp2(),n=t.sub(i.pow(r).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(t),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(t),s.indirectDiffuse.mulAssign(t),s.indirectSpecular.mulAssign(n)}finish({context:e}){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=gx.dot(rx).clamp(),s=zw({dotVH:e,f0:Vv,f90:zv}),i=t.mul(hp.mul(s).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(hp));t.assign(i)}if(!0===this.sheen){const e=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect.mul(1/Math.PI));t.assign(e)}}}const Uv=Dd(1),Gv=Dd(-2),jv=Dd(.8),$v=Dd(-1),Wv=Dd(.4),Hv=Dd(2),qv=Dd(.305),Xv=Dd(3),Yv=Dd(.21),Zv=Dd(4),Qv=Dd(4),Kv=Dd(16),Jv=Ed(([e])=>{const t=Gd(Ym(e)).toVar(),s=Dd(-1).toVar();return Pd(t.x.greaterThan(t.z),()=>{Pd(t.x.greaterThan(t.y),()=>{s.assign(kf(e.x.greaterThan(0),0,3))}).Else(()=>{s.assign(kf(e.y.greaterThan(0),1,4))})}).Else(()=>{Pd(t.z.greaterThan(t.y),()=>{s.assign(kf(e.z.greaterThan(0),2,5))}).Else(()=>{s.assign(kf(e.y.greaterThan(0),1,4))})}),s}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),eT=Ed(([e,t])=>{const s=Vd().toVar();return Pd(t.equal(0),()=>{s.assign(Vd(e.z,e.y).div(Ym(e.x)))}).ElseIf(t.equal(1),()=>{s.assign(Vd(e.x.negate(),e.z.negate()).div(Ym(e.y)))}).ElseIf(t.equal(2),()=>{s.assign(Vd(e.x.negate(),e.y).div(Ym(e.z)))}).ElseIf(t.equal(3),()=>{s.assign(Vd(e.z.negate(),e.y).div(Ym(e.x)))}).ElseIf(t.equal(4),()=>{s.assign(Vd(e.x.negate(),e.z).div(Ym(e.y)))}).Else(()=>{s.assign(Vd(e.x,e.y).div(Ym(e.z)))}),Kp(.5,s.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),tT=Ed(([e])=>{const t=Dd(0).toVar();return Pd(e.greaterThanEqual(jv),()=>{t.assign(Uv.sub(e).mul($v.sub(Gv)).div(Uv.sub(jv)).add(Gv))}).ElseIf(e.greaterThanEqual(Wv),()=>{t.assign(jv.sub(e).mul(Hv.sub($v)).div(jv.sub(Wv)).add($v))}).ElseIf(e.greaterThanEqual(qv),()=>{t.assign(Wv.sub(e).mul(Xv.sub(Hv)).div(Wv.sub(qv)).add(Hv))}).ElseIf(e.greaterThanEqual(Yv),()=>{t.assign(qv.sub(e).mul(Zv.sub(Xv)).div(qv.sub(Yv)).add(Xv))}).Else(()=>{t.assign(Dd(-2).mul(Fm(Kp(1.16,e))))}),t}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),sT=Ed(([e,t])=>{const s=e.toVar();s.assign(Kp(2,s).sub(1));const i=Gd(s,1).toVar();return Pd(t.equal(0),()=>{i.assign(i.zyx)}).ElseIf(t.equal(1),()=>{i.assign(i.xzy),i.xz.mulAssign(-1)}).ElseIf(t.equal(2),()=>{i.x.mulAssign(-1)}).ElseIf(t.equal(3),()=>{i.assign(i.zyx),i.xz.mulAssign(-1)}).ElseIf(t.equal(4),()=>{i.assign(i.xzy),i.xy.mulAssign(-1)}).ElseIf(t.equal(5),()=>{i.z.mulAssign(-1)}),i}).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),iT=Ed(([e,t,s,i,r,n])=>{const o=Dd(s),a=Gd(t),l=Nf(tT(o),Gv,n),h=Gm(l),u=zm(l),c=Gd(rT(e,a,u,i,r,n)).toVar();return Pd(h.notEqual(0),()=>{const t=Gd(rT(e,a,u.add(1),i,r,n)).toVar();c.assign(Af(c,t,h))}),c}),rT=Ed(([e,t,s,i,r,n])=>{const o=Dd(s).toVar(),a=Gd(t),l=Dd(Jv(a)).toVar(),h=Dd(df(Qv.sub(o),0)).toVar();o.assign(df(o,Qv));const u=Dd(Dm(o)).toVar(),c=Vd(eT(a,l).mul(u.sub(2)).add(1)).toVar();return Pd(l.greaterThan(2),()=>{c.y.addAssign(u),l.subAssign(3)}),c.x.addAssign(l.mul(u)),c.x.addAssign(h.mul(Kp(3,Kv))),c.y.addAssign(Kp(4,Dm(n).sub(u))),c.x.mulAssign(i),c.y.mulAssign(r),e.sample(c).grad(Vd(),Vd())}),nT=Ed(({envMap:e,mipInt:t,outputDirection:s,theta:i,axis:r,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:a})=>{const l=$m(i),h=s.mul(l).add(r.cross(s).mul(jm(i))).add(r.mul(r.dot(s).mul(l.oneMinus())));return rT(e,h,t,n,o,a)}),oT=Ed(({n:e,latitudinal:t,poleAxis:s,outputDirection:i,weights:r,samples:n,dTheta:o,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c})=>{const d=Gd(kf(t,s,xf(s,i))).toVar();Pd(d.equal(Gd(0)),()=>{d.assign(Gd(i.z,0,i.x.negate()))}),d.assign(Um(d));const p=Gd().toVar();return p.addAssign(r.element(0).mul(nT({theta:0,axis:d,outputDirection:i,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c}))),C_({start:Ld(1),end:e},({i:e})=>{Pd(e.greaterThanEqual(n),()=>{R_()});const t=Dd(o.mul(Dd(e))).toVar();p.addAssign(r.element(e).mul(nT({theta:t.mul(-1),axis:d,outputDirection:i,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c}))),p.addAssign(r.element(e).mul(nT({theta:t,axis:d,outputDirection:i,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c})))}),Hd(p,1)}),aT=Ed(([e])=>{const t=Fd(e).toVar();return t.assign(t.shiftLeft(Fd(16)).bitOr(t.shiftRight(Fd(16)))),t.assign(t.bitAnd(Fd(1431655765)).shiftLeft(Fd(1)).bitOr(t.bitAnd(Fd(2863311530)).shiftRight(Fd(1)))),t.assign(t.bitAnd(Fd(858993459)).shiftLeft(Fd(2)).bitOr(t.bitAnd(Fd(3435973836)).shiftRight(Fd(2)))),t.assign(t.bitAnd(Fd(252645135)).shiftLeft(Fd(4)).bitOr(t.bitAnd(Fd(4042322160)).shiftRight(Fd(4)))),t.assign(t.bitAnd(Fd(16711935)).shiftLeft(Fd(8)).bitOr(t.bitAnd(Fd(4278255360)).shiftRight(Fd(8)))),Dd(t).mul(2.3283064365386963e-10)}),lT=Ed(([e,t])=>Vd(Dd(e).div(Dd(t)),aT(e))),hT=Ed(([e,t,s])=>{const i=Gd(t).toVar(),r=Dd(s),n=r.mul(r).toVar(),o=Um(Gd(n.mul(i.x),n.mul(i.y),i.z)).toVar(),a=o.x.mul(o.x).add(o.y.mul(o.y)),l=kf(a.greaterThan(0),Gd(o.y.negate(),o.x,0).div(Om(a)),Gd(1,0,0)).toVar(),h=xf(o,l).toVar(),u=Om(e.x),c=Kp(2,3.14159265359).mul(e.y),d=u.mul($m(c)).toVar(),p=u.mul(jm(c)).toVar(),m=Kp(.5,o.z.add(1));p.assign(m.oneMinus().mul(Om(d.mul(d).oneMinus())).add(m.mul(p)));const f=l.mul(d).add(h.mul(p)).add(o.mul(Om(df(0,d.mul(d).add(p.mul(p)).oneMinus()))));return Um(Gd(n.mul(f.x),n.mul(f.y),df(0,f.z)))}),uT=Ed(({roughness:e,mipInt:t,envMap:s,N_immutable:i,GGX_SAMPLES:r,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:a})=>{const l=Gd(i).toVar(),h=Gd(0).toVar(),u=Dd(0).toVar();return Pd(e.lessThan(.001),()=>{h.assign(rT(s,l,t,n,o,a))}).Else(()=>{const i=kf(Ym(l.z).lessThan(.999),Gd(0,0,1),Gd(1,0,0)),c=Um(xf(i,l)).toVar(),d=xf(l,c).toVar();C_({start:Fd(0),end:r},({i:i})=>{const p=lT(i,r),m=hT(p,Gd(0,0,1),e),f=Um(c.mul(m.x).add(d.mul(m.y)).add(l.mul(m.z))),g=Um(f.mul(yf(l,f).mul(2)).sub(l)),y=df(yf(l,g),0);Pd(y.greaterThan(0),()=>{const e=rT(s,g,t,n,o,a);h.addAssign(e.mul(y)),u.addAssign(y)})}),Pd(u.greaterThan(0),()=>{h.assign(h.div(u))})}),Hd(h,1)}),cT=[.125,.215,.35,.446,.526,.582],dT=20,pT=new $u(-1,1,1,-1,0,1),mT=new Wh(90,1),fT=new eh;let gT=null,yT=0,xT=0;const bT=new da,_T=new WeakMap,wT=[3,1,5,0,4,2],vT=sT(qg(),Hg("faceIndex")).normalize(),TT=Gd(vT.x,vT.y,vT.z);class ST{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._ggxMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,s=.1,i=100,r={}){const{size:n=256,position:o=bT,renderTarget:a=null}=r;if(this._setSize(n),!1===this._hasInitialized){Yo('PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.');const n=a||this._allocateTarget();return r.renderTarget=n,this.fromSceneAsync(e,t,s,i,r),n}gT=this._renderer.getRenderTarget(),yT=this._renderer.getActiveCubeFace(),xT=this._renderer.getActiveMipmapLevel();const l=a||this._allocateTarget();return l.depthBuffer=!0,this._init(l),this._sceneToCubeUV(e,s,i,l,o),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}async fromSceneAsync(e,t=0,s=.1,i=100,r={}){return Qo('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,s,i,r)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){Yo('PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.'),this._setSizeFromTexture(e);const s=t||this._allocateTarget();return this.fromEquirectangularAsync(e,s),s}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return Qo('PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._hasInitialized){Yo("PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const s=t||this._allocateTarget();return this.fromCubemapAsync(e,t),s}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return Qo('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=ET(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=CT(),await this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose(),null!==this._backgroundBox&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSizeFromTexture(e){e.mapping===un||e.mapping===cn?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._ggxMaterial&&this._ggxMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(gT,yT,xT),e.scissorTest=!1,AT(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),gT=this._renderer.getRenderTarget(),yT=this._renderer.getActiveCubeFace(),xT=this._renderer.getActiveMipmapLevel();const s=t||this._allocateTarget();return this._init(s),this._textureToCubeUV(e,s),this._applyPMREM(s),this._cleanup(s),s}_allocateTarget(){return MT(3*Math.max(this._cubeSize,112),4*this._cubeSize)}_init(e){if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==e.width||this._pingPongRenderTarget.height!==e.height){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=MT(e.width,e.height);const{_lodMax:t}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=function(e){const t=[],s=[],i=[];let r=e;const n=e-4+1+cT.length;for(let o=0;o<n;o++){const n=Math.pow(2,r);t.push(n);let a=1/n;o>e-4?a=cT[o-e+4-1]:0===o&&(a=0),s.push(a);const l=1/(n-2),h=-l,u=1+l,c=[h,h,u,h,u,u,h,h,u,u,h,u],d=6,p=6,m=3,f=2,g=1,y=new Float32Array(m*p*d),x=new Float32Array(f*p*d),b=new Float32Array(g*p*d);for(let e=0;e<d;e++){const t=e%3*2/3-1,s=e>2?0:-1,i=[t,s,0,t+2/3,s,0,t+2/3,s+1,0,t,s,0,t+2/3,s+1,0,t,s+1,0],r=wT[e];y.set(i,m*p*r),x.set(c,f*p*r);const n=[r,r,r,r,r,r];b.set(n,g*p*r)}const _=new Sh;_.setAttribute("position",new dh(y,m)),_.setAttribute("uv",new dh(x,f)),_.setAttribute("faceIndex",new dh(b,g)),i.push(new Fh(_,null)),r>4&&r--}return{lodMeshes:i,sizeLods:t,sigmas:s}}(t)),this._blurMaterial=function(e,t,s){const i=ay(new Array(dT).fill(0)),r=Up(new da(0,1,0)),n=Up(0),o=Dd(dT),a=Up(0),l=Up(1),h=ty(),u=Up(0),c=Dd(1/t),d=Dd(1/s),p=Dd(e),m={n:o,latitudinal:a,weights:i,poleAxis:r,outputDirection:TT,dTheta:n,samples:l,envMap:h,mipInt:u,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},f=NT("blur");return f.fragmentNode=oT({...m,latitudinal:a.equal(1)}),_T.set(f,m),f}(t,e.width,e.height),this._ggxMaterial=function(e,t,s){const i=ty(),r=Up(0),n=Up(0),o=Dd(1/t),a=Dd(1/s),l=Dd(e),h={envMap:i,roughness:r,mipInt:n,CUBEUV_TEXEL_WIDTH:o,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:l},u=NT("ggx");return u.fragmentNode=uT({...h,N_immutable:TT,GGX_SAMPLES:Fd(512)}),_T.set(u,h),u}(t,e.width,e.height)}}async _compileMaterial(e){const t=new Fh(new Sh,e);await this._renderer.compile(t,pT)}_sceneToCubeUV(e,t,s,i,r){const n=mT;n.near=t,n.far=s;const o=[1,1,1,1,-1,1],a=[1,-1,1,-1,1,-1],l=this._renderer,h=l.autoClear;l.getClearColor(fT),l.autoClear=!1,null===this._backgroundBox&&(this._backgroundBox=new Fh(new Vh,new rh({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1})));const u=this._backgroundBox,c=u.material;let d=!1;const p=e.background;p?p.isColor&&(c.color.copy(p),e.background=null,d=!0):(c.color.copy(fT),d=!0),l.setRenderTarget(i),l.clear(),d&&l.render(u,n);for(let t=0;t<6;t++){const s=t%3;0===s?(n.up.set(0,o[t],0),n.position.set(r.x,r.y,r.z),n.lookAt(r.x+a[t],r.y,r.z)):1===s?(n.up.set(0,0,o[t]),n.position.set(r.x,r.y,r.z),n.lookAt(r.x,r.y+a[t],r.z)):(n.up.set(0,o[t],0),n.position.set(r.x,r.y,r.z),n.lookAt(r.x,r.y,r.z+a[t]));const h=this._cubeSize;AT(i,s*h,t>2?h:0,h,h),l.render(e,n)}l.autoClear=h,e.background=p}_textureToCubeUV(e,t){const s=this._renderer,i=e.mapping===un||e.mapping===cn;i?null===this._cubemapMaterial&&(this._cubemapMaterial=ET(e)):null===this._equirectMaterial&&(this._equirectMaterial=CT(e));const r=i?this._cubemapMaterial:this._equirectMaterial;r.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=r;const o=this._cubeSize;AT(t,0,0,3*o,2*o),s.setRenderTarget(t),s.render(n,pT)}_applyPMREM(e){const t=this._renderer,s=t.autoClear;t.autoClear=!1;const i=this._lodMeshes.length;for(let t=1;t<i;t++)this._applyGGXFilter(e,t-1,t);t.autoClear=s}_applyGGXFilter(e,t,s){const i=this._renderer,r=this._pingPongRenderTarget,n=this._ggxMaterial,o=this._lodMeshes[s];o.material=n;const a=_T.get(n),l=s/(this._lodMeshes.length-1),h=t/(this._lodMeshes.length-1),u=Math.sqrt(l*l-h*h)*(0+1.25*l),{_lodMax:c}=this,d=this._sizeLods[s],p=3*d*(s>c-4?s-c+4:0),m=4*(this._cubeSize-d);e.texture.frame=(e.texture.frame||0)+1,a.envMap.value=e.texture,a.roughness.value=u,a.mipInt.value=c-t,AT(r,p,m,3*d,2*d),i.setRenderTarget(r),i.render(o,pT),r.texture.frame=(r.texture.frame||0)+1,a.envMap.value=r.texture,a.roughness.value=0,a.mipInt.value=c-s,AT(e,p,m,3*d,2*d),i.setRenderTarget(e),i.render(o,pT)}_blur(e,t,s,i,r){const n=this._pingPongRenderTarget;this._halfBlur(e,n,t,s,i,"latitudinal",r),this._halfBlur(n,e,s,s,i,"longitudinal",r)}_halfBlur(e,t,s,i,r,n,o){const a=this._renderer,l=this._blurMaterial;"latitudinal"!==n&&"longitudinal"!==n&&Zo("blur direction must be either latitudinal or longitudinal!");const h=this._lodMeshes[i];h.material=l;const u=_T.get(l),c=this._sizeLods[s]-1,d=isFinite(r)?Math.PI/(2*c):2*Math.PI/39,p=r/d,m=isFinite(r)?1+Math.floor(3*p):dT;m>dT&&Yo(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);const f=[];let g=0;for(let e=0;e<dT;++e){const t=e/p,s=Math.exp(-t*t/2);f.push(s),0===e?g+=s:e<m&&(g+=2*s)}for(let e=0;e<f.length;e++)f[e]=f[e]/g;e.texture.frame=(e.texture.frame||0)+1,u.envMap.value=e.texture,u.samples.value=m,u.weights.array=f,u.latitudinal.value="latitudinal"===n?1:0,o&&(u.poleAxis.value=o);const{_lodMax:y}=this;u.dTheta.value=d,u.mipInt.value=y-s;const x=this._sizeLods[i];AT(t,3*x*(i>y-4?i-y+4:0),4*(this._cubeSize-x),3*x,2*x),a.setRenderTarget(t),a.render(h,pT)}}function MT(e,t){const s=new Ba(e,t,{magFilter:xn,minFilter:xn,generateMipmaps:!1,type:En,format:Ln,colorSpace:Ao});return s.texture.mapping=306,s.texture.name="PMREM.cubeUv",s.texture.isPMREMTexture=!0,s.scissorTest=!0,s}function AT(e,t,s,i,r){e.viewport.set(t,s,i,r),e.scissor.set(t,s,i,r)}function NT(e){const t=new gw;return t.depthTest=!1,t.depthWrite=!1,t.blending=0,t.name=`PMREM_${e}`,t}function ET(e){const t=NT("cubemap");return t.fragmentNode=Dx(e,TT),t}function CT(e){const t=NT("equirect");return t.fragmentNode=ty(e,Aw(TT),0),t}const RT=new WeakMap;function PT(e,t,s){const i=function(e){let t=RT.get(e);void 0===t&&(t=new WeakMap,RT.set(e,t));return t}(t);let r=i.get(e);if((void 0!==r?r.pmremVersion:-1)!==e.pmremVersion){const t=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const s=6;for(let i=0;i<s;i++)void 0!==e[i]&&t++;return t===s}(t))return null;r=s.fromCubemap(e,r)}else{if(!function(e){return null!=e&&e.height>0}(t))return null;r=s.fromEquirectangular(e,r)}r.pmremVersion=e.pmremVersion,i.set(e,r)}return r.texture}class BT extends Bc{static get type(){return"PMREMNode"}constructor(e,t=null,s=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=s,this._generator=null;const i=new Ra;i.isRenderTargetTexture=!0,this._texture=ty(i),this._width=Up(0),this._height=Up(0),this._maxMip=Up(0),this.updateBeforeType=wc.RENDER}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){const t=function(e){const t=Math.log2(e)-2,s=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:s,maxMip:t}}(e.image.height);this._texture.value=e,this._width.value=t.texelWidth,this._height.value=t.texelHeight,this._maxMip.value=t.maxMip}updateBefore(e){let t=this._pmrem;const s=t?t.pmremVersion:-1,i=this._value;s!==i.pmremVersion&&(t=!0===i.isPMREMTexture?i:PT(i,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new ST(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this,e)),t=Ax.mul(Gd(t.x,t.y.negate(),t.z));let s=this.levelNode;return null===s&&e.context.getTextureLevel&&(s=e.context.getTextureLevel(this)),iT(this._texture,t,s,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const IT=Td(BT).setParameterLength(1,3),DT=new WeakMap;class LT extends F_{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let s=this.envNode;if(s.isTextureNode||s.isMaterialReferenceNode){const e=s.isTextureNode?s.value:t[s.property];let i=DT.get(e);void 0===i&&(i=IT(e),DT.set(e,i)),s=i}const i=!0===t.useAnisotropy||t.anisotropy>0?db:mx,r=s.context(FT(ap,i)).mul(Mx),n=s.context(OT(fx)).mul(Math.PI).mul(Mx),o=Eg(r),a=Eg(n);e.context.radiance.addAssign(o),e.context.iblIrradiance.addAssign(a);const l=e.context.lightingModel.clearcoatRadiance;if(l){const e=s.context(FT(up,gx)).mul(Mx),t=Eg(e);l.addAssign(t)}}}const FT=(e,t)=>{let s=null;return{getUV:()=>(null===s&&(s=rx.negate().reflect(t),s=vf(e).mix(s,t).normalize(),s=s.transformDirection(Ay)),s),getTextureLevel:()=>e}},OT=e=>({getUV:()=>e,getTextureLevel:()=>Dd(1)}),VT=new Au;class zT extends gw{static get type(){return"MeshStandardNodeMaterial"}constructor(e){super(),this.isMeshStandardNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.metalnessNode=null,this.roughnessNode=null,this.setDefaultValues(VT),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new LT(t):null}setupLightingModel(){return new kv}setupSpecular(){const e=Af(Gd(.04),rp.rgb,lp);_p.assign(Gd(.04)),wp.assign(e),vp.assign(1)}setupVariants(){const e=this.metalnessNode?Dd(this.metalnessNode):Db;lp.assign(e);let t=this.roughnessNode?Dd(this.roughnessNode):Ib;t=Yw({roughness:t}),ap.assign(t),this.setupSpecular(),np.assign(rp.rgb.mul(e.oneMinus()))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const kT=new Nu;class UT extends zT{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.anisotropyNode=null,this.setDefaultValues(kT),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||null!==this.clearcoatNode}get useIridescence(){return this.iridescence>0||null!==this.iridescenceNode}get useSheen(){return this.sheen>0||null!==this.sheenNode}get useAnisotropy(){return this.anisotropy>0||null!==this.anisotropyNode}get useTransmission(){return this.transmission>0||null!==this.transmissionNode}get useDispersion(){return this.dispersion>0||null!==this.dispersionNode}setupSpecular(){const e=this.iorNode?Dd(this.iorNode):Xb;Ep.assign(e),_p.assign(cf(_f(Ep.sub(1).div(Ep.add(1))).mul(Rb),Gd(1)).mul(Cb)),wp.assign(Af(_p,rp.rgb,lp)),vp.assign(Af(Cb,1,lp))}setupLightingModel(){return new kv(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?Dd(this.clearcoatNode):Fb,t=this.clearcoatRoughnessNode?Dd(this.clearcoatRoughnessNode):Ob;hp.assign(e),up.assign(Yw({roughness:t}))}if(this.useSheen){const e=this.sheenNode?Gd(this.sheenNode):kb,t=this.sheenRoughnessNode?Dd(this.sheenRoughnessNode):Ub;cp.assign(e),dp.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?Dd(this.iridescenceNode):jb,t=this.iridescenceIORNode?Dd(this.iridescenceIORNode):$b,s=this.iridescenceThicknessNode?Dd(this.iridescenceThicknessNode):Wb;pp.assign(e),mp.assign(t),fp.assign(s)}if(this.useAnisotropy){const e=(this.anisotropyNode?Vd(this.anisotropyNode):Gb).toVar();yp.assign(e.length()),Pd(yp.equal(0),()=>{e.assign(Vd(1,0))}).Else(()=>{e.divAssign(Vd(yp)),yp.assign(yp.saturate())}),gp.assign(yp.pow2().mix(ap.pow2(),1)),xp.assign(ub[0].mul(e.x).add(ub[1].mul(e.y))),bp.assign(ub[1].mul(e.x).sub(ub[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?Dd(this.transmissionNode):Hb,t=this.thicknessNode?Dd(this.thicknessNode):qb,s=this.attenuationDistanceNode?Dd(this.attenuationDistanceNode):Yb,i=this.attenuationColorNode?Gd(this.attenuationColorNode):Zb;if(Cp.assign(e),Rp.assign(t),Pp.assign(s),Bp.assign(i),this.useDispersion){const e=this.dispersionNode?Dd(this.dispersionNode):i_;Ip.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?Gd(this.clearcoatNormalNode):Vb}setup(e){e.context.setupClearcoatNormal=()=>eg(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}copy(e){return this.clearcoatNode=e.clearcoatNode,this.clearcoatRoughnessNode=e.clearcoatRoughnessNode,this.clearcoatNormalNode=e.clearcoatNormalNode,this.sheenNode=e.sheenNode,this.sheenRoughnessNode=e.sheenRoughnessNode,this.iridescenceNode=e.iridescenceNode,this.iridescenceIORNode=e.iridescenceIORNode,this.iridescenceThicknessNode=e.iridescenceThicknessNode,this.specularIntensityNode=e.specularIntensityNode,this.specularColorNode=e.specularColorNode,this.transmissionNode=e.transmissionNode,this.thicknessNode=e.thicknessNode,this.attenuationDistanceNode=e.attenuationDistanceNode,this.attenuationColorNode=e.attenuationColorNode,this.dispersionNode=e.dispersionNode,this.anisotropyNode=e.anisotropyNode,super.copy(e)}}const GT=Ed(({normal:e,lightDirection:t,builder:s})=>{const i=e.dot(t),r=Vd(i.mul(.5).add(.5),0);if(s.material.gradientMap){const e=kx("gradientMap","texture").context({getUV:()=>r});return Gd(e.r)}{const e=r.fwidth().mul(.5);return Af(Gd(.7),Gd(1),Rf(Dd(.7).sub(e.x),Dd(.7).add(e.x),r.x))}});class jT extends Lw{direct({lightDirection:e,lightColor:t,reflectedLight:s},i){const r=GT({normal:hx,lightDirection:e,builder:i}).mul(t);s.directDiffuse.addAssign(r.mul(kw({diffuseColor:rp.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(kw({diffuseColor:rp}))),i.indirectDiffuse.mulAssign(t)}}const $T=new Cu;class WT extends gw{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues($T),this.setValues(e)}setupLightingModel(){return new jT}}const HT=Ed(()=>{const e=Gd(rx.z,0,rx.x.negate()).normalize(),t=rx.cross(e);return Vd(e.dot(mx),t.dot(mx)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),qT=new Bu;class XT extends gw{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(qT),this.setValues(e)}setupVariants(e){const t=HT;let s;s=e.material.matcap?kx("matcap","texture").context({getUV:()=>t}):Gd(Af(.2,.8,t.y)),rp.rgb.mulAssign(s.rgb)}}class YT extends Bc{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}getNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:s}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),i=t.sin();return Zd(e,i,i.negate(),e).mul(s)}{const e=t,i=Kd(Hd(1,0,0,0),Hd(0,$m(e.x),jm(e.x).negate(),0),Hd(0,jm(e.x),$m(e.x),0),Hd(0,0,0,1)),r=Kd(Hd($m(e.y),0,jm(e.y),0),Hd(0,1,0,0),Hd(jm(e.y).negate(),0,$m(e.y),0),Hd(0,0,0,1)),n=Kd(Hd($m(e.z),jm(e.z).negate(),0,0),Hd(jm(e.z),$m(e.z),0,0),Hd(0,0,1,0),Hd(0,0,0,1));return i.mul(r).mul(n).mul(Hd(s,1)).xyz}}}const ZT=Td(YT).setParameterLength(2),QT=new iu;class KT extends gw{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(QT),this.setValues(e)}setupPositionView(e){const{object:t,camera:s}=e,{positionNode:i,rotationNode:r,scaleNode:n,sizeAttenuation:o}=this,a=Xy.mul(Gd(i||0));let l=Vd(Uy[0].xyz.length(),Uy[1].xyz.length());null!==n&&(l=l.mul(Vd(n))),s.isPerspectiveCamera&&!1===o&&(l=l.mul(a.z.negate()));let h=Ky.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,s)=>new cg(e,t,s))("center","vec2",t);h=h.sub(e.sub(.5))}h=h.mul(l);const u=Dd(r||zb),c=ZT(h,u);return Hd(a.xy.add(c),a.zw)}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const JT=new xu,eS=new ua;class tS extends KT{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(JT),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return Xy.mul(Gd(e||Jy)).xyz}setupVertexSprite(e){const{material:t,camera:s}=e,{rotationNode:i,scaleNode:r,sizeNode:n,sizeAttenuation:o}=this;let a=super.setupVertex(e);if(!0!==t.isNodeMaterial)return a;let l=null!==n?Vd(n):s_;l=l.mul(dy),s.isPerspectiveCamera&&!0===o&&(l=l.mul(sS.div(ix.z.negate()))),r&&r.isNode&&(l=l.mul(Vd(r)));let h=Ky.xy;if(i&&i.isNode){const e=Dd(i);h=ZT(h,e)}return h=h.mul(l),h=h.div(yy.div(2)),h=h.mul(a.w),a=a.add(Hd(h,0,0)),a}setupVertex(e){return e.object.isPoints?super.setupVertex(e):this.setupVertexSprite(e)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}const sS=Up(1).onFrameUpdate(function({renderer:e}){const t=e.getSize(eS);this.value=.5*t.y});class iS extends Lw{constructor(){super(),this.shadowNode=Dd(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){rp.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(rp.rgb)}}const rS=new Mu;class nS extends gw{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(rS),this.setValues(e)}setupLightingModel(){return new iS}}sp("vec3"),sp("vec3"),sp("vec3");class oS{constructor(e,t,s){this.renderer=e,this.nodes=t,this.info=s,this._context="undefined"!=typeof self?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,s)=>{this._requestId=this._context.requestAnimationFrame(e),!0===this.info.autoReset&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,this.renderer._inspector.begin(),null!==this._animationLoop&&this._animationLoop(t,s),this.renderer._inspector.finish()};e()}stop(){this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class aS{constructor(){this.weakMaps={}}_getWeakMap(e){const t=e.length;let s=this.weakMaps[t];return void 0===s&&(s=new WeakMap,this.weakMaps[t]=s),s}get(e){let t=this._getWeakMap(e);for(let s=0;s<e.length-1;s++)if(t=t.get(e[s]),void 0===t)return;return t.get(e[e.length-1])}set(e,t){let s=this._getWeakMap(e);for(let t=0;t<e.length-1;t++){const i=e[t];!1===s.has(i)&&s.set(i,new WeakMap),s=s.get(i)}return s.set(e[e.length-1],t),this}delete(e){let t=this._getWeakMap(e);for(let s=0;s<e.length-1;s++)if(t=t.get(e[s]),void 0===t)return!1;return t.delete(e[e.length-1])}}let lS=0;class hS{constructor(e,t,s,i,r,n,o,a,l,h){this.id=lS++,this._nodes=e,this._geometries=t,this.renderer=s,this.object=i,this.material=r,this.scene=n,this.camera=o,this.lightsNode=a,this.context=l,this.geometry=i.geometry,this.version=r.version,this.drawRange=null,this.attributes=null,this.attributesId=null,this.pipeline=null,this.group=null,this.vertexBuffers=null,this.drawParams=null,this.bundle=null,this.clippingContext=h,this.clippingContextCacheKey=null!==h?h.cacheKey:"",this.initialNodesCacheKey=this.getDynamicCacheKey(),this.initialCacheKey=this.getCacheKey(),this._nodeBuilderState=null,this._bindings=null,this._monitor=null,this.onDispose=null,this.isRenderObject=!0,this.onMaterialDispose=()=>{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return null!==this.clippingContext&&this.clippingContext.cacheKey!==this.clippingContextCacheKey&&(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return!0===this.material.hardwareClipping?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getIndirectOffset(){return this._geometries.getIndirectOffset(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null,this.attributesId=null}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,s=[],i=new Set,r={};for(const n of e){let e;if(n.node&&n.node.attribute?e=n.node.attribute:(e=t.getAttribute(n.name),r[n.name]=e.version),void 0===e)continue;s.push(e);const o=e.isInterleavedBufferAttribute?e.data:e;i.add(o)}return this.attributes=s,this.attributesId=r,this.vertexBuffers=Array.from(i.values()),s}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:s,group:i,drawRange:r}=this,n=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),o=this.getIndex(),a=null!==o;let l=1;if(!0===s.isInstancedBufferGeometry?l=s.instanceCount:void 0!==e.count&&(l=Math.max(0,e.count)),0===l)return null;if(n.instanceCount=l,!0===e.isBatchedMesh)return n;let h=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(h=2);let u=r.start*h,c=(r.start+r.count)*h;null!==i&&(u=Math.max(u,i.start*h),c=Math.min(c,(i.start+i.count)*h));const d=s.attributes.position;let p=1/0;a?p=o.count:null!=d&&(p=d.count),u=Math.max(u,0),c=Math.min(c,p);const m=c-u;return m<0||m===1/0?null:(n.vertexCount=m,n.firstVertex=u,n)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const s of Object.keys(e.attributes).sort()){const i=e.attributes[s];t+=s+",",i.data&&(t+=i.data.stride+","),i.offset&&(t+=i.offset+","),i.itemSize&&(t+=i.itemSize+","),i.normalized&&(t+="n,")}for(const s of Object.keys(e.morphAttributes).sort()){const i=e.morphAttributes[s];t+="morph-"+s+",";for(let e=0,s=i.length;e<s;e++){t+=i[e].id+","}}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t,renderer:s}=this;let i=t.customProgramCacheKey();for(const e of function(e){const t=Object.keys(e);let s=Object.getPrototypeOf(e);for(;s;){const e=Object.getOwnPropertyDescriptors(s);for(const s in e)if(void 0!==e[s]){const i=e[s];i&&"function"==typeof i.get&&t.push(s)}s=Object.getPrototypeOf(s)}return t}(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(e))continue;const r=t[e];let n;if(null!==r){const e=typeof r;"number"===e?n=0!==r?"1":"0":"object"===e?(n="{",r.isTexture&&(n+=r.mapping,!0===s.backend.isWebGPUBackend&&(n+=r.magFilter,n+=r.minFilter,n+=r.wrapS,n+=r.wrapT,n+=r.wrapR)),n+="}"):n=String(r)}else n=String(r);i+=n+","}return i+=this.clippingContextCacheKey+",",e.geometry&&(i+=this.getGeometryCacheKey()),e.skeleton&&(i+=e.skeleton.bones.length+","),e.isBatchedMesh&&(i+=e._matricesTexture.uuid+",",null!==e._colorsTexture&&(i+=e._colorsTexture.uuid+",")),(e.isInstancedMesh||e.count>1||Array.isArray(e.morphTargetInfluences))&&(i+=e.uuid+","),i+=this.context.id+",",i+=e.receiveShadow+",",nc(i)}get needsGeometryUpdate(){if(this.geometry.id!==this.object.geometry.id)return!0;if(null!==this.attributes){const e=this.attributesId;for(const t in e){const s=this.geometry.getAttribute(t);if(void 0===s||e[t]!==s.id)return!0}}return!1}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return!0!==this.material.isShadowPassMaterial&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=ac(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=ac(e,1)),e=ac(e,this.camera.id,this.renderer.contextNode.id,this.renderer.contextNode.version),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const uS=[];class cS{constructor(e,t,s,i,r,n){this.renderer=e,this.nodes=t,this.geometries=s,this.pipelines=i,this.bindings=r,this.info=n,this.chainMaps={}}get(e,t,s,i,r,n,o,a){const l=this.getChainMap(a);uS[0]=e,uS[1]=t,uS[2]=n,uS[3]=r;let h=l.get(uS);return void 0===h?(h=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,s,i,r,n,o,a),l.set(uS,h)):(h.updateClipping(o),h.needsGeometryUpdate&&h.setGeometry(e.geometry),(h.version!==t.version||h.needsUpdate)&&(h.initialCacheKey!==h.getCacheKey()?(h.dispose(),h=this.get(e,t,s,i,r,n,o,a)):h.version=t.version)),uS.length=0,h}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new aS)}dispose(){this.chainMaps={}}createRenderObject(e,t,s,i,r,n,o,a,l,h,u){const c=this.getChainMap(u),d=new hS(e,t,s,i,r,n,o,a,l,h);return d.onDispose=()=>{this.pipelines.delete(d),this.bindings.deleteForRender(d),this.nodes.delete(d),c.delete(d.getChainArray())},d}}class dS{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}delete(e){let t=null;return this.data.has(e)&&(t=this.data.get(e),this.data.delete(e)),t}has(e){return this.data.has(e)}dispose(){this.data=new WeakMap}}const pS=1,mS=2,fS=3,gS=4,yS=16;class xS extends dS{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return null!==t&&this.backend.destroyAttribute(e),t}update(e,t){const s=this.get(e);if(void 0===s.version)t===pS?this.backend.createAttribute(e):t===mS?this.backend.createIndexAttribute(e):t===fS?this.backend.createStorageAttribute(e):t===gS&&this.backend.createIndirectStorageAttribute(e),s.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(s.version<t.version||t.usage===zo)&&(this.backend.updateAttribute(e),s.version=t.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}function bS(e){return null!==e.index?e.index.version:e.attributes.position.version}function _S(e){const t=[],s=e.index,i=e.attributes.position;if(null!==s){const e=s.array;for(let s=0,i=e.length;s<i;s+=3){const i=e[s+0],r=e[s+1],n=e[s+2];t.push(i,r,r,n,n,i)}}else{for(let e=0,s=i.array.length/3-1;e<s;e+=3){const s=e+0,i=e+1,r=e+2;t.push(s,i,i,r,r,s)}}const r=new($o(t)?mh:ph)(t,1);return r.version=bS(e),r}class wS extends dS{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap,this._geometryDisposeListeners=new Map}has(e){const t=e.geometry;return super.has(t)&&!0===this.get(t).initialized}updateForRender(e){!1===this.has(e)&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry;this.get(t).initialized=!0,this.info.memory.geometries++;const s=()=>{this.info.memory.geometries--;const i=t.index,r=e.getAttributes();null!==i&&this.attributes.delete(i);for(const e of r)this.attributes.delete(e);const n=this.wireframes.get(t);void 0!==n&&this.attributes.delete(n),t.removeEventListener("dispose",s),this._geometryDisposeListeners.delete(t)};t.addEventListener("dispose",s),this._geometryDisposeListeners.set(t,s)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,fS):this.updateAttribute(e,pS);const s=this.getIndex(e);null!==s&&this.updateAttribute(s,mS);const i=e.geometry.indirect;null!==i&&this.updateAttribute(i,gS)}updateAttribute(e,t){const s=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,s)):this.attributeCall.get(e.data)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e.data,s),this.attributeCall.set(e,s)):this.attributeCall.get(e)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e,s))}getIndirect(e){return e.geometry.indirect}getIndirectOffset(e){return e.geometry.indirectOffset}getIndex(e){const{geometry:t,material:s}=e;let i=t.index;if(!0===s.wireframe){const e=this.wireframes;let s=e.get(t);void 0===s?(s=_S(t),e.set(t,s)):s.version!==bS(t)&&(this.attributes.delete(s),s=_S(t),e.set(t,s)),i=s}return i}dispose(){for(const[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener("dispose",t);this._geometryDisposeListeners.clear()}}class vS{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0}}update(e,t,s){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=s*(t/3):e.isPoints?this.render.points+=s*t:e.isLineSegments?this.render.lines+=s*(t/2):e.isLine?this.render.lines+=s*(t-1):Zo("WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0,this.memory.geometries=0,this.memory.textures=0}}class TS{constructor(e){this.cacheKey=e,this.usedTimes=0}}class SS extends TS{constructor(e,t,s){super(e),this.vertexProgram=t,this.fragmentProgram=s}}class MS extends TS{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let AS=0;class NS{constructor(e,t,s,i=null,r=null){this.id=AS++,this.code=e,this.stage=t,this.name=s,this.transforms=i,this.attributes=r,this.usedTimes=0}}class ES extends dS{constructor(e,t){super(),this.backend=e,this.nodes=t,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:s}=this,i=this.get(e);if(this._needsComputeUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.computeProgram.usedTimes--);const n=this.nodes.getForCompute(e);let o=this.programs.compute.get(n.computeShader);void 0===o&&(r&&0===r.computeProgram.usedTimes&&this._releaseProgram(r.computeProgram),o=new NS(n.computeShader,"compute",e.name,n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,o),s.createProgram(o));const a=this._getComputeCacheKey(e,o);let l=this.caches.get(a);void 0===l&&(r&&0===r.usedTimes&&this._releasePipeline(r),l=this._getComputePipeline(e,o,a,t)),l.usedTimes++,o.usedTimes++,i.version=e.version,i.pipeline=l}return i.pipeline}getForRender(e,t=null){const{backend:s}=this,i=this.get(e);if(this._needsRenderUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.vertexProgram.usedTimes--,r.fragmentProgram.usedTimes--);const n=e.getNodeBuilderState(),o=e.material?e.material.name:"";let a=this.programs.vertex.get(n.vertexShader);void 0===a&&(r&&0===r.vertexProgram.usedTimes&&this._releaseProgram(r.vertexProgram),a=new NS(n.vertexShader,"vertex",o),this.programs.vertex.set(n.vertexShader,a),s.createProgram(a));let l=this.programs.fragment.get(n.fragmentShader);void 0===l&&(r&&0===r.fragmentProgram.usedTimes&&this._releaseProgram(r.fragmentProgram),l=new NS(n.fragmentShader,"fragment",o),this.programs.fragment.set(n.fragmentShader,l),s.createProgram(l));const h=this._getRenderCacheKey(e,a,l);let u=this.caches.get(h);void 0===u?(r&&0===r.usedTimes&&this._releasePipeline(r),u=this._getRenderPipeline(e,a,l,h,t)):e.pipeline=u,u.usedTimes++,a.usedTimes++,l.usedTimes++,i.pipeline=u}return i.pipeline}delete(e){const t=this.get(e).pipeline;return t&&(t.usedTimes--,0===t.usedTimes&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,0===t.computeProgram.usedTimes&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,0===t.vertexProgram.usedTimes&&this._releaseProgram(t.vertexProgram),0===t.fragmentProgram.usedTimes&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,s,i){s=s||this._getComputeCacheKey(e,t);let r=this.caches.get(s);return void 0===r&&(r=new MS(s,t),this.caches.set(s,r),this.backend.createComputePipeline(r,i)),r}_getRenderPipeline(e,t,s,i,r){i=i||this._getRenderCacheKey(e,t,s);let n=this.caches.get(i);return void 0===n&&(n=new SS(i,t,s),this.caches.set(i,n),e.pipeline=n,this.backend.createRenderPipeline(e,r)),n}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,s){return t.id+","+s.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,s=e.stage;this.programs[s].delete(t)}_needsComputeUpdate(e){const t=this.get(e);return void 0===t.pipeline||t.version!==e.version}_needsRenderUpdate(e){return void 0===this.get(e).pipeline||this.backend.needsRenderUpdate(e)}}class CS extends dS{constructor(e,t,s,i,r,n){super(),this.backend=e,this.textures=s,this.pipelines=r,this.attributes=i,this.nodes=t,this.info=n,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const e of t){const s=this.get(e);void 0===s.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),s.bindGroup=e)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t){const s=this.get(e);void 0===s.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),s.bindGroup=e)}return t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}deleteForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}deleteForRender(e){const t=e.getBindings();for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isSampler)this.textures.updateSampler(t.texture);else if(t.isStorageBuffer){const e=t.attribute,s=e.isIndirectStorageBufferAttribute?gS:fS;this.attributes.update(e,s)}}_update(e,t){const{backend:s}=this;let i=!1,r=!0,n=0,o=0;for(const t of e.bindings){if(!1!==this.nodes.updateGroup(t)){if(t.isStorageBuffer){const e=t.attribute,s=e.isIndirectStorageBufferAttribute?gS:fS;this.attributes.update(e,s)}if(t.isUniformBuffer){t.update()&&s.updateBinding(t)}else if(t.isSampledTexture){const e=t.update(),a=t.texture,l=this.textures.get(a);e&&(this.textures.updateTexture(a),t.generation!==l.generation&&(t.generation=l.generation,i=!0,r=!1));if(void 0!==s.get(a).externalTexture||l.isDefaultTexture?r=!1:(n=10*n+a.id,o+=a.version),!0===a.isStorageTexture&&!0===a.mipmapsAutoUpdate){const e=this.get(a);!0===t.store?e.needsMipmap=!0:this.textures.needsMipmaps(a)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(a),e.needsMipmap=!1)}}else if(t.isSampler){if(t.update()){const e=this.textures.updateSampler(t.texture);t.samplerKey!==e&&(t.samplerKey=e,i=!0,r=!1)}}}}!0===i&&this.backend.updateBindings(e,t,r?n:0,o)}}function RS(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?e.z-t.z:e.id-t.id}function PS(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?t.z-e.z:e.id-t.id}function BS(e){return(e.transmission>0||e.transmissionNode&&e.transmissionNode.isNode)&&2===e.side&&!1===e.forceSinglePass}class IS{constructor(e,t,s){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,s),this.lightsArray=[],this.scene=t,this.camera=s,this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,s,i,r,n,o){let a=this.renderItems[this.renderItemsIndex];return void 0===a?(a={id:e.id,object:e,geometry:t,material:s,groupOrder:i,renderOrder:e.renderOrder,z:r,group:n,clippingContext:o},this.renderItems[this.renderItemsIndex]=a):(a.id=e.id,a.object=e,a.geometry=t,a.material=s,a.groupOrder=i,a.renderOrder=e.renderOrder,a.z=r,a.group=n,a.clippingContext=o),this.renderItemsIndex++,a}push(e,t,s,i,r,n,o){const a=this.getNextRenderItem(e,t,s,i,r,n,o);!0===e.occlusionTest&&this.occlusionQueryCount++,!0===s.transparent||s.transmission>0||s.transmissionNode&&s.transmissionNode.isNode||s.backdropNode&&s.backdropNode.isNode?(BS(s)&&this.transparentDoublePass.push(a),this.transparent.push(a)):this.opaque.push(a)}unshift(e,t,s,i,r,n,o){const a=this.getNextRenderItem(e,t,s,i,r,n,o);!0===s.transparent||s.transmission>0||s.transmissionNode&&s.transmissionNode.isNode||s.backdropNode&&s.backdropNode.isNode?(BS(s)&&this.transparentDoublePass.unshift(a),this.transparent.unshift(a)):this.opaque.unshift(a)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||RS),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||PS),this.transparent.length>1&&this.transparent.sort(t||PS)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e<t;e++){const t=this.renderItems[e];if(null===t.id)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.groupOrder=null,t.renderOrder=null,t.z=null,t.group=null,t.clippingContext=null}}}const DS=[];class LS{constructor(e){this.lighting=e,this.lists=new aS}get(e,t){const s=this.lists;DS[0]=e,DS[1]=t;let i=s.get(DS);return void 0===i&&(i=new IS(this.lighting,e,t),s.set(DS,i)),DS.length=0,i}dispose(){this.lists=new aS}}let FS=0;class OS{constructor(){this.id=FS++,this.color=!0,this.clearColor=!0,this.clearColorValue={r:0,g:0,b:0,a:1},this.depth=!0,this.clearDepth=!0,this.clearDepthValue=1,this.stencil=!1,this.clearStencil=!0,this.clearStencilValue=1,this.viewport=!1,this.viewportValue=new Pa,this.scissor=!1,this.scissorValue=new Pa,this.renderTarget=null,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.activeMipmapLevel=0,this.sampleCount=1,this.width=0,this.height=0,this.occlusionQueryCount=0,this.clippingContext=null,this.isRenderContext=!0}getCacheKey(){return VS(this)}}function VS(e){const{textures:t,activeCubeFace:s,activeMipmapLevel:i}=e,r=[s,i];for(const e of t)r.push(e.id);return oc(r)}const zS=[],kS=new Jh,US=new Uh;class GS{constructor(){this.chainMaps={}}get(e,t,s=null,i=null){let r;if(zS[0]=e,zS[1]=t,null!==i&&(zS[2]=i),null===s)r="default";else{const e=s.texture.format;r=`${s.textures.length}:${e}:${s.samples}:${s.depthBuffer}:${s.stencilBuffer}`}const n=this._getChainMap(r);let o=n.get(zS);return void 0===o&&(o=new OS,n.set(zS,o)),zS.length=0,null!==s&&(o.sampleCount=0===s.samples?1:s.samples),o}getForClear(e=null){return this.get(kS,US,e)}_getChainMap(e){return this.chainMaps[e]||(this.chainMaps[e]=new aS)}dispose(){this.chainMaps={}}}const jS=new da;class $S extends dS{constructor(e,t,s){super(),this.renderer=e,this.backend=t,this.info=s}updateRenderTarget(e,t=0){const s=this.get(e),i=0===e.samples?1:e.samples,r=s.depthTextureMips||(s.depthTextureMips={}),n=e.textures,o=this.getSize(n[0]),a=o.width>>t,l=o.height>>t;let h=e.depthTexture||r[t];const u=!0===e.depthBuffer||!0===e.stencilBuffer;let c=!1;void 0===h&&u&&(h=new _u,h.format=e.stencilBuffer?On:Fn,h.type=e.stencilBuffer?Pn:An,h.image.width=a,h.image.height=l,h.image.depth=o.depth,h.renderTarget=e,h.isArrayTexture=!0===e.multiview&&o.depth>1,r[t]=h),s.width===o.width&&o.height===s.height||(c=!0,h&&(h.needsUpdate=!0,h.image.width=a,h.image.height=l,h.image.depth=h.isArrayTexture?h.image.depth:1)),s.width=o.width,s.height=o.height,s.textures=n,s.depthTexture=h||null,s.depth=e.depthBuffer,s.stencil=e.stencilBuffer,s.renderTarget=e,s.sampleCount!==i&&(c=!0,h&&(h.needsUpdate=!0),s.sampleCount=i);const d={sampleCount:i};if(!0!==e.isXRRenderTarget){for(let e=0;e<n.length;e++){const t=n[e];c&&(t.needsUpdate=!0),this.updateTexture(t,d)}h&&this.updateTexture(h,d)}!0!==s.initialized&&(s.initialized=!0,s.onDispose=()=>{this._destroyRenderTarget(e)},e.addEventListener("dispose",s.onDispose))}updateTexture(e,t={}){const s=this.get(e);if(!0===s.initialized&&s.version===e.version)return;const i=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,r=this.backend;if(i&&!0===s.initialized&&r.destroyTexture(e),e.isFramebufferTexture){const t=this.renderer.getRenderTarget();e.type=t?t.texture.type:wn}const{width:n,height:o,depth:a}=this.getSize(e);if(t.width=n,t.height=o,t.depth=a,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,n,o):1,e.isCubeTexture&&e.mipmaps.length>0&&t.levels++,i||!0===e.isStorageTexture||!0===e.isExternalTexture)r.createTexture(e,t),s.generation=e.version;else if(e.version>0){const i=e.image;if(void 0===i)Yo("Renderer: Texture marked for update but image is undefined.");else if(!1===i.complete)Yo("Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const s=[];for(const t of e.images)s.push(t);t.images=s}else t.image=i;void 0!==s.isDefaultTexture&&!0!==s.isDefaultTexture||(r.createTexture(e,t),s.isDefaultTexture=!1,s.generation=e.version),!0===e.source.dataReady&&r.updateTexture(e,t);const n=!0===e.isStorageTexture&&!1===e.mipmapsAutoUpdate;t.needsMipmaps&&0===e.mipmaps.length&&!n&&r.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else r.createDefaultTexture(e),s.isDefaultTexture=!0,s.generation=e.version;!0!==s.initialized&&(s.initialized=!0,s.generation=e.version,this.info.memory.textures++,e.isVideoTexture&&!0===_a.enabled&&_a.getTransfer(e.colorSpace)!==Eo&&Yo("WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace."),s.onDispose=()=>{this._destroyTexture(e)},e.addEventListener("dispose",s.onDispose)),s.version=e.version}updateSampler(e){return this.backend.updateSampler(e)}getSize(e,t=jS){let s=e.images?e.images[0]:e.image;return s?(void 0!==s.image&&(s=s.image),"undefined"!=typeof HTMLVideoElement&&s instanceof HTMLVideoElement?(t.width=s.videoWidth||1,t.height=s.videoHeight||1,t.depth=1):"undefined"!=typeof VideoFrame&&s instanceof VideoFrame?(t.width=s.displayWidth||1,t.height=s.displayHeight||1,t.depth=1):(t.width=s.width||1,t.height=s.height||1,t.depth=e.isCubeTexture?6:s.depth||1)):t.width=t.height=t.depth=1,t}getMipLevels(e,t,s){let i;return i=e.mipmaps.length>0?e.mipmaps.length:!0===e.isCompressedTexture?1:Math.floor(Math.log2(Math.max(t,s)))+1,i}needsMipmaps(e){return!0===e.generateMipmaps||e.mipmaps.length>0}_destroyRenderTarget(e){if(!0===this.has(e)){const t=this.get(e),s=t.textures,i=t.depthTexture;e.removeEventListener("dispose",t.onDispose);for(let e=0;e<s.length;e++)this._destroyTexture(s[e]);i&&this._destroyTexture(i),this.delete(e),this.backend.delete(e)}}_destroyTexture(e){if(!0===this.has(e)){const t=this.get(e);e.removeEventListener("dispose",t.onDispose);const s=t.isDefaultTexture;this.backend.destroyTexture(e,s),this.delete(e),this.info.memory.textures--}}}class WS extends eh{constructor(e,t,s,i=1){super(e,t,s),this.a=i}set(e,t,s,i=1){return this.a=i,super.set(e,t,s)}copy(e){return void 0!==e.a&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}class HS extends tp{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getMemberType(e,t){const s=this.getNodeType(e),i=e.getStructTypeNode(s);let r;return null!==i?r=i.getMemberType(e,t):(Zo(`TSL: Member "${t}" not found in struct "${s}".`),r="float"),r}getHash(){return this.uuid}generate(){return this.name}}class qS extends Cc{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this._currentNode=null,this.isStackNode=!0}getElementType(e){return this.hasOutput?this.outputNode.getElementType(e):"void"}getNodeType(e){return this.hasOutput?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.hasOutput?this.outputNode.getMemberType(e,t):"void"}addToStack(e,t=this.nodes.length){return!0!==e.isNode?(Zo("TSL: Invalid node added to stack."),this):(this.nodes.splice(t,0,e),this)}addToStackBefore(e){const t=this._currentNode?this.nodes.indexOf(this._currentNode):0;return this.addToStack(e,t)}If(e,t){const s=new xd(t);return this._currentCond=kf(e,s),this.addToStack(this._currentCond)}ElseIf(e,t){const s=new xd(t),i=kf(e,s);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new xd(e),this}Switch(e){return this._expressionNode=bd(e),this}Case(...e){const t=[];if(e.length>=2)for(let s=0;s<e.length-1;s++)t.push(this._expressionNode.equal(bd(e[s])));else Zo("TSL: Invalid parameter length. Case() requires at least two parameters.");const s=new xd(e[e.length-1]);let i=t[0];for(let e=1;e<t.length;e++)i=i.or(t[e]);const r=kf(i,s);return null===this._currentCond?(this._currentCond=r,this.addToStack(this._currentCond)):(this._currentCond.elseNode=r,this._currentCond=r,this)}Default(e){return this.Else(e),this}setup(e){const t=e.getNodeProperties(this);let s=0;for(const i of this.getChildren())i.isVarNode&&i.isIntent(e)&&!0!==i.isAssign(e)||(t["node"+s++]=i);return t.outputNode||null}get hasOutput(){return this.outputNode&&this.outputNode.isNode}build(e,...t){const s=Rd(),i=e.buildStage;Cd(this),e.setActiveStack(this);const r=t=>{if(this._currentNode=t,!t.isVarNode||!t.isIntent(e)||!0===t.isAssign(e))if("setup"===i)t.build(e);else if("analyze"===i)t.build(e,this);else if("generate"===i){const s=e.getDataFromNode(t,"any").stages,i=s&&s[e.shaderStage];if(t.isVarNode&&i&&1===i.length&&i[0]&&i[0].isStackNode)return;t.build(e,"void")}},n=[...this.nodes];for(const e of n)r(e);this._currentNode=null;const o=this.nodes.filter(e=>-1===n.indexOf(e));for(const e of o)r(e);let a;return a=this.hasOutput?this.outputNode.build(e,...t):super.build(e,...t),Cd(s),e.removeActiveStack(this),a}}const XS=Td(qS).setParameterLength(0,1);class YS extends Cc{static get type(){return"StructTypeNode"}constructor(e,t=null){var s;super("struct"),this.membersLayout=(s=e,Object.entries(s).map(([e,t])=>"string"==typeof t?{name:e,type:t,atomic:!1}:{name:e,type:t.type,atomic:t.atomic||!1})),this.name=t,this.isStructLayoutNode=!0}getLength(){const e=Float32Array.BYTES_PER_ELEMENT;let t=1,s=0;for(const i of this.membersLayout){const r=i.type,n=pc(r),o=mc(r)/e;t=Math.max(t,o);const a=s%t%o;0!==a&&(s+=o-a),s+=n}return Math.ceil(s/t)*t}getMemberType(e,t){const s=this.membersLayout.find(e=>e.name===t);return s?s.type:"void"}getNodeType(e){return e.getStructTypeFromNode(this,this.membersLayout,this.name).name}setup(e){e.getStructTypeFromNode(this,this.membersLayout,this.name),e.addInclude(this)}generate(e){return this.getNodeType(e)}}class ZS extends Cc{static get type(){return"StructNode"}constructor(e,t){super("vec3"),this.structTypeNode=e,this.values=t,this.isStructNode=!0}getNodeType(e){return this.structTypeNode.getNodeType(e)}getMemberType(e,t){return this.structTypeNode.getMemberType(e,t)}generate(e){const t=e.getVarFromNode(this),s=t.type,i=e.getPropertyName(t);return e.addLineFlowCode(`${i} = ${e.generateStruct(s,this.structTypeNode.membersLayout,this.values)}`,this),t.name}}class QS extends Cc{static get type(){return"OutputStructNode"}constructor(...e){super(),this.members=e,this.isOutputStructNode=!0}getNodeType(e){const t=e.getNodeProperties(this);if(void 0===t.membersLayout){const s=this.members,i=[];for(let t=0;t<s.length;t++){const r="m"+t,n=s[t].getNodeType(e);i.push({name:r,type:n,index:t})}t.membersLayout=i,t.structType=e.getOutputStructTypeFromNode(this,t.membersLayout)}return t.structType.name}generate(e){const t=e.getOutputStructName(),s=this.members,i=""!==t?t+".":"";for(let t=0;t<s.length;t++){const r=s[t].build(e);e.addLineFlowCode(`${i}m${t} = ${r}`,this)}return t}}const KS=Td(QS);function JS(e,t){for(let s=0;s<e.length;s++)if(e[s].name===t)return s;return-1}class eM extends QS{static get type(){return"MRTNode"}constructor(e){super(),this.outputNodes=e,this.isMRTNode=!0}has(e){return void 0!==this.outputNodes[e]}get(e){return this.outputNodes[e]}merge(e){const t={...this.outputNodes,...e.outputNodes};return tM(t)}setup(e){const t=this.outputNodes,s=[],i=e.renderer.getRenderTarget().textures;for(const e in t){s[JS(i,e)]=Hd(t[e])}return this.members=s,super.setup(e)}}const tM=Td(eM);class sM extends Bc{static get type(){return"BitcastNode"}constructor(e,t,s=null){super(),this.valueNode=e,this.conversionType=t,this.inputType=s,this.isBitcastNode=!0}getNodeType(e){if(null!==this.inputType){const t=this.valueNode.getNodeType(e),s=e.getTypeLength(t);return e.getTypeFromLength(s,this.conversionType)}return this.conversionType}generate(e){const t=this.getNodeType(e);let s="";if(null!==this.inputType){const t=this.valueNode.getNodeType(e);s=1===e.getTypeLength(t)?this.inputType:e.changeComponentType(t,this.inputType)}else s=this.valueNode.getNodeType(e);return`${e.getBitcastMethod(t,s)}( ${this.valueNode.build(e,s)} )`}}const iM=Md(sM).setParameterLength(2),rM=e=>new sM(e,"uint","float"),nM={};class oM extends vm{static get type(){return"BitcountNode"}constructor(e,t){super(e,t),this.isBitcountNode=!0}_resolveElementType(e,t,s){"int"===s?t.assign(iM(e,"uint")):t.assign(e)}_returnDataNode(e){switch(e){case"uint":return Fd;case"int":return Ld;case"uvec2":return kd;case"uvec3":return $d;case"uvec4":return Xd;case"ivec2":return zd;case"ivec3":return jd;case"ivec4":return qd}}_createTrailingZerosBaseLayout(e,t){const s=this._returnDataNode(t);return Ed(([e])=>{const i=Fd(0);this._resolveElementType(e,i,t);const r=Dd(i.bitAnd(Km(i))),n=rM(r).shiftRight(23).sub(127);return s(n)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createLeadingZerosBaseLayout(e,t){const s=this._returnDataNode(t);return Ed(([e])=>{Pd(e.equal(Fd(0)),()=>Fd(32));const i=Fd(0),r=Fd(0);return this._resolveElementType(e,i,t),Pd(i.shiftRight(16).equal(0),()=>{r.addAssign(16),i.shiftLeftAssign(16)}),Pd(i.shiftRight(24).equal(0),()=>{r.addAssign(8),i.shiftLeftAssign(8)}),Pd(i.shiftRight(28).equal(0),()=>{r.addAssign(4),i.shiftLeftAssign(4)}),Pd(i.shiftRight(30).equal(0),()=>{r.addAssign(2),i.shiftLeftAssign(2)}),Pd(i.shiftRight(31).equal(0),()=>{r.addAssign(1)}),s(r)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createOneBitsBaseLayout(e,t){const s=this._returnDataNode(t);return Ed(([e])=>{const i=Fd(0);this._resolveElementType(e,i,t),i.assign(i.sub(i.shiftRight(Fd(1)).bitAnd(Fd(1431655765)))),i.assign(i.bitAnd(Fd(858993459)).add(i.shiftRight(Fd(2)).bitAnd(Fd(858993459))));const r=i.add(i.shiftRight(Fd(4))).bitAnd(Fd(252645135)).mul(Fd(16843009)).shiftRight(Fd(24));return s(r)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createMainLayout(e,t,s,i){const r=this._returnDataNode(t);return Ed(([e])=>{if(1===s)return r(i(e));{const t=r(0),n=["x","y","z","w"];for(let r=0;r<s;r++){const s=n[r];t[s].assign(i(e[s]))}return t}}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}setup(e){const{method:t,aNode:s}=this,{renderer:i}=e;if(i.backend.isWebGPUBackend)return super.setup(e);const r=this.getInputType(e),n=e.getElementType(r),o=e.getTypeLength(r),a=`${t}_base_${n}`,l=`${t}_${r}`;let h=nM[a];if(void 0===h){switch(t){case oM.COUNT_LEADING_ZEROS:h=this._createLeadingZerosBaseLayout(a,n);break;case oM.COUNT_TRAILING_ZEROS:h=this._createTrailingZerosBaseLayout(a,n);break;case oM.COUNT_ONE_BITS:h=this._createOneBitsBaseLayout(a,n)}nM[a]=h}let u=nM[l];void 0===u&&(u=this._createMainLayout(l,r,o,h),nM[l]=u);return Ed(()=>u(s))()}}oM.COUNT_TRAILING_ZEROS="countTrailingZeros",oM.COUNT_LEADING_ZEROS="countLeadingZeros",oM.COUNT_ONE_BITS="countOneBits";const aM=Md(oM,oM.COUNT_TRAILING_ZEROS).setParameterLength(1),lM=Md(oM,oM.COUNT_LEADING_ZEROS).setParameterLength(1),hM=Md(oM,oM.COUNT_ONE_BITS).setParameterLength(1),uM=Ed(([e])=>{const t=e.toUint().mul(747796405).add(2891336453),s=t.shiftRight(t.shiftRight(28).add(4)).bitXor(t).mul(277803737);return s.shiftRight(22).bitXor(s).toFloat().mul(1/2**32)}),cM=(e,t)=>bf(Kp(4,e.mul(Qp(1,e))),t);class dM extends Bc{static get type(){return"PackFloatNode"}constructor(e,t){super(),this.vectorNode=t,this.encoding=e,this.isPackFloatNode=!0}getNodeType(){return"uint"}generate(e){const t=this.vectorNode.getNodeType(e);return`${e.getFloatPackingMethod(this.encoding)}(${this.vectorNode.build(e,t)})`}}const pM=Md(dM,"snorm").setParameterLength(1),mM=Md(dM,"unorm").setParameterLength(1),fM=Md(dM,"float16").setParameterLength(1);class gM extends Bc{static get type(){return"UnpackFloatNode"}constructor(e,t){super(),this.uintNode=t,this.encoding=e,this.isUnpackFloatNode=!0}getNodeType(){return"vec2"}generate(e){const t=this.uintNode.getNodeType(e);return`${e.getFloatUnpackingMethod(this.encoding)}(${this.uintNode.build(e,t)})`}}const yM=Md(gM,"snorm").setParameterLength(1),xM=Md(gM,"unorm").setParameterLength(1),bM=Md(gM,"float16").setParameterLength(1),_M=Ed(([e])=>e.fract().sub(.5).abs()).setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),wM=Ed(([e])=>Gd(_M(e.z.add(_M(e.y.mul(1)))),_M(e.z.add(_M(e.x.mul(1)))),_M(e.y.add(_M(e.x.mul(1)))))).setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),vM=Ed(([e,t,s])=>{const i=Gd(e).toVar(),r=Dd(1.4).toVar(),n=Dd(0).toVar(),o=Gd(i).toVar();return C_({start:Dd(0),end:Dd(3),type:"float",condition:"<="},()=>{const e=Gd(wM(o.mul(2))).toVar();i.addAssign(e.add(s.mul(Dd(.1).mul(t)))),o.mulAssign(1.8),r.mulAssign(1.5),i.mulAssign(1.2);const a=Dd(_M(i.z.add(_M(i.x.add(_M(i.y)))))).toVar();n.addAssign(a.div(r)),o.addAssign(.14)}),n}).setLayout({name:"triNoise3D",type:"float",inputs:[{name:"position",type:"vec3"},{name:"speed",type:"float"},{name:"time",type:"float"}]});class TM extends Cc{static get type(){return"FunctionOverloadingNode"}constructor(e=[],...t){super(),this.functionNodes=e,this.parametersNodes=t,this._candidateFn=null,this.global=!0}getNodeType(e){return this.getCandidateFn(e).shaderNode.layout.type}getCandidateFn(e){const t=this.parametersNodes;let s=this._candidateFn;if(null===s){let i=null,r=-1;for(const s of this.functionNodes){const n=s.shaderNode.layout;if(null===n)throw new Error("FunctionOverloadingNode: FunctionNode must be a layout.");const o=n.inputs;if(t.length===o.length){let n=0;for(let s=0;s<t.length;s++){const i=t[s],r=o[s];i.getNodeType(e)===r.type&&n++}n>r&&(i=s,r=n)}}this._candidateFn=s=i}return s}setup(e){return this.getCandidateFn(e)(...this.parametersNodes)}}const SM=Td(TM),MM=e=>(...t)=>SM(e,...t),AM=Up(0).setGroup(Vp).onRenderUpdate(e=>e.time),NM=Up(0).setGroup(Vp).onRenderUpdate(e=>e.deltaTime),EM=Up(0,"uint").setGroup(Vp).onRenderUpdate(e=>e.frameId);const CM=Ed(([e,t,s=Vd(.5)])=>ZT(e.sub(s),t).add(s)),RM=Ed(([e,t,s=Vd(.5)])=>{const i=e.sub(s),r=i.dot(i),n=r.mul(r).mul(t);return e.add(i.mul(n))}),PM=Ed(({position:e=null,horizontal:t=!0,vertical:s=!1})=>{let i;null!==e?(i=Uy.toVar(),i[3][0]=e.x,i[3][1]=e.y,i[3][2]=e.z):i=Uy;const r=Ay.mul(i);return gd(t)&&(r[0][0]=Uy[0].length(),r[0][1]=0,r[0][2]=0),gd(s)&&(r[1][0]=0,r[1][1]=Uy[1].length(),r[1][2]=0),r[2][0]=0,r[2][1]=0,r[2][2]=1,Sy.mul(r).mul(Jy)}),BM=Ed(([e=null])=>{const t=tw();return tw(q_(e)).sub(t).lessThan(0).select(py,e)});class IM extends Cc{static get type(){return"SpriteSheetUVNode"}constructor(e,t=qg(),s=Dd(0)){super("vec2"),this.countNode=e,this.uvNode=t,this.frameNode=s}setup(){const{frameNode:e,uvNode:t,countNode:s}=this,{width:i,height:r}=s,n=e.mod(i.mul(r)).floor(),o=n.mod(i),a=r.sub(n.add(1).div(i).ceil()),l=s.reciprocal(),h=Vd(o,a);return t.add(h).mul(l)}}const DM=Td(IM).setParameterLength(3),LM=Ed(([e,t=null,s=null,i=Dd(1),r=Jy,n=ux])=>{let o=n.abs().normalize();o=o.div(o.dot(Gd(1)));const a=r.yz.mul(i),l=r.zx.mul(i),h=r.xy.mul(i),u=e.value,c=null!==t?t.value:u,d=null!==s?s.value:u,p=ty(u,a).mul(o.x),m=ty(c,l).mul(o.y),f=ty(d,h).mul(o.z);return Zp(p,m,f)}),FM=new hu,OM=new da,VM=new da,zM=new da,kM=new ll,UM=new da(0,0,-1),GM=new Pa,jM=new da,$M=new da,WM=new Pa,HM=new ua,qM=new Ba,XM=py.flipX();qM.depthTexture=new _u(1,1);let YM=!1;class ZM extends Jg{static get type(){return"ReflectorNode"}constructor(e={}){super(e.defaultTexture||qM.texture,XM),this._reflectorBaseNode=e.reflector||new QM(this,e),this._depthNode=null,this.setUpdateMatrix(!1)}get reflector(){return this._reflectorBaseNode}get target(){return this._reflectorBaseNode.target}getDepthNode(){if(null===this._depthNode){if(!0!==this._reflectorBaseNode.depth)throw new Error("THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ");this._depthNode=bd(new ZM({defaultTexture:qM.depthTexture,reflector:this._reflectorBaseNode}))}return this._depthNode}setup(e){return e.object.isQuadMesh||this._reflectorBaseNode.build(e),super.setup(e)}clone(){const e=new this.constructor(this.reflectorNode);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e._reflectorBaseNode=this._reflectorBaseNode,e}dispose(){super.dispose(),this._reflectorBaseNode.dispose()}}class QM extends Cc{static get type(){return"ReflectorBaseNode"}constructor(e,t={}){super();const{target:s=new Ll,resolutionScale:i=1,generateMipmaps:r=!1,bounces:n=!0,depth:o=!1,samples:a=0}=t;this.textureNode=e,this.target=s,this.resolutionScale=i,void 0!==t.resolution&&(Qo('ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".'),this.resolutionScale=t.resolution),this.generateMipmaps=r,this.bounces=n,this.depth=o,this.samples=a,this.updateBeforeType=n?wc.RENDER:wc.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new Map,this.forceUpdate=!1,this.hasOutput=!1}_updateResolution(e,t){const s=this.resolutionScale;t.getDrawingBufferSize(HM),e.setSize(Math.round(HM.width*s),Math.round(HM.height*s))}setup(e){return this._updateResolution(qM,e.renderer),super.setup(e)}dispose(){super.dispose();for(const e of this.renderTargets.values())e.dispose()}getVirtualCamera(e){let t=this.virtualCameras.get(e);return void 0===t&&(t=e.clone(),this.virtualCameras.set(e,t)),t}getRenderTarget(e){let t=this.renderTargets.get(e);return void 0===t&&(t=new Ba(0,0,{type:En,samples:this.samples}),!0===this.generateMipmaps&&(t.texture.minFilter=1008,t.texture.generateMipmaps=!0),!0===this.depth&&(t.depthTexture=new _u),this.renderTargets.set(e,t)),t}updateBefore(e){if(!1===this.bounces&&YM)return!1;YM=!0;const{scene:t,camera:s,renderer:i,material:r}=e,{target:n}=this,o=this.getVirtualCamera(s),a=this.getRenderTarget(o);i.getDrawingBufferSize(HM),this._updateResolution(a,i),VM.setFromMatrixPosition(n.matrixWorld),zM.setFromMatrixPosition(s.matrixWorld),kM.extractRotation(n.matrixWorld),OM.set(0,0,1),OM.applyMatrix4(kM),jM.subVectors(VM,zM);let l=!1;if(!0===jM.dot(OM)>0&&!1===this.forceUpdate){if(!1===this.hasOutput)return void(YM=!1);l=!0}jM.reflect(OM).negate(),jM.add(VM),kM.extractRotation(s.matrixWorld),UM.set(0,0,-1),UM.applyMatrix4(kM),UM.add(zM),$M.subVectors(VM,UM),$M.reflect(OM).negate(),$M.add(VM),o.coordinateSystem=s.coordinateSystem,o.position.copy(jM),o.up.set(0,1,0),o.up.applyMatrix4(kM),o.up.reflect(OM),o.lookAt($M),o.near=s.near,o.far=s.far,o.updateMatrixWorld(),o.projectionMatrix.copy(s.projectionMatrix),FM.setFromNormalAndCoplanarPoint(OM,VM),FM.applyMatrix4(o.matrixWorldInverse),GM.set(FM.normal.x,FM.normal.y,FM.normal.z,FM.constant);const h=o.projectionMatrix;WM.x=(Math.sign(GM.x)+h.elements[8])/h.elements[0],WM.y=(Math.sign(GM.y)+h.elements[9])/h.elements[5],WM.z=-1,WM.w=(1+h.elements[10])/h.elements[14],GM.multiplyScalar(1/GM.dot(WM));h.elements[2]=GM.x,h.elements[6]=GM.y,h.elements[10]=i.coordinateSystem===Uo?GM.z-0:GM.z+1-0,h.elements[14]=GM.w,this.textureNode.value=a.texture,!0===this.depth&&(this.textureNode.getDepthNode().value=a.depthTexture),r.visible=!1;const u=i.getRenderTarget(),c=i.getMRT(),d=i.autoClear;i.setMRT(null),i.setRenderTarget(a),i.autoClear=!0;const p=t.name;t.name=(t.name||"Scene")+" [ Reflector ]",l?(i.clear(),this.hasOutput=!1):(i.render(t,o),this.hasOutput=!0),t.name=p,i.setMRT(c),i.setRenderTarget(u),i.autoClear=d,r.visible=!0,YM=!1,this.forceUpdate=!1}get resolution(){return Qo('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale}set resolution(e){Qo('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale=e}}const KM=new $u(-1,1,1,-1,0,1);class JM extends Sh{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new gh([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new gh(t,2))}}const eA=new JM;class tA extends Fh{constructor(e=null){super(eA,e),this.camera=KM,this.isQuadMesh=!0}async renderAsync(e){Qo('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,KM)}render(e){e.render(this,KM)}}const sA=new ua;class iA extends Jg{static get type(){return"RTTNode"}constructor(e,t=null,s=null,i={type:En}){const r=new Ba(t,s,i);super(r.texture,qg()),this.isRTTNode=!0,this.node=e,this.width=t,this.height=s,this.pixelRatio=1,this.renderTarget=r,this.textureNeedsUpdate=!0,this.autoUpdate=!0,this._rttNode=null,this._quadMesh=new tA(new gw),this.updateBeforeType=wc.RENDER}get autoResize(){return null===this.width}setup(e){return this._rttNode=this.node.context(e.getSharedContext()),this._quadMesh.material.name="RTT",this._quadMesh.material.needsUpdate=!0,super.setup(e)}setSize(e,t){this.width=e,this.height=t;const s=e*this.pixelRatio,i=t*this.pixelRatio;this.renderTarget.setSize(s,i),this.textureNeedsUpdate=!0}setPixelRatio(e){this.pixelRatio=e,this.setSize(this.width,this.height)}updateBefore({renderer:e}){if(!1===this.textureNeedsUpdate&&!1===this.autoUpdate)return;if(this.textureNeedsUpdate=!1,!0===this.autoResize){const t=e.getPixelRatio(),s=e.getSize(sA),i=Math.floor(s.width*t),r=Math.floor(s.height*t);i===this.renderTarget.width&&r===this.renderTarget.height||(this.renderTarget.setSize(i,r),this.textureNeedsUpdate=!0)}let t="RTT";this.node.name&&(t=this.node.name+" [ "+t+" ]"),this._quadMesh.material.fragmentNode=this._rttNode,this._quadMesh.name=t;const s=e.getRenderTarget();e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),e.setRenderTarget(s)}clone(){const e=new Jg(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e.referenceNode=this,e}}const rA=(e,...t)=>bd(new iA(bd(e),...t)),nA=Ed(([e,t,s],i)=>{let r;i.renderer.coordinateSystem===Uo?(e=Vd(e.x,e.y.oneMinus()).mul(2).sub(1),r=Hd(Gd(e,t),1)):r=Hd(Gd(e.x,e.y.oneMinus(),t).mul(2).sub(1),1);const n=Hd(s.mul(r));return n.xyz.div(n.w)}),oA=Ed(([e,t])=>{const s=t.mul(Hd(e,1)),i=s.xy.div(s.w).mul(.5).add(.5).toVar();return Vd(i.x,i.y.oneMinus())}),aA=Ed(([e,t,s])=>{const i=Yg(sy(t)),r=zd(e.mul(i)).toVar(),n=sy(t,r).toVar(),o=sy(t,r.sub(zd(2,0))).toVar(),a=sy(t,r.sub(zd(1,0))).toVar(),l=sy(t,r.add(zd(1,0))).toVar(),h=sy(t,r.add(zd(2,0))).toVar(),u=sy(t,r.add(zd(0,2))).toVar(),c=sy(t,r.add(zd(0,1))).toVar(),d=sy(t,r.sub(zd(0,1))).toVar(),p=sy(t,r.sub(zd(0,2))).toVar(),m=Ym(Qp(Dd(2).mul(a).sub(o),n)).toVar(),f=Ym(Qp(Dd(2).mul(l).sub(h),n)).toVar(),g=Ym(Qp(Dd(2).mul(c).sub(u),n)).toVar(),y=Ym(Qp(Dd(2).mul(d).sub(p),n)).toVar(),x=nA(e,n,s).toVar(),b=m.lessThan(f).select(x.sub(nA(e.sub(Vd(Dd(1).div(i.x),0)),a,s)),x.negate().add(nA(e.add(Vd(Dd(1).div(i.x),0)),l,s))),_=g.lessThan(y).select(x.sub(nA(e.add(Vd(0,Dd(1).div(i.y))),c,s)),x.negate().add(nA(e.sub(Vd(0,Dd(1).div(i.y))),d,s)));return Um(xf(b,_))}),lA=Ed(([e])=>Gm(Dd(52.9829189).mul(Gm(yf(e,Vd(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),hA=Ed(([e,t,s])=>{const i=Dd(2.399963229728653),r=Om(Dd(e).add(.5).div(Dd(t))),n=Dd(e).mul(i).add(s);return Vd($m(n),jm(n)).mul(r)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]});class uA extends Cc{static get type(){return"SampleNode"}constructor(e,t=null){super(),this.callback=e,this.uvNode=t,this.isSampleNode=!0}setup(){return this.sample(qg())}sample(e){return this.callback(e)}}class cA extends Cc{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===cA.OBJECT?this.updateType=wc.OBJECT:e===cA.MATERIAL?this.updateType=wc.RENDER:e===cA.BEFORE_OBJECT?this.updateBeforeType=wc.OBJECT:e===cA.BEFORE_MATERIAL&&(this.updateBeforeType=wc.RENDER)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}}cA.OBJECT="object",cA.MATERIAL="material",cA.BEFORE_OBJECT="beforeObject",cA.BEFORE_MATERIAL="beforeMaterial";const dA=(e,t)=>new cA(e,t).toStack();class pA extends nu{constructor(e,t,s=Float32Array){super(ArrayBuffer.isView(e)?e:new s(e*t),t),this.isStorageInstancedBufferAttribute=!0}}class mA extends dh{constructor(e,t,s=Float32Array){super(ArrayBuffer.isView(e)?e:new s(e*t),t),this.isStorageBufferAttribute=!0}}class fA extends Cc{static get type(){return"PointUVNode"}constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const gA=Sd(fA),yA=new xl,xA=new ll;class bA extends Cc{static get type(){return"SceneNode"}constructor(e=bA.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,s=null!==this.scene?this.scene:e.scene;let i;return t===bA.BACKGROUND_BLURRINESS?i=Ox("backgroundBlurriness","float",s):t===bA.BACKGROUND_INTENSITY?i=Ox("backgroundIntensity","float",s):t===bA.BACKGROUND_ROTATION?i=Up("mat4").setName("backgroundRotation").setGroup(Vp).onRenderUpdate(()=>{const e=s.background;return null!==e&&e.isTexture&&300!==e.mapping?(yA.copy(s.backgroundRotation),yA.x*=-1,yA.y*=-1,yA.z*=-1,xA.makeRotationFromEuler(yA)):xA.identity(),xA}):Zo("SceneNode: Unknown scope:",t),i}}bA.BACKGROUND_BLURRINESS="backgroundBlurriness",bA.BACKGROUND_INTENSITY="backgroundIntensity",bA.BACKGROUND_ROTATION="backgroundRotation";const _A=Sd(bA,bA.BACKGROUND_BLURRINESS),wA=Sd(bA,bA.BACKGROUND_INTENSITY),vA=Sd(bA,bA.BACKGROUND_ROTATION);class TA extends Jg{static get type(){return"StorageTextureNode"}constructor(e,t,s=null){super(e,t),this.storeNode=s,this.mipLevel=0,this.isStorageTextureNode=!0,this.access=vc.WRITE_ONLY}getInputType(){return"storageTexture"}setup(e){super.setup(e);const t=e.getNodeProperties(this);return t.storeNode=this.storeNode,t}setAccess(e){return this.access=e,this}setMipLevel(e){return this.mipLevel=e,this}generate(e,t){let s;return s=null!==this.storeNode?this.generateStore(e):super.generate(e,t),s}toReadWrite(){return this.setAccess(vc.READ_WRITE)}toReadOnly(){return this.setAccess(vc.READ_ONLY)}toWriteOnly(){return this.setAccess(vc.WRITE_ONLY)}generateStore(e){const t=e.getNodeProperties(this),{uvNode:s,storeNode:i,depthNode:r}=t,n=super.generate(e,"property"),o=s.build(e,!0===this.value.is3DTexture?"uvec3":"uvec2"),a=i.build(e,"vec4"),l=r?r.build(e,"int"):null,h=e.generateTextureStore(e,n,o,l,a);e.addLineFlowCode(h,this)}clone(){const e=super.clone();return e.storeNode=this.storeNode,e.mipLevel=this.mipLevel,e}}const SA=Td(TA).setParameterLength(1,3),MA=Ed(({texture:e,uv:t})=>{const s=1e-4,i=Gd().toVar();return Pd(t.x.lessThan(s),()=>{i.assign(Gd(1,0,0))}).ElseIf(t.y.lessThan(s),()=>{i.assign(Gd(0,1,0))}).ElseIf(t.z.lessThan(s),()=>{i.assign(Gd(0,0,1))}).ElseIf(t.x.greaterThan(.9999),()=>{i.assign(Gd(-1,0,0))}).ElseIf(t.y.greaterThan(.9999),()=>{i.assign(Gd(0,-1,0))}).ElseIf(t.z.greaterThan(.9999),()=>{i.assign(Gd(0,0,-1))}).Else(()=>{const s=.01,r=e.sample(t.add(Gd(-.01,0,0))).r.sub(e.sample(t.add(Gd(s,0,0))).r),n=e.sample(t.add(Gd(0,-.01,0))).r.sub(e.sample(t.add(Gd(0,s,0))).r),o=e.sample(t.add(Gd(0,0,-.01))).r.sub(e.sample(t.add(Gd(0,0,s))).r);i.assign(Gd(r,n,o))}),i.normalize()});class AA extends Jg{static get type(){return"Texture3DNode"}constructor(e,t=null,s=null){super(e,t,s),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return Gd(.5,.5,.5)}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return!e.isFlipY()||!0!==s.isRenderTargetTexture&&!0!==s.isFramebufferTexture||(t=this.sampler?t.flipY():t.setY(Ld(Yg(this,this.levelNode).y).sub(t.y).sub(1))),t}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}generateOffset(e,t){return t.build(e,"ivec3")}normal(e){return MA({texture:this,uv:e})}}const NA=Td(AA).setParameterLength(1,3);class EA extends Fx{static get type(){return"UserDataNode"}constructor(e,t,s=null){super(e,t,s),this.userData=s}updateReference(e){return this.reference=null!==this.userData?this.userData:e.object.userData,this.reference}}const CA=new WeakMap;class RA extends Bc{static get type(){return"VelocityNode"}constructor(){super("vec2"),this.projectionMatrix=null,this.updateType=wc.OBJECT,this.updateAfterType=wc.OBJECT,this.previousModelWorldMatrix=Up(new ll),this.previousProjectionMatrix=Up(new ll).setGroup(Vp),this.previousCameraViewMatrix=Up(new ll)}setProjectionMatrix(e){this.projectionMatrix=e}update({frameId:e,camera:t,object:s}){const i=BA(s);this.previousModelWorldMatrix.value.copy(i);const r=PA(t);r.frameId!==e&&(r.frameId=e,void 0===r.previousProjectionMatrix?(r.previousProjectionMatrix=new ll,r.previousCameraViewMatrix=new ll,r.currentProjectionMatrix=new ll,r.currentCameraViewMatrix=new ll,r.previousProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),r.previousCameraViewMatrix.copy(t.matrixWorldInverse)):(r.previousProjectionMatrix.copy(r.currentProjectionMatrix),r.previousCameraViewMatrix.copy(r.currentCameraViewMatrix)),r.currentProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),r.currentCameraViewMatrix.copy(t.matrixWorldInverse),this.previousProjectionMatrix.value.copy(r.previousProjectionMatrix),this.previousCameraViewMatrix.value.copy(r.previousCameraViewMatrix))}updateAfter({object:e}){BA(e).copy(e.matrixWorld)}setup(){const e=null===this.projectionMatrix?Sy:Up(this.projectionMatrix),t=this.previousCameraViewMatrix.mul(this.previousModelWorldMatrix),s=e.mul(Xy).mul(Jy),i=this.previousProjectionMatrix.mul(t).mul(ex),r=s.xy.div(s.w),n=i.xy.div(i.w);return Qp(r,n)}}function PA(e){let t=CA.get(e);return void 0===t&&(t={},CA.set(e,t)),t}function BA(e,t=0){const s=PA(e);let i=s[t];return void 0===i&&(s[t]=i=new ll,s[t].copy(e.matrixWorld)),i}const IA=Sd(RA),DA=Ed(([e])=>VA(e.rgb)),LA=Ed(([e,t=Dd(1)])=>t.mix(VA(e.rgb),e.rgb)),FA=Ed(([e,t=Dd(1)])=>{const s=Zp(e.r,e.g,e.b).div(3),i=e.r.max(e.g.max(e.b)),r=i.sub(s).mul(t).mul(-3);return Af(e.rgb,i,r)}),OA=Ed(([e,t=Dd(1)])=>{const s=Gd(.57735,.57735,.57735),i=t.cos();return Gd(e.rgb.mul(i).add(s.cross(e.rgb).mul(t.sin()).add(s.mul(yf(s,e.rgb).mul(i.oneMinus())))))}),VA=(e,t=Gd(_a.getLuminanceCoefficients(new da)))=>yf(e,t),zA=Ed(([e,t=Gd(1),s=Gd(0),i=Gd(1),r=Dd(1),n=Gd(_a.getLuminanceCoefficients(new da,Ao))])=>{const o=e.rgb.dot(Gd(n)),a=df(e.rgb.mul(t).add(s),0).toVar(),l=a.pow(i).toVar();return Pd(a.r.greaterThan(0),()=>{a.r.assign(l.r)}),Pd(a.g.greaterThan(0),()=>{a.g.assign(l.g)}),Pd(a.b.greaterThan(0),()=>{a.b.assign(l.b)}),a.assign(o.add(a.sub(o).mul(r))),Hd(a.rgb,e.a)});class kA extends Bc{static get type(){return"PosterizeNode"}constructor(e,t){super(),this.sourceNode=e,this.stepsNode=t}setup(){const{sourceNode:e,stepsNode:t}=this;return e.mul(t).floor().div(t)}}const UA=Td(kA).setParameterLength(2),GA=new ua;class jA extends Jg{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class $A extends jA{static get type(){return"PassMultipleTextureNode"}constructor(e,t,s=!1){super(e,null),this.textureName=t,this.previousTexture=s}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){const e=new this.constructor(this.passNode,this.textureName,this.previousTexture);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}class WA extends Bc{static get type(){return"PassNode"}constructor(e,t,s,i={}){super("vec4"),this.scope=e,this.scene=t,this.camera=s,this.options=i,this._pixelRatio=1,this._width=1,this._height=1;const r=new _u;r.isRenderTargetTexture=!0,r.name="depth";const n=new Ba(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:En,...i});n.texture.name="output",n.depthTexture=r,this.renderTarget=n,this.overrideMaterial=null,this.transparent=!0,this.opaque=!0,this.contextNode=null,this._contextNodeCache=null,this._textures={output:n.texture,depth:r},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=Up(0),this._cameraFar=Up(0),this._mrt=null,this._layers=null,this._resolutionScale=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=wc.FRAME,this.global=!0}setResolutionScale(e){return this._resolutionScale=e,this}getResolutionScale(){return this._resolutionScale}setResolution(e){return Yo("PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead."),this.setResolutionScale(e)}getResolution(){return Yo("PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead."),this.getResolutionScale()}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getTexture(e){let t=this._textures[e];if(void 0===t){t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)}return t}getPreviousTexture(e){let t=this._previousTextures[e];return void 0===t&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(void 0!==t){const s=this._textures[e],i=this.renderTarget.textures.indexOf(s);this.renderTarget.textures[i]=t,this._textures[e]=t,this._previousTextures[e]=s,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return void 0===t&&(t=new $A(this,e),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return void 0===t&&(void 0===this._textureNodes[e]&&this.getTextureNode(e),t=new $A(this,e,!0),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(void 0===t){const s=this._cameraNear,i=this._cameraFar;this._viewZNodes[e]=t=Q_(this.getTextureNode(e),s,i)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(void 0===t){const s=this._cameraNear,i=this._cameraFar,r=this.getViewZNode(e);this._linearDepthNodes[e]=t=Y_(r,s,i)}return t}async compileAsync(e){const t=e.getRenderTarget(),s=e.getMRT();e.setRenderTarget(this.renderTarget),e.setMRT(this._mrt),await e.compileAsync(this.scene,this.camera),e.setRenderTarget(t),e.setMRT(s)}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,this.renderTarget.texture.type=e.getOutputBufferType(),this.scope===WA.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:s}=this;let i,r;const n=t.getOutputRenderTarget();n&&!0===n.isXRRenderTarget?(r=1,i=t.xr.getCamera(),t.xr.updateCamera(i),GA.set(n.width,n.height)):(i=this.camera,r=t.getPixelRatio(),t.getSize(GA)),this._pixelRatio=r,this.setSize(GA.width,GA.height);const o=t.getRenderTarget(),a=t.getMRT(),l=t.autoClear,h=t.transparent,u=t.opaque,c=i.layers.mask,d=t.contextNode,p=s.overrideMaterial;this._cameraNear.value=i.near,this._cameraFar.value=i.far,null!==this._layers&&(i.layers.mask=this._layers.mask);for(const e in this._previousTextures)this.toggleTexture(e);null!==this.overrideMaterial&&(s.overrideMaterial=this.overrideMaterial),t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.autoClear=!0,t.transparent=this.transparent,t.opaque=this.opaque,null!==this.contextNode&&(null!==this._contextNodeCache&&this._contextNodeCache.version===this.version||(this._contextNodeCache={version:this.version,context:Gf({...t.contextNode.getFlowContextData(),...this.contextNode.getFlowContextData()})}),t.contextNode=this._contextNodeCache.context);const m=s.name;s.name=this.name?this.name:s.name,t.render(s,i),s.name=m,s.overrideMaterial=p,t.setRenderTarget(o),t.setMRT(a),t.autoClear=l,t.transparent=h,t.opaque=u,t.contextNode=d,i.layers.mask=c}setSize(e,t){this._width=e,this._height=t;const s=Math.floor(this._width*this._pixelRatio*this._resolutionScale),i=Math.floor(this._height*this._pixelRatio*this._resolutionScale);this.renderTarget.setSize(s,i),null!==this._scissor&&this.renderTarget.scissor.copy(this._scissor),null!==this._viewport&&this.renderTarget.viewport.copy(this._viewport)}setScissor(e,t,s,i){null===e?this._scissor=null:(null===this._scissor&&(this._scissor=new Pa),e.isVector4?this._scissor.copy(e):this._scissor.set(e,t,s,i),this._scissor.multiplyScalar(this._pixelRatio*this._resolutionScale).floor())}setViewport(e,t,s,i){null===e?this._viewport=null:(null===this._viewport&&(this._viewport=new Pa),e.isVector4?this._viewport.copy(e):this._viewport.set(e,t,s,i),this._viewport.multiplyScalar(this._pixelRatio*this._resolutionScale).floor())}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}WA.COLOR="color",WA.DEPTH="depth";class HA extends WA{static get type(){return"ToonOutlinePassNode"}constructor(e,t,s,i,r){super(WA.COLOR,e,t),this.colorNode=s,this.thicknessNode=i,this.alphaNode=r,this._materialCache=new WeakMap,this.name="Outline Pass"}updateBefore(e){const{renderer:t}=e,s=t.getRenderObjectFunction();t.setRenderObjectFunction((e,s,i,r,n,o,a,l)=>{if((n.isMeshToonMaterial||n.isMeshToonNodeMaterial)&&!1===n.wireframe){const h=this._getOutlineMaterial(n);t.renderObject(e,s,i,r,h,o,a,l)}t.renderObject(e,s,i,r,n,o,a,l)}),super.updateBefore(e),t.setRenderObjectFunction(s)}_createMaterial(){const e=new gw;e.isMeshToonOutlineMaterial=!0,e.name="Toon_Outline",e.side=1;const t=ux.negate(),s=Sy.mul(Xy),i=Dd(1),r=s.mul(Hd(Jy,1)),n=s.mul(Hd(Jy.add(t),1)),o=Um(r.sub(n));return e.vertexNode=r.add(o.mul(this.thicknessNode).mul(r.w).mul(i)),e.colorNode=Hd(this.colorNode,this.alphaNode),e}_getOutlineMaterial(e){let t=this._materialCache.get(e);return void 0===t&&(t=this._createMaterial(),this._materialCache.set(e,t)),t}}const qA=Ed(([e,t])=>e.mul(t).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),XA=Ed(([e,t])=>(e=e.mul(t)).div(e.add(1)).clamp()).setLayout({name:"reinhardToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),YA=Ed(([e,t])=>{const s=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),i=e.mul(e.mul(6.2).add(1.7)).add(.06);return s.div(i).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),ZA=Ed(([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),s=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(s)}),QA=Ed(([e,t])=>{const s=Qd(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=Qd(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=s.mul(e),e=ZA(e),(e=i.mul(e)).clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),KA=Qd(Gd(1.6605,-.1246,-.0182),Gd(-.5876,1.1329,-.1006),Gd(-.0728,-.0083,1.1187)),JA=Qd(Gd(.6274,.0691,.0164),Gd(.3293,.9195,.088),Gd(.0433,.0113,.8956)),eN=Ed(([e])=>{const t=Gd(e).toVar(),s=Gd(t.mul(t)).toVar(),i=Gd(s.mul(s)).toVar();return Dd(15.5).mul(i.mul(s)).sub(Kp(40.14,i.mul(t))).add(Kp(31.96,i).sub(Kp(6.868,s.mul(t))).add(Kp(.4298,s).add(Kp(.1191,t).sub(.00232))))}),tN=Ed(([e,t])=>{const s=Gd(e).toVar(),i=Qd(Gd(.856627153315983,.137318972929847,.11189821299995),Gd(.0951212405381588,.761241990602591,.0767994186031903),Gd(.0482516061458583,.101439036467562,.811302368396859)),r=Qd(Gd(1.1271005818144368,-.1413297634984383,-.14132976349843826),Gd(-.11060664309660323,1.157823702216272,-.11060664309660294),Gd(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=Dd(-12.47393),o=Dd(4.026069);return s.mulAssign(t),s.assign(JA.mul(s)),s.assign(i.mul(s)),s.assign(df(s,1e-10)),s.assign(Fm(s)),s.assign(s.sub(n).div(o.sub(n))),s.assign(Nf(s,0,1)),s.assign(eN(s)),s.assign(r.mul(s)),s.assign(bf(df(Gd(0),s),Gd(2.2))),s.assign(KA.mul(s)),s.assign(Nf(s,0,1)),s}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),sN=Ed(([e,t])=>{const s=Dd(.76),i=Dd(.15);e=e.mul(t);const r=cf(e.r,cf(e.g,e.b)),n=kf(r.lessThan(.08),r.sub(Kp(6.25,r.mul(r))),.04);e.subAssign(n);const o=df(e.r,df(e.g,e.b));Pd(o.lessThan(s),()=>e);const a=Qp(1,s),l=Qp(1,a.mul(a).div(o.add(a.sub(s))));e.mulAssign(l.div(o));const h=Qp(1,Jp(1,i.mul(o.sub(l)).add(1)));return Af(e,Gd(l),h)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class iN extends Cc{static get type(){return"CodeNode"}constructor(e="",t=[],s=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=s}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const s of t)s.build(e);const s=e.getCodeFromNode(this,this.getNodeType(e));return s.code=this.code,s.code}serialize(e){super.serialize(e),e.code=this.code,e.language=this.language}deserialize(e){super.deserialize(e),this.code=e.code,this.language=e.language}}const rN=Td(iN).setParameterLength(1,3);class nN extends iN{static get type(){return"FunctionNode"}constructor(e="",t=[],s=""){super(e,t,s)}getNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){const s=this.getNodeType(e);return e.getStructTypeNode(s).getMemberType(e,t)}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let s=t.nodeFunction;return void 0===s&&(s=e.parser.parseFunction(this.code),t.nodeFunction=s),s}generate(e,t){super.generate(e);const s=this.getNodeFunction(e),i=s.name,r=s.type,n=e.getCodeFromNode(this,r);""!==i&&(n.name=i);const o=e.getPropertyName(n),a=this.getNodeFunction(e).getCode(o);return n.code=a+"\n","property"===t?o:e.format(`${o}()`,r,t)}}const oN=(e,t=[],s="")=>{for(let e=0;e<t.length;e++){const s=t[e];"function"==typeof s&&(t[e]=s.functionNode)}const i=new nN(e,t,s),r=(...e)=>i.call(...e);return r.functionNode=i,r};class aN extends Cc{static get type(){return"ScriptableValueNode"}constructor(e=null){super(),this._value=e,this._cache=null,this.inputType=null,this.outputType=null,this.events=new Ko,this.isScriptableValueNode=!0}get isScriptableOutputNode(){return null!==this.outputType}set value(e){this._value!==e&&(this._cache&&"URL"===this.inputType&&this.value.value instanceof ArrayBuffer&&(URL.revokeObjectURL(this._cache),this._cache=null),this._value=e,this.events.dispatchEvent({type:"change"}),this.refresh())}get value(){return this._value}refresh(){this.events.dispatchEvent({type:"refresh"})}getValue(){const e=this.value;if(e&&null===this._cache&&"URL"===this.inputType&&e.value instanceof ArrayBuffer)this._cache=URL.createObjectURL(new Blob([e.value]));else if(e&&null!==e.value&&void 0!==e.value&&(("URL"===this.inputType||"String"===this.inputType)&&"string"==typeof e.value||"Number"===this.inputType&&"number"==typeof e.value||"Vector2"===this.inputType&&e.value.isVector2||"Vector3"===this.inputType&&e.value.isVector3||"Vector4"===this.inputType&&e.value.isVector4||"Color"===this.inputType&&e.value.isColor||"Matrix3"===this.inputType&&e.value.isMatrix3||"Matrix4"===this.inputType&&e.value.isMatrix4))return e.value;return this._cache||e}getNodeType(e){return this.value&&this.value.isNode?this.value.getNodeType(e):"float"}setup(){return this.value&&this.value.isNode?this.value:Dd()}serialize(e){super.serialize(e),null!==this.value?"ArrayBuffer"===this.inputType?e.value=xc(this.value):e.value=this.value?this.value.toJSON(e.meta).uuid:null:e.value=null,e.inputType=this.inputType,e.outputType=this.outputType}deserialize(e){super.deserialize(e);let t=null;null!==e.value&&(t="ArrayBuffer"===e.inputType?bc(e.value):"Texture"===e.inputType?e.meta.textures[e.value]:e.meta.nodes[e.value]||null),this.value=t,this.inputType=e.inputType,this.outputType=e.outputType}}const lN=Td(aN).setParameterLength(1);class hN extends Map{get(e,t=null,...s){if(this.has(e))return super.get(e);if(null!==t){const i=t(...s);return this.set(e,i),i}}}class uN{constructor(e){this.scriptableNode=e}get parameters(){return this.scriptableNode.parameters}get layout(){return this.scriptableNode.getLayout()}getInputLayout(e){return this.scriptableNode.getInputLayout(e)}get(e){const t=this.parameters[e];return t?t.getValue():null}}const cN=new hN;class dN extends Cc{static get type(){return"ScriptableNode"}constructor(e=null,t={}){super(),this.codeNode=e,this.parameters=t,this._local=new hN,this._output=lN(null),this._outputs={},this._source=this.source,this._method=null,this._object=null,this._value=null,this._needsOutputUpdate=!0,this.onRefresh=this.onRefresh.bind(this),this.isScriptableNode=!0}get source(){return this.codeNode?this.codeNode.code:""}setLocal(e,t){return this._local.set(e,t)}getLocal(e){return this._local.get(e)}onRefresh(){this._refresh()}getInputLayout(e){for(const t of this.getLayout())if(t.inputType&&(t.id===e||t.name===e))return t}getOutputLayout(e){for(const t of this.getLayout())if(t.outputType&&(t.id===e||t.name===e))return t}setOutput(e,t){const s=this._outputs;return void 0===s[e]?s[e]=lN(t):s[e].value=t,this}getOutput(e){return this._outputs[e]}getParameter(e){return this.parameters[e]}setParameter(e,t){const s=this.parameters;return t&&t.isScriptableNode?(this.deleteParameter(e),s[e]=t,s[e].getDefaultOutput().events.addEventListener("refresh",this.onRefresh)):t&&t.isScriptableValueNode?(this.deleteParameter(e),s[e]=t,s[e].events.addEventListener("refresh",this.onRefresh)):void 0===s[e]?(s[e]=lN(t),s[e].events.addEventListener("refresh",this.onRefresh)):s[e].value=t,this}getValue(){return this.getDefaultOutput().getValue()}deleteParameter(e){let t=this.parameters[e];return t&&(t.isScriptableNode&&(t=t.getDefaultOutput()),t.events.removeEventListener("refresh",this.onRefresh)),this}clearParameters(){for(const e of Object.keys(this.parameters))this.deleteParameter(e);return this.needsUpdate=!0,this}call(e,...t){const s=this.getObject()[e];if("function"==typeof s)return s(...t)}async callAsync(e,...t){const s=this.getObject()[e];if("function"==typeof s)return"AsyncFunction"===s.constructor.name?await s(...t):s(...t)}getNodeType(e){return this.getDefaultOutputNode().getNodeType(e)}refresh(e=null){null!==e?this.getOutput(e).refresh():this._refresh()}getObject(){if(this.needsUpdate&&this.dispose(),null!==this._object)return this._object;const e=new uN(this),t=cN.get("THREE"),s=cN.get("TSL"),i=this.getMethod(),r=[e,this._local,cN,()=>this.refresh(),(e,t)=>this.setOutput(e,t),t,s];this._object=i(...r);const n=this._object.layout;if(n&&(!1===n.cache&&this._local.clear(),this._output.outputType=n.outputType||null,Array.isArray(n.elements)))for(const e of n.elements){const t=e.id||e.name;e.inputType&&(void 0===this.getParameter(t)&&this.setParameter(t,null),this.getParameter(t).inputType=e.inputType),e.outputType&&(void 0===this.getOutput(t)&&this.setOutput(t,null),this.getOutput(t).outputType=e.outputType)}return this._object}deserialize(e){super.deserialize(e);for(const e in this.parameters){let t=this.parameters[e];t.isScriptableNode&&(t=t.getDefaultOutput()),t.events.addEventListener("refresh",this.onRefresh)}}getLayout(){return this.getObject().layout}getDefaultOutputNode(){const e=this.getDefaultOutput().value;return e&&e.isNode?e:Dd()}getDefaultOutput(){return this._exec()._output}getMethod(){if(this.needsUpdate&&this.dispose(),null!==this._method)return this._method;const e=["layout","init","main","dispose"].join(", "),t="\nreturn { ...output, "+e+" };",s="var "+e+"; var output = {};\n"+this.codeNode.code+t;return this._method=new Function(...["parameters","local","global","refresh","setOutput","THREE","TSL"],s),this._method}dispose(){null!==this._method&&(this._object&&"function"==typeof this._object.dispose&&this._object.dispose(),this._method=null,this._object=null,this._source=null,this._value=null,this._needsOutputUpdate=!0,this._output.value=null,this._outputs={})}setup(){return this.getDefaultOutputNode()}getCacheKey(e){const t=[nc(this.source),this.getDefaultOutputNode().getCacheKey(e)];for(const s in this.parameters)t.push(this.parameters[s].getCacheKey(e));return oc(t)}set needsUpdate(e){!0===e&&this.dispose()}get needsUpdate(){return this.source!==this._source}_exec(){return null===this.codeNode||(!0===this._needsOutputUpdate&&(this._value=this.call("main"),this._needsOutputUpdate=!1),this._output.value=this._value),this}_refresh(){this.needsUpdate=!0,this._exec(),this._output.refresh()}}const pN=Td(dN).setParameterLength(1,2);function mN(e){let t;const s=e.context.getViewZ;return void 0!==s&&(t=s(this)),(t||ix.z).negate()}const fN=Ed(([e,t],s)=>{const i=mN(s);return Rf(e,t,i)}),gN=Ed(([e],t)=>{const s=mN(t);return e.mul(e,s,s).negate().exp().oneMinus()}),yN=Ed(([e,t])=>Hd(t.toFloat().mix(Sp.rgb,e.toVec3()),Sp.a));let xN=null,bN=null;class _N extends Cc{static get type(){return"RangeNode"}constructor(e=Dd(),t=Dd()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=this.getConstNode(this.minNode),s=this.getConstNode(this.maxNode),i=e.getTypeLength(fc(t.value)),r=e.getTypeLength(fc(s.value));return i>r?i:r}getNodeType(e){return e.object.count>1?e.getTypeFromLength(this.getVectorLength(e)):"float"}getConstNode(e){let t=null;if(e.traverse(e=>{!0===e.isConstNode&&(t=e)}),null===t)throw new Error('THREE.TSL: No "ConstNode" found in node graph.');return t}setup(e){const t=e.object;let s=null;if(t.count>1){const i=this.getConstNode(this.minNode),r=this.getConstNode(this.maxNode),n=i.value,o=r.value,a=e.getTypeLength(fc(n)),l=e.getTypeLength(fc(o));xN=xN||new Pa,bN=bN||new Pa,xN.setScalar(0),bN.setScalar(0),1===a?xN.setScalar(n):n.isColor?xN.set(n.r,n.g,n.b,1):xN.set(n.x,n.y,n.z||0,n.w||0),1===l?bN.setScalar(o):o.isColor?bN.set(o.r,o.g,o.b,1):bN.set(o.x,o.y,o.z||0,o.w||0);const h=4,u=h*t.count,c=new Float32Array(u);for(let e=0;e<u;e++){const t=e%h,s=xN.getComponent(t),i=bN.getComponent(t);c[e]=ha.lerp(s,i,Math.random())}const d=this.getNodeType(e);if(t.count<=4096)s=ry(c,"vec4",t.count).element(m_).convert(d);else{const t=new nu(c,4);e.geometry.setAttribute("__range"+this.id,t),s=vg(t).convert(d)}}else s=Dd(0);return s}}const wN=Td(_N).setParameterLength(2);class vN extends Cc{static get type(){return"ComputeBuiltinNode"}constructor(e,t){super(t),this._builtinName=e}getHash(e){return this.getBuiltinName(e)}getNodeType(){return this.nodeType}setBuiltinName(e){return this._builtinName=e,this}getBuiltinName(){return this._builtinName}hasBuiltin(e){return e.hasBuiltin(this._builtinName)}generate(e,t){const s=this.getBuiltinName(e),i=this.getNodeType(e);return"compute"===e.shaderStage?e.format(s,i,t):(Yo(`ComputeBuiltinNode: Compute built-in value ${s} can not be accessed in the ${e.shaderStage} stage`),e.generateConst(i))}serialize(e){super.serialize(e),e.global=this.global,e._builtinName=this._builtinName}deserialize(e){super.deserialize(e),this.global=e.global,this._builtinName=e._builtinName}}const TN=(e,t)=>new vN(e,t),SN=TN("numWorkgroups","uvec3"),MN=TN("workgroupId","uvec3"),AN=TN("globalId","uvec3"),NN=TN("localId","uvec3"),EN=TN("subgroupSize","uint");const CN=Td(class extends Cc{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:s}=e;!0===s.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}});class RN extends Rc{constructor(e,t){super(e,t),this.isWorkgroupInfoElementNode=!0}generate(e,t){let s;const i=e.context.assign;if(s=super.generate(e),!0!==i){const i=this.getNodeType(e);s=e.format(s,i,t)}return s}}class PN extends Cc{constructor(e,t,s=0){super(t),this.bufferType=t,this.bufferCount=s,this.isWorkgroupInfoNode=!0,this.elementType=t,this.scope=e,this.name=""}setName(e){return this.name=e,this}label(e){return Yo('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setScope(e){return this.scope=e,this}getElementType(){return this.elementType}getInputType(){return`${this.scope}Array`}element(e){return new RN(this,e)}generate(e){const t=""!==this.name?this.name:`${this.scope}Array_${this.id}`;return e.getScopedArray(t,this.scope.toLowerCase(),this.bufferType,this.bufferCount)}}class BN extends Cc{static get type(){return"AtomicFunctionNode"}constructor(e,t,s){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=s,this.parents=!0}getInputType(e){return this.pointerNode.getNodeType(e)}getNodeType(e){return this.getInputType(e)}generate(e){const t=e.getNodeProperties(this),s=t.parents,i=this.method,r=this.getNodeType(e),n=this.getInputType(e),o=this.pointerNode,a=this.valueNode,l=[];l.push(`&${o.build(e,n)}`),null!==a&&l.push(a.build(e,n));const h=`${e.getMethod(i,r)}( ${l.join(", ")} )`;if(!(!!s&&(1===s.length&&!0===s[0].isStackNode)))return void 0===t.constNode&&(t.constNode=Fg(h,r).toConst()),t.constNode.build(e);e.addLineFlowCode(h,this)}}BN.ATOMIC_LOAD="atomicLoad",BN.ATOMIC_STORE="atomicStore",BN.ATOMIC_ADD="atomicAdd",BN.ATOMIC_SUB="atomicSub",BN.ATOMIC_MAX="atomicMax",BN.ATOMIC_MIN="atomicMin",BN.ATOMIC_AND="atomicAnd",BN.ATOMIC_OR="atomicOr",BN.ATOMIC_XOR="atomicXor";const IN=Td(BN),DN=(e,t,s)=>IN(e,t,s).toStack();class LN extends Bc{static get type(){return"SubgroupFunctionNode"}constructor(e,t=null,s=null){super(),this.method=e,this.aNode=t,this.bNode=s}getInputType(e){const t=this.aNode?this.aNode.getNodeType(e):null,s=this.bNode?this.bNode.getNodeType(e):null;return(e.isMatrix(t)?0:e.getTypeLength(t))>(e.isMatrix(s)?0:e.getTypeLength(s))?t:s}getNodeType(e){const t=this.method;return t===LN.SUBGROUP_ELECT?"bool":t===LN.SUBGROUP_BALLOT?"uvec4":this.getInputType(e)}generate(e,t){const s=this.method,i=this.getNodeType(e),r=this.getInputType(e),n=this.aNode,o=this.bNode,a=[];if(s===LN.SUBGROUP_BROADCAST||s===LN.SUBGROUP_SHUFFLE||s===LN.QUAD_BROADCAST){const t=o.getNodeType(e);a.push(n.build(e,i),o.build(e,"float"===t?"int":i))}else s===LN.SUBGROUP_SHUFFLE_XOR||s===LN.SUBGROUP_SHUFFLE_DOWN||s===LN.SUBGROUP_SHUFFLE_UP?a.push(n.build(e,i),o.build(e,"uint")):(null!==n&&a.push(n.build(e,r)),null!==o&&a.push(o.build(e,r)));const l=0===a.length?"()":`( ${a.join(", ")} )`;return e.format(`${e.getMethod(s,i)}${l}`,i,t)}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}LN.SUBGROUP_ELECT="subgroupElect",LN.SUBGROUP_BALLOT="subgroupBallot",LN.SUBGROUP_ADD="subgroupAdd",LN.SUBGROUP_INCLUSIVE_ADD="subgroupInclusiveAdd",LN.SUBGROUP_EXCLUSIVE_AND="subgroupExclusiveAdd",LN.SUBGROUP_MUL="subgroupMul",LN.SUBGROUP_INCLUSIVE_MUL="subgroupInclusiveMul",LN.SUBGROUP_EXCLUSIVE_MUL="subgroupExclusiveMul",LN.SUBGROUP_AND="subgroupAnd",LN.SUBGROUP_OR="subgroupOr",LN.SUBGROUP_XOR="subgroupXor",LN.SUBGROUP_MIN="subgroupMin",LN.SUBGROUP_MAX="subgroupMax",LN.SUBGROUP_ALL="subgroupAll",LN.SUBGROUP_ANY="subgroupAny",LN.SUBGROUP_BROADCAST_FIRST="subgroupBroadcastFirst",LN.QUAD_SWAP_X="quadSwapX",LN.QUAD_SWAP_Y="quadSwapY",LN.QUAD_SWAP_DIAGONAL="quadSwapDiagonal",LN.SUBGROUP_BROADCAST="subgroupBroadcast",LN.SUBGROUP_SHUFFLE="subgroupShuffle",LN.SUBGROUP_SHUFFLE_XOR="subgroupShuffleXor",LN.SUBGROUP_SHUFFLE_UP="subgroupShuffleUp",LN.SUBGROUP_SHUFFLE_DOWN="subgroupShuffleDown",LN.QUAD_BROADCAST="quadBroadcast";const FN=Md(LN,LN.SUBGROUP_ELECT).setParameterLength(0),ON=Md(LN,LN.SUBGROUP_BALLOT).setParameterLength(1),VN=Md(LN,LN.SUBGROUP_ADD).setParameterLength(1),zN=Md(LN,LN.SUBGROUP_INCLUSIVE_ADD).setParameterLength(1),kN=Md(LN,LN.SUBGROUP_EXCLUSIVE_AND).setParameterLength(1),UN=Md(LN,LN.SUBGROUP_MUL).setParameterLength(1),GN=Md(LN,LN.SUBGROUP_INCLUSIVE_MUL).setParameterLength(1),jN=Md(LN,LN.SUBGROUP_EXCLUSIVE_MUL).setParameterLength(1),$N=Md(LN,LN.SUBGROUP_AND).setParameterLength(1),WN=Md(LN,LN.SUBGROUP_OR).setParameterLength(1),HN=Md(LN,LN.SUBGROUP_XOR).setParameterLength(1),qN=Md(LN,LN.SUBGROUP_MIN).setParameterLength(1),XN=Md(LN,LN.SUBGROUP_MAX).setParameterLength(1),YN=Md(LN,LN.SUBGROUP_ALL).setParameterLength(0),ZN=Md(LN,LN.SUBGROUP_ANY).setParameterLength(0),QN=Md(LN,LN.SUBGROUP_BROADCAST_FIRST).setParameterLength(2),KN=Md(LN,LN.QUAD_SWAP_X).setParameterLength(1),JN=Md(LN,LN.QUAD_SWAP_Y).setParameterLength(1),eE=Md(LN,LN.QUAD_SWAP_DIAGONAL).setParameterLength(1),tE=Md(LN,LN.SUBGROUP_BROADCAST).setParameterLength(2),sE=Md(LN,LN.SUBGROUP_SHUFFLE).setParameterLength(2),iE=Md(LN,LN.SUBGROUP_SHUFFLE_XOR).setParameterLength(2),rE=Md(LN,LN.SUBGROUP_SHUFFLE_UP).setParameterLength(2),nE=Md(LN,LN.SUBGROUP_SHUFFLE_DOWN).setParameterLength(2),oE=Md(LN,LN.QUAD_BROADCAST).setParameterLength(1);let aE;function lE(e){aE=aE||new WeakMap;let t=aE.get(e);return void 0===t&&aE.set(e,t={}),t}function hE(e){const t=lE(e);return t.shadowMatrix||(t.shadowMatrix=Up("mat4").setGroup(Vp).onRenderUpdate(t=>(!0===e.castShadow&&!1!==t.renderer.shadowMap.enabled||(e.shadow.camera.coordinateSystem!==t.camera.coordinateSystem&&(e.shadow.camera.coordinateSystem=t.camera.coordinateSystem,e.shadow.camera.updateProjectionMatrix()),e.shadow.updateMatrices(e)),e.shadow.matrix)))}function uE(e,t=tx){const s=hE(e).mul(t);return s.xyz.div(s.w)}function cE(e){const t=lE(e);return t.position||(t.position=Up(new da).setGroup(Vp).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(e.matrixWorld)))}function dE(e){const t=lE(e);return t.targetPosition||(t.targetPosition=Up(new da).setGroup(Vp).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(e.target.matrixWorld)))}function pE(e){const t=lE(e);return t.viewPosition||(t.viewPosition=Up(new da).setGroup(Vp).onRenderUpdate(({camera:t},s)=>{s.value=s.value||new da,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)}))}const mE=e=>Ay.transformDirection(cE(e).sub(dE(e))),fE=(e,t)=>{for(const s of t)if(s.isAnalyticLightNode&&s.light.id===e)return s;return null},gE=new WeakMap,yE=[];class xE extends Cc{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=sp("vec3","totalDiffuse"),this.totalSpecularNode=sp("vec3","totalSpecular"),this.outgoingLightNode=sp("vec3","outgoingLight"),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=this._lights;for(let t=0;t<e.length;t++){const s=e[t];if(yE.push(s.id),yE.push(s.castShadow?1:0),!0===s.isSpotLight){const e=null!==s.map?s.map.id:-1,t=s.colorNode?s.colorNode.getCacheKey():-1;yE.push(e,t)}}const t=oc(yE);return yE.length=0,t}getHash(e){if(null===this._lightNodesHash){null===this._lightNodes&&this.setupLightsNode(e);const t=[];for(const e of this._lightNodes)t.push(e.getHash());this._lightNodesHash="lights-"+t.join(",")}return this._lightNodesHash}analyze(e){const t=e.getNodeProperties(this);for(const s of t.nodes)s.build(e);t.outputNode.build(e)}setupLightsNode(e){const t=[],s=this._lightNodes,i=(e=>e.sort((e,t)=>e.id-t.id))(this._lights),r=e.renderer.library;for(const e of i)if(e.isNode)t.push(bd(e));else{let i=null;if(null!==s&&(i=fE(e.id,s)),null===i){const s=r.getLightNodeClass(e.constructor);if(null===s){Yo(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let i=null;gE.has(e)?i=gE.get(e):(i=new s(e),gE.set(e,i)),t.push(i)}}this._lightNodes=t}setupDirectLight(e,t,s){const{lightingModel:i,reflectedLight:r}=e.context;i.direct({...s,lightNode:t,reflectedLight:r},e)}setupDirectRectAreaLight(e,t,s){const{lightingModel:i,reflectedLight:r}=e.context;i.directRectArea({...s,lightNode:t,reflectedLight:r},e)}setupLights(e,t){for(const s of t)s.build(e)}getLightNodes(e){return null===this._lightNodes&&this.setupLightsNode(e),this._lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let s=this.outgoingLightNode;const i=e.context,r=i.lightingModel,n=e.getNodeProperties(this);if(r){const{totalDiffuseNode:t,totalSpecularNode:o}=this;i.outgoingLight=s;const a=e.addStack();n.nodes=a.nodes,r.start(e);const{backdrop:l,backdropAlpha:h}=i,{directDiffuse:u,directSpecular:c,indirectDiffuse:d,indirectSpecular:p}=i.reflectedLight;let m=u.add(d);null!==l&&(m=Gd(null!==h?h.mix(m,l):l)),t.assign(m),o.assign(c.add(p)),s.assign(t.add(o)),r.finish(e),s=s.bypass(e.removeStack())}else n.nodes=[];return e.lightsNode=t,s}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}class bE extends Cc{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=wc.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){_E.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||tx)}}const _E=sp("vec3","shadowPositionWorld");function wE(e,t){return t=function(e,t={}){return t.toneMapping=e.toneMapping,t.toneMappingExposure=e.toneMappingExposure,t.outputColorSpace=e.outputColorSpace,t.renderTarget=e.getRenderTarget(),t.activeCubeFace=e.getActiveCubeFace(),t.activeMipmapLevel=e.getActiveMipmapLevel(),t.renderObjectFunction=e.getRenderObjectFunction(),t.pixelRatio=e.getPixelRatio(),t.mrt=e.getMRT(),t.clearColor=e.getClearColor(t.clearColor||new eh),t.clearAlpha=e.getClearAlpha(),t.autoClear=e.autoClear,t.scissorTest=e.getScissorTest(),t}(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}const vE=new WeakMap,TE=Ed(({depthTexture:e,shadowCoord:t,depthLayer:s})=>{let i=ty(e,t.xy).setName("t_basic");return e.isArrayTexture&&(i=i.depth(s)),i.compare(t.z)}),SE=Ed(({depthTexture:e,shadowCoord:t,shadow:s,depthLayer:i})=>{const r=(t,s)=>{let r=ty(e,t);return e.isArrayTexture&&(r=r.depth(i)),r.compare(s)},n=Ox("mapSize","vec2",s).setGroup(Vp),o=Ox("radius","float",s).setGroup(Vp),a=Vd(1).div(n),l=o.mul(a.x),h=lA(fy.xy).mul(6.28318530718);return Zp(r(t.xy.add(hA(0,5,h).mul(l)),t.z),r(t.xy.add(hA(1,5,h).mul(l)),t.z),r(t.xy.add(hA(2,5,h).mul(l)),t.z),r(t.xy.add(hA(3,5,h).mul(l)),t.z),r(t.xy.add(hA(4,5,h).mul(l)),t.z)).mul(.2)}),ME=Ed(({depthTexture:e,shadowCoord:t,shadow:s,depthLayer:i})=>{const r=(t,s)=>{let r=ty(e,t);return e.isArrayTexture&&(r=r.depth(i)),r.compare(s)},n=Ox("mapSize","vec2",s).setGroup(Vp),o=Vd(1).div(n),a=o.x,l=o.y,h=t.xy,u=Gm(h.mul(n).add(.5));return h.subAssign(u.mul(o)),Zp(r(h,t.z),r(h.add(Vd(a,0)),t.z),r(h.add(Vd(0,l)),t.z),r(h.add(o),t.z),Af(r(h.add(Vd(a.negate(),0)),t.z),r(h.add(Vd(a.mul(2),0)),t.z),u.x),Af(r(h.add(Vd(a.negate(),l)),t.z),r(h.add(Vd(a.mul(2),l)),t.z),u.x),Af(r(h.add(Vd(0,l.negate())),t.z),r(h.add(Vd(0,l.mul(2))),t.z),u.y),Af(r(h.add(Vd(a,l.negate())),t.z),r(h.add(Vd(a,l.mul(2))),t.z),u.y),Af(Af(r(h.add(Vd(a.negate(),l.negate())),t.z),r(h.add(Vd(a.mul(2),l.negate())),t.z),u.x),Af(r(h.add(Vd(a.negate(),l.mul(2))),t.z),r(h.add(Vd(a.mul(2),l.mul(2))),t.z),u.x),u.y)).mul(1/9)}),AE=Ed(({depthTexture:e,shadowCoord:t,depthLayer:s})=>{let i=ty(e).sample(t.xy);e.isArrayTexture&&(i=i.depth(s)),i=i.rg;const r=i.x,n=df(1e-7,i.y.mul(i.y)),o=pf(t.z,r);Pd(o.equal(1),()=>Dd(1));const a=t.z.sub(r);let l=n.div(n.add(a.mul(a)));return l=Nf(Qp(l,.3).div(.65)),df(o,l)}),NE=Ed(([e,t,s])=>{let i=tx.sub(e).length();return i=i.sub(t).div(s.sub(t)),i=i.saturate(),i}),EE=e=>{let t=vE.get(e);if(void 0===t){const s=e.isPointLight?(e=>{const t=e.shadow.camera,s=Ox("near","float",t).setGroup(Vp),i=Ox("far","float",t).setGroup(Vp),r=Ly(e);return NE(r,s,i)})(e):null;t=new gw,t.colorNode=Hd(0,0,0,1),t.depthNode=s,t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.fog=!1,vE.set(e,t)}return t},CE=e=>{const t=vE.get(e);void 0!==t&&(t.dispose(),vE.delete(e))},RE=new aS,PE=[],BE=(e,t,s,i)=>{PE[0]=e,PE[1]=t;let r=RE.get(PE);return void 0!==r&&r.shadowType===s&&r.useVelocity===i||(r=(r,n,o,a,l,h,...u)=>{(!0===r.castShadow||r.receiveShadow&&3===s)&&(i&&(yc(r).useVelocity=!0),r.onBeforeShadow(e,r,o,t.camera,a,n.overrideMaterial,h),e.renderObject(r,n,o,a,l,h,...u),r.onAfterShadow(e,r,o,t.camera,a,n.overrideMaterial,h))},r.shadowType=s,r.useVelocity=i,RE.set(PE,r)),PE[0]=null,PE[1]=null,r},IE=Ed(({samples:e,radius:t,size:s,shadowPass:i,depthLayer:r})=>{const n=Dd(0).toVar("meanVertical"),o=Dd(0).toVar("squareMeanVertical"),a=e.lessThanEqual(Dd(1)).select(Dd(0),Dd(2).div(e.sub(1))),l=e.lessThanEqual(Dd(1)).select(Dd(0),Dd(-1));C_({start:Ld(0),end:Ld(e),type:"int",condition:"<"},({i:e})=>{const h=l.add(Dd(e).mul(a));let u=i.sample(Zp(fy.xy,Vd(0,h).mul(t)).div(s));i.value.isArrayTexture&&(u=u.depth(r)),u=u.x,n.addAssign(u),o.addAssign(u.mul(u))}),n.divAssign(e),o.divAssign(e);const h=Om(o.sub(n.mul(n)).max(0));return Vd(n,h)}),DE=Ed(({samples:e,radius:t,size:s,shadowPass:i,depthLayer:r})=>{const n=Dd(0).toVar("meanHorizontal"),o=Dd(0).toVar("squareMeanHorizontal"),a=e.lessThanEqual(Dd(1)).select(Dd(0),Dd(2).div(e.sub(1))),l=e.lessThanEqual(Dd(1)).select(Dd(0),Dd(-1));C_({start:Ld(0),end:Ld(e),type:"int",condition:"<"},({i:e})=>{const h=l.add(Dd(e).mul(a));let u=i.sample(Zp(fy.xy,Vd(h,0).mul(t)).div(s));i.value.isArrayTexture&&(u=u.depth(r)),n.addAssign(u.x),o.addAssign(Zp(u.y.mul(u.y),u.x.mul(u.x)))}),n.divAssign(e),o.divAssign(e);const h=Om(o.sub(n.mul(n)).max(0));return Vd(n,h)}),LE=[TE,SE,ME,AE];let FE;const OE=new tA;class VE extends bE{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._currentShadowType=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture:s,shadowCoord:i,shadow:r,depthLayer:n}){const o=i.x.greaterThanEqual(0).and(i.x.lessThanEqual(1)).and(i.y.greaterThanEqual(0)).and(i.y.lessThanEqual(1)).and(i.z.lessThanEqual(1)),a=t({depthTexture:s,shadowCoord:i,shadow:r,depthLayer:n});return o.select(a,Dd(1))}setupShadowCoord(e,t){const{shadow:s}=this,{renderer:i}=e,r=Ox("bias","float",s).setGroup(Vp);let n,o=t;if(s.camera.isOrthographicCamera||!0!==i.logarithmicDepthBuffer)o=o.xyz.div(o.w),n=o.z,i.coordinateSystem===Uo&&(n=n.mul(2).sub(1));else{const e=o.w;o=o.xy.div(e);const t=Ox("near","float",s.camera).setGroup(Vp),i=Ox("far","float",s.camera).setGroup(Vp);n=K_(e.negate(),t,i)}return o=Gd(o.x,o.y.oneMinus(),n.add(r)),o}getShadowFilterFn(e){return LE[e]}setupRenderTarget(e,t){const s=new _u(e.mapSize.width,e.mapSize.height);s.name="ShadowDepthTexture",s.compareFunction=Po;const i=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return i.texture.name="ShadowMap",i.texture.type=e.mapType,i.depthTexture=s,{shadowMap:i,depthTexture:s}}setupShadow(e){const{renderer:t,camera:s}=e,{light:i,shadow:r}=this,n=t.shadowMap.type,{depthTexture:o,shadowMap:a}=this.setupRenderTarget(r,e);if(r.camera.coordinateSystem=s.coordinateSystem,r.camera.updateProjectionMatrix(),3===n&&!0!==r.isPointLightShadow){o.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:kn,type:En,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:kn,type:En,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:kn,type:En,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:kn,type:En,depthBuffer:!1}));let t=ty(o);o.isArrayTexture&&(t=t.depth(this.depthLayer));let s=ty(this.vsmShadowMapVertical.texture);o.isArrayTexture&&(s=s.depth(this.depthLayer));const i=Ox("blurSamples","float",r).setGroup(Vp),n=Ox("radius","float",r).setGroup(Vp),l=Ox("mapSize","vec2",r).setGroup(Vp);let h=this.vsmMaterialVertical||(this.vsmMaterialVertical=new gw);h.fragmentNode=IE({samples:i,radius:n,size:l,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),h.name="VSMVertical",h=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new gw),h.fragmentNode=DE({samples:i,radius:n,size:l,shadowPass:s,depthLayer:this.depthLayer}).context(e.getSharedContext()),h.name="VSMHorizontal"}const l=Ox("intensity","float",r).setGroup(Vp),h=Ox("normalBias","float",r).setGroup(Vp),u=hE(i).mul(_E.add(fx.mul(h))),c=this.setupShadowCoord(e,u),d=r.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===d)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const p=3===n&&!0!==r.isPointLightShadow?this.vsmShadowMapHorizontal.texture:o,m=this.setupShadowFilter(e,{filterFn:d,shadowTexture:a.texture,depthTexture:p,shadowCoord:c,shadow:r,depthLayer:this.depthLayer});let f;a.texture.isCubeTexture?f=Dx(a.texture,c.xyz):(f=ty(a.texture,c),o.isArrayTexture&&(f=f.depth(this.depthLayer)));const g=Af(1,m.rgb.mix(f,1),l.mul(f.a)).toVar();this.shadowMap=a,this.shadow.map=a;const y=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return g.toInspector(`${y} / Color`,()=>this.shadowMap.texture.isCubeTexture?Dx(this.shadowMap.texture):ty(this.shadowMap.texture)).toInspector(`${y} / Depth`,()=>this.shadowMap.texture.isCubeTexture?Dx(this.shadowMap.texture).r.oneMinus():sy(this.shadowMap.depthTexture,qg().mul(Yg(ty(this.shadowMap.depthTexture)))).r.oneMinus())}setup(e){if(!1!==e.renderer.shadowMap.enabled)return Ed(()=>{const t=e.renderer.shadowMap.type;this._currentShadowType!==t&&(this._reset(),this._node=null);let s=this._node;return this.setupShadowPosition(e),null===s&&(this._node=s=this.setupShadow(e),this._currentShadowType=t),e.material.shadowNode&&Yo('NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.'),e.material.receivedShadowNode&&(s=e.material.receivedShadowNode(s)),s})()}renderShadow(e){const{shadow:t,shadowMap:s,light:i}=this,{renderer:r,scene:n}=e;t.updateMatrices(i),s.setSize(t.mapSize.width,t.mapSize.height,s.depth);const o=n.name;n.name=`Shadow Map [ ${i.name||"ID: "+i.id} ]`,r.render(n,t.camera),n.name=o}updateShadow(e){const{shadowMap:t,light:s,shadow:i}=this,{renderer:r,scene:n,camera:o}=e,a=r.shadowMap.type,l=t.depthTexture.version;this._depthVersionCached=l;const h=i.camera.layers.mask;4294967294&i.camera.layers.mask||(i.camera.layers.mask=o.layers.mask);const u=r.getRenderObjectFunction(),c=r.getMRT(),d=!!c&&c.has("velocity");FE=function(e,t,s){return s=function(e,t){return t=function(e,t={}){return t.background=e.background,t.backgroundNode=e.backgroundNode,t.overrideMaterial=e.overrideMaterial,t}(e,t),e.background=null,e.backgroundNode=null,e.overrideMaterial=null,t}(t,s=wE(e,s)),s}(r,n,FE),n.overrideMaterial=EE(s),r.setRenderObjectFunction(BE(r,i,a,d)),r.setClearColor(0,0),r.setRenderTarget(t),this.renderShadow(e),r.setRenderObjectFunction(u),3===a&&!0!==i.isPointLightShadow&&this.vsmPass(r),i.camera.layers.mask=h,function(e,t,s){!function(e,t){e.toneMapping=t.toneMapping,e.toneMappingExposure=t.toneMappingExposure,e.outputColorSpace=t.outputColorSpace,e.setRenderTarget(t.renderTarget,t.activeCubeFace,t.activeMipmapLevel),e.setRenderObjectFunction(t.renderObjectFunction),e.setPixelRatio(t.pixelRatio),e.setMRT(t.mrt),e.setClearColor(t.clearColor,t.clearAlpha),e.autoClear=t.autoClear,e.setScissorTest(t.scissorTest)}(e,s),function(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}(t,s)}(r,n,FE)}vsmPass(e){const{shadow:t}=this,s=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,s),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,s),e.setRenderTarget(this.vsmShadowMapVertical),OE.material=this.vsmMaterialVertical,OE.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),OE.material=this.vsmMaterialHorizontal,OE.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,CE(this.light),this.shadowMap&&(this.shadowMap.dispose(),this.shadowMap=null),null!==this.vsmShadowMapVertical&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),null!==this.vsmShadowMapHorizontal&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null)}updateBefore(e){const{shadow:t}=this;let s=t.needsUpdate||t.autoUpdate;s&&(this._cameraFrameId[e.camera]===e.frameId&&(s=!1),this._cameraFrameId[e.camera]=e.frameId),s&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const zE=(e,t)=>new VE(e,t),kE=new eh,UE=new ll,GE=new da,jE=new da,$E=[new da(1,0,0),new da(-1,0,0),new da(0,-1,0),new da(0,1,0),new da(0,0,1),new da(0,0,-1)],WE=[new da(0,-1,0),new da(0,-1,0),new da(0,0,-1),new da(0,0,1),new da(0,-1,0),new da(0,-1,0)],HE=[new da(1,0,0),new da(-1,0,0),new da(0,1,0),new da(0,-1,0),new da(0,0,1),new da(0,0,-1)],qE=[new da(0,-1,0),new da(0,-1,0),new da(0,0,1),new da(0,0,-1),new da(0,-1,0),new da(0,-1,0)],XE=Ed(({depthTexture:e,bd3D:t,dp:s})=>Dx(e,t).compare(s)),YE=Ed(({depthTexture:e,bd3D:t,dp:s,shadow:i})=>{const r=Ox("radius","float",i).setGroup(Vp),n=Ox("mapSize","vec2",i).setGroup(Vp),o=r.div(n.x),a=Ym(t),l=Um(xf(t,a.x.greaterThan(a.z).select(Gd(0,1,0),Gd(1,0,0)))),h=xf(t,l),u=lA(fy.xy).mul(6.28318530718),c=hA(0,5,u),d=hA(1,5,u),p=hA(2,5,u),m=hA(3,5,u),f=hA(4,5,u);return Dx(e,t.add(l.mul(c.x).add(h.mul(c.y)).mul(o))).compare(s).add(Dx(e,t.add(l.mul(d.x).add(h.mul(d.y)).mul(o))).compare(s)).add(Dx(e,t.add(l.mul(p.x).add(h.mul(p.y)).mul(o))).compare(s)).add(Dx(e,t.add(l.mul(m.x).add(h.mul(m.y)).mul(o))).compare(s)).add(Dx(e,t.add(l.mul(f.x).add(h.mul(f.y)).mul(o))).compare(s)).mul(.2)}),ZE=Ed(({filterFn:e,depthTexture:t,shadowCoord:s,shadow:i})=>{const r=s.xyz.toVar(),n=r.length(),o=Up("float").setGroup(Vp).onRenderUpdate(()=>i.camera.near),a=Up("float").setGroup(Vp).onRenderUpdate(()=>i.camera.far),l=Ox("bias","float",i).setGroup(Vp),h=Dd(1).toVar();return Pd(n.sub(a).lessThanEqual(0).and(n.sub(o).greaterThanEqual(0)),()=>{const s=n.sub(o).div(a.sub(o)).toVar();s.addAssign(l);const u=r.normalize();h.assign(e({depthTexture:t,bd3D:u,dp:s,shadow:i}))}),h});class QE extends VE{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return 0===e?XE:YE}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:s,shadowCoord:i,shadow:r}){return ZE({filterFn:t,depthTexture:s,shadowCoord:i,shadow:r})}setupRenderTarget(e,t){const s=new wu(e.mapSize.width);s.name="PointShadowDepthTexture",s.compareFunction=Po;const i=t.createCubeRenderTarget(e.mapSize.width);return i.texture.name="PointShadowMap",i.depthTexture=s,{shadowMap:i,depthTexture:s}}renderShadow(e){const{shadow:t,shadowMap:s,light:i}=this,{renderer:r,scene:n}=e,o=t.camera,a=t.matrix,l=r.coordinateSystem===Uo,h=l?$E:HE,u=l?WE:qE;s.setSize(t.mapSize.width,t.mapSize.width);const c=r.autoClear,d=r.getClearColor(kE),p=r.getClearAlpha();r.autoClear=!1,r.setClearColor(t.clearColor,t.clearAlpha);for(let e=0;e<6;e++){r.setRenderTarget(s,e),r.clear();const l=i.distance||o.far;l!==o.far&&(o.far=l,o.updateProjectionMatrix()),GE.setFromMatrixPosition(i.matrixWorld),o.position.copy(GE),jE.copy(o.position),jE.add(h[e]),o.up.copy(u[e]),o.lookAt(jE),o.updateMatrixWorld(),a.makeTranslation(-GE.x,-GE.y,-GE.z),UE.multiplyMatrices(o.projectionMatrix,o.matrixWorldInverse),t._frustum.setFromProjectionMatrix(UE,o.coordinateSystem,o.reversedDepth);const c=n.name;n.name=`Point Light Shadow [ ${i.name||"ID: "+i.id} ] - Face ${e+1}`,r.render(n,o),n.name=c}r.autoClear=c,r.setClearColor(d,p)}}const KE=(e,t)=>new QE(e,t);class JE extends F_{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new eh,this.colorNode=e&&e.colorNode||Up(this.color).setGroup(Vp),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=wc.FRAME,e&&e.shadow&&(this._shadowDisposeListener=()=>{this.disposeShadow()},e.addEventListener("dispose",this._shadowDisposeListener))}dispose(){this._shadowDisposeListener&&this.light.removeEventListener("dispose",this._shadowDisposeListener),super.dispose()}disposeShadow(){null!==this.shadowNode&&(this.shadowNode.dispose(),this.shadowNode=null),this.shadowColorNode=null,null!==this.baseColorNode&&(this.colorNode=this.baseColorNode,this.baseColorNode=null)}getHash(){return this.light.uuid}getLightVector(e){return pE(this.light).sub(e.context.positionView||ix)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return zE(this.light)}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let s=this.shadowColorNode;if(null===s){const e=this.light.shadow.shadowNode;let t;t=void 0!==e?bd(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=s=this.colorNode.mul(t),this.baseColorNode=this.colorNode}e.context.getShadow&&(s=e.context.getShadow(this,e)),this.colorNode=s}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):null!==this.shadowNode&&(this.shadowNode.dispose(),this.shadowNode=null,this.shadowColorNode=null);const t=this.setupDirect(e),s=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),s&&e.lightsNode.setupDirectRectAreaLight(e,this,s)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const eC=Ed(({lightDistance:e,cutoffDistance:t,decayExponent:s})=>{const i=e.pow(s).max(.01).reciprocal();return t.greaterThan(0).select(i.mul(e.div(t).pow4().oneMinus().clamp().pow2()),i)}),tC=({color:e,lightVector:t,cutoffDistance:s,decayExponent:i})=>{const r=t.normalize(),n=t.length(),o=eC({lightDistance:n,cutoffDistance:s,decayExponent:i});return{lightDirection:r,lightColor:e.mul(o)}};class sC extends JE{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=Up(0).setGroup(Vp),this.decayExponentNode=Up(2).setGroup(Vp)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return KE(this.light)}setupDirect(e){return tC({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const iC=Ed(([e=qg()])=>{const t=e.mul(2),s=t.x.floor(),i=t.y.floor();return s.add(i).mod(2).sign()}),rC=Ed(([e=qg()],{renderer:t,material:s})=>{const i=Mf(e.mul(2).sub(1));let r;if(s.alphaToCoverage&&t.currentSamples>0){const e=Dd(i.fwidth()).toVar();r=Rf(e.oneMinus(),e.add(1),i).oneMinus()}else r=kf(i.greaterThan(1),0,1);return r}),nC=Ed(([e,t,s])=>{const i=Dd(s).toVar(),r=Dd(t).toVar(),n=Od(e).toVar();return kf(n,r,i)}).setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),oC=Ed(([e,t])=>{const s=Od(t).toVar(),i=Dd(e).toVar();return kf(s,i.negate(),i)}).setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),aC=Ed(([e])=>{const t=Dd(e).toVar();return Ld(zm(t))}).setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),lC=Ed(([e,t])=>{const s=Dd(e).toVar();return t.assign(aC(s)),s.sub(Dd(t))}),hC=MM([Ed(([e,t,s,i,r,n])=>{const o=Dd(n).toVar(),a=Dd(r).toVar(),l=Dd(i).toVar(),h=Dd(s).toVar(),u=Dd(t).toVar(),c=Dd(e).toVar(),d=Dd(Qp(1,a)).toVar();return Qp(1,o).mul(c.mul(d).add(u.mul(a))).add(o.mul(h.mul(d).add(l.mul(a))))}).setLayout({name:"mx_bilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"}]}),Ed(([e,t,s,i,r,n])=>{const o=Dd(n).toVar(),a=Dd(r).toVar(),l=Gd(i).toVar(),h=Gd(s).toVar(),u=Gd(t).toVar(),c=Gd(e).toVar(),d=Dd(Qp(1,a)).toVar();return Qp(1,o).mul(c.mul(d).add(u.mul(a))).add(o.mul(h.mul(d).add(l.mul(a))))}).setLayout({name:"mx_bilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"}]})]),uC=MM([Ed(([e,t,s,i,r,n,o,a,l,h,u])=>{const c=Dd(u).toVar(),d=Dd(h).toVar(),p=Dd(l).toVar(),m=Dd(a).toVar(),f=Dd(o).toVar(),g=Dd(n).toVar(),y=Dd(r).toVar(),x=Dd(i).toVar(),b=Dd(s).toVar(),_=Dd(t).toVar(),w=Dd(e).toVar(),v=Dd(Qp(1,p)).toVar(),T=Dd(Qp(1,d)).toVar();return Dd(Qp(1,c)).toVar().mul(T.mul(w.mul(v).add(_.mul(p))).add(d.mul(b.mul(v).add(x.mul(p))))).add(c.mul(T.mul(y.mul(v).add(g.mul(p))).add(d.mul(f.mul(v).add(m.mul(p))))))}).setLayout({name:"mx_trilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"v4",type:"float"},{name:"v5",type:"float"},{name:"v6",type:"float"},{name:"v7",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]}),Ed(([e,t,s,i,r,n,o,a,l,h,u])=>{const c=Dd(u).toVar(),d=Dd(h).toVar(),p=Dd(l).toVar(),m=Gd(a).toVar(),f=Gd(o).toVar(),g=Gd(n).toVar(),y=Gd(r).toVar(),x=Gd(i).toVar(),b=Gd(s).toVar(),_=Gd(t).toVar(),w=Gd(e).toVar(),v=Dd(Qp(1,p)).toVar(),T=Dd(Qp(1,d)).toVar();return Dd(Qp(1,c)).toVar().mul(T.mul(w.mul(v).add(_.mul(p))).add(d.mul(b.mul(v).add(x.mul(p))))).add(c.mul(T.mul(y.mul(v).add(g.mul(p))).add(d.mul(f.mul(v).add(m.mul(p))))))}).setLayout({name:"mx_trilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"v4",type:"vec3"},{name:"v5",type:"vec3"},{name:"v6",type:"vec3"},{name:"v7",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]})]),cC=MM([Ed(([e,t,s])=>{const i=Dd(s).toVar(),r=Dd(t).toVar(),n=Fd(e).toVar(),o=Fd(n.bitAnd(Fd(7))).toVar(),a=Dd(nC(o.lessThan(Fd(4)),r,i)).toVar(),l=Dd(Kp(2,nC(o.lessThan(Fd(4)),i,r))).toVar();return oC(a,Od(o.bitAnd(Fd(1)))).add(oC(l,Od(o.bitAnd(Fd(2)))))}).setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),Ed(([e,t,s,i])=>{const r=Dd(i).toVar(),n=Dd(s).toVar(),o=Dd(t).toVar(),a=Fd(e).toVar(),l=Fd(a.bitAnd(Fd(15))).toVar(),h=Dd(nC(l.lessThan(Fd(8)),o,n)).toVar(),u=Dd(nC(l.lessThan(Fd(4)),n,nC(l.equal(Fd(12)).or(l.equal(Fd(14))),o,r))).toVar();return oC(h,Od(l.bitAnd(Fd(1)))).add(oC(u,Od(l.bitAnd(Fd(2)))))}).setLayout({name:"mx_gradient_float_1",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]})]),dC=MM([Ed(([e,t,s])=>{const i=Dd(s).toVar(),r=Dd(t).toVar(),n=$d(e).toVar();return Gd(cC(n.x,r,i),cC(n.y,r,i),cC(n.z,r,i))}).setLayout({name:"mx_gradient_vec3_0",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"}]}),Ed(([e,t,s,i])=>{const r=Dd(i).toVar(),n=Dd(s).toVar(),o=Dd(t).toVar(),a=$d(e).toVar();return Gd(cC(a.x,o,n,r),cC(a.y,o,n,r),cC(a.z,o,n,r))}).setLayout({name:"mx_gradient_vec3_1",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]})]),pC=Ed(([e])=>{const t=Dd(e).toVar();return Kp(.6616,t)}).setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),mC=Ed(([e])=>{const t=Dd(e).toVar();return Kp(.982,t)}).setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),fC=MM([pC,Ed(([e])=>{const t=Gd(e).toVar();return Kp(.6616,t)}).setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),gC=MM([mC,Ed(([e])=>{const t=Gd(e).toVar();return Kp(.982,t)}).setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),yC=Ed(([e,t])=>{const s=Ld(t).toVar(),i=Fd(e).toVar();return i.shiftLeft(s).bitOr(i.shiftRight(Ld(32).sub(s)))}).setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),xC=Ed(([e,t,s])=>{e.subAssign(s),e.bitXorAssign(yC(s,Ld(4))),s.addAssign(t),t.subAssign(e),t.bitXorAssign(yC(e,Ld(6))),e.addAssign(s),s.subAssign(t),s.bitXorAssign(yC(t,Ld(8))),t.addAssign(e),e.subAssign(s),e.bitXorAssign(yC(s,Ld(16))),s.addAssign(t),t.subAssign(e),t.bitXorAssign(yC(e,Ld(19))),e.addAssign(s),s.subAssign(t),s.bitXorAssign(yC(t,Ld(4))),t.addAssign(e)}),bC=Ed(([e,t,s])=>{const i=Fd(s).toVar(),r=Fd(t).toVar(),n=Fd(e).toVar();return i.bitXorAssign(r),i.subAssign(yC(r,Ld(14))),n.bitXorAssign(i),n.subAssign(yC(i,Ld(11))),r.bitXorAssign(n),r.subAssign(yC(n,Ld(25))),i.bitXorAssign(r),i.subAssign(yC(r,Ld(16))),n.bitXorAssign(i),n.subAssign(yC(i,Ld(4))),r.bitXorAssign(n),r.subAssign(yC(n,Ld(14))),i.bitXorAssign(r),i.subAssign(yC(r,Ld(24))),i}).setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),_C=Ed(([e])=>{const t=Fd(e).toVar();return Dd(t).div(Dd(Fd(Ld(4294967295))))}).setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),wC=Ed(([e])=>{const t=Dd(e).toVar();return t.mul(t).mul(t).mul(t.mul(t.mul(6).sub(15)).add(10))}).setLayout({name:"mx_fade",type:"float",inputs:[{name:"t",type:"float"}]}),vC=MM([Ed(([e])=>{const t=Ld(e).toVar(),s=Fd(Fd(1)).toVar(),i=Fd(Fd(Ld(3735928559)).add(s.shiftLeft(Fd(2))).add(Fd(13))).toVar();return bC(i.add(Fd(t)),i,i)}).setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),Ed(([e,t])=>{const s=Ld(t).toVar(),i=Ld(e).toVar(),r=Fd(Fd(2)).toVar(),n=Fd().toVar(),o=Fd().toVar(),a=Fd().toVar();return n.assign(o.assign(a.assign(Fd(Ld(3735928559)).add(r.shiftLeft(Fd(2))).add(Fd(13))))),n.addAssign(Fd(i)),o.addAssign(Fd(s)),bC(n,o,a)}).setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),Ed(([e,t,s])=>{const i=Ld(s).toVar(),r=Ld(t).toVar(),n=Ld(e).toVar(),o=Fd(Fd(3)).toVar(),a=Fd().toVar(),l=Fd().toVar(),h=Fd().toVar();return a.assign(l.assign(h.assign(Fd(Ld(3735928559)).add(o.shiftLeft(Fd(2))).add(Fd(13))))),a.addAssign(Fd(n)),l.addAssign(Fd(r)),h.addAssign(Fd(i)),bC(a,l,h)}).setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),Ed(([e,t,s,i])=>{const r=Ld(i).toVar(),n=Ld(s).toVar(),o=Ld(t).toVar(),a=Ld(e).toVar(),l=Fd(Fd(4)).toVar(),h=Fd().toVar(),u=Fd().toVar(),c=Fd().toVar();return h.assign(u.assign(c.assign(Fd(Ld(3735928559)).add(l.shiftLeft(Fd(2))).add(Fd(13))))),h.addAssign(Fd(a)),u.addAssign(Fd(o)),c.addAssign(Fd(n)),xC(h,u,c),h.addAssign(Fd(r)),bC(h,u,c)}).setLayout({name:"mx_hash_int_3",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"}]}),Ed(([e,t,s,i,r])=>{const n=Ld(r).toVar(),o=Ld(i).toVar(),a=Ld(s).toVar(),l=Ld(t).toVar(),h=Ld(e).toVar(),u=Fd(Fd(5)).toVar(),c=Fd().toVar(),d=Fd().toVar(),p=Fd().toVar();return c.assign(d.assign(p.assign(Fd(Ld(3735928559)).add(u.shiftLeft(Fd(2))).add(Fd(13))))),c.addAssign(Fd(h)),d.addAssign(Fd(l)),p.addAssign(Fd(a)),xC(c,d,p),c.addAssign(Fd(o)),d.addAssign(Fd(n)),bC(c,d,p)}).setLayout({name:"mx_hash_int_4",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"},{name:"yy",type:"int"}]})]),TC=MM([Ed(([e,t])=>{const s=Ld(t).toVar(),i=Ld(e).toVar(),r=Fd(vC(i,s)).toVar(),n=$d().toVar();return n.x.assign(r.bitAnd(Ld(255))),n.y.assign(r.shiftRight(Ld(8)).bitAnd(Ld(255))),n.z.assign(r.shiftRight(Ld(16)).bitAnd(Ld(255))),n}).setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),Ed(([e,t,s])=>{const i=Ld(s).toVar(),r=Ld(t).toVar(),n=Ld(e).toVar(),o=Fd(vC(n,r,i)).toVar(),a=$d().toVar();return a.x.assign(o.bitAnd(Ld(255))),a.y.assign(o.shiftRight(Ld(8)).bitAnd(Ld(255))),a.z.assign(o.shiftRight(Ld(16)).bitAnd(Ld(255))),a}).setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]})]),SC=MM([Ed(([e])=>{const t=Vd(e).toVar(),s=Ld().toVar(),i=Ld().toVar(),r=Dd(lC(t.x,s)).toVar(),n=Dd(lC(t.y,i)).toVar(),o=Dd(wC(r)).toVar(),a=Dd(wC(n)).toVar(),l=Dd(hC(cC(vC(s,i),r,n),cC(vC(s.add(Ld(1)),i),r.sub(1),n),cC(vC(s,i.add(Ld(1))),r,n.sub(1)),cC(vC(s.add(Ld(1)),i.add(Ld(1))),r.sub(1),n.sub(1)),o,a)).toVar();return fC(l)}).setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),Ed(([e])=>{const t=Gd(e).toVar(),s=Ld().toVar(),i=Ld().toVar(),r=Ld().toVar(),n=Dd(lC(t.x,s)).toVar(),o=Dd(lC(t.y,i)).toVar(),a=Dd(lC(t.z,r)).toVar(),l=Dd(wC(n)).toVar(),h=Dd(wC(o)).toVar(),u=Dd(wC(a)).toVar(),c=Dd(uC(cC(vC(s,i,r),n,o,a),cC(vC(s.add(Ld(1)),i,r),n.sub(1),o,a),cC(vC(s,i.add(Ld(1)),r),n,o.sub(1),a),cC(vC(s.add(Ld(1)),i.add(Ld(1)),r),n.sub(1),o.sub(1),a),cC(vC(s,i,r.add(Ld(1))),n,o,a.sub(1)),cC(vC(s.add(Ld(1)),i,r.add(Ld(1))),n.sub(1),o,a.sub(1)),cC(vC(s,i.add(Ld(1)),r.add(Ld(1))),n,o.sub(1),a.sub(1)),cC(vC(s.add(Ld(1)),i.add(Ld(1)),r.add(Ld(1))),n.sub(1),o.sub(1),a.sub(1)),l,h,u)).toVar();return gC(c)}).setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]})]),MC=MM([Ed(([e])=>{const t=Vd(e).toVar(),s=Ld().toVar(),i=Ld().toVar(),r=Dd(lC(t.x,s)).toVar(),n=Dd(lC(t.y,i)).toVar(),o=Dd(wC(r)).toVar(),a=Dd(wC(n)).toVar(),l=Gd(hC(dC(TC(s,i),r,n),dC(TC(s.add(Ld(1)),i),r.sub(1),n),dC(TC(s,i.add(Ld(1))),r,n.sub(1)),dC(TC(s.add(Ld(1)),i.add(Ld(1))),r.sub(1),n.sub(1)),o,a)).toVar();return fC(l)}).setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),Ed(([e])=>{const t=Gd(e).toVar(),s=Ld().toVar(),i=Ld().toVar(),r=Ld().toVar(),n=Dd(lC(t.x,s)).toVar(),o=Dd(lC(t.y,i)).toVar(),a=Dd(lC(t.z,r)).toVar(),l=Dd(wC(n)).toVar(),h=Dd(wC(o)).toVar(),u=Dd(wC(a)).toVar(),c=Gd(uC(dC(TC(s,i,r),n,o,a),dC(TC(s.add(Ld(1)),i,r),n.sub(1),o,a),dC(TC(s,i.add(Ld(1)),r),n,o.sub(1),a),dC(TC(s.add(Ld(1)),i.add(Ld(1)),r),n.sub(1),o.sub(1),a),dC(TC(s,i,r.add(Ld(1))),n,o,a.sub(1)),dC(TC(s.add(Ld(1)),i,r.add(Ld(1))),n.sub(1),o,a.sub(1)),dC(TC(s,i.add(Ld(1)),r.add(Ld(1))),n,o.sub(1),a.sub(1)),dC(TC(s.add(Ld(1)),i.add(Ld(1)),r.add(Ld(1))),n.sub(1),o.sub(1),a.sub(1)),l,h,u)).toVar();return gC(c)}).setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]})]),AC=MM([Ed(([e])=>{const t=Dd(e).toVar(),s=Ld(aC(t)).toVar();return _C(vC(s))}).setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),Ed(([e])=>{const t=Vd(e).toVar(),s=Ld(aC(t.x)).toVar(),i=Ld(aC(t.y)).toVar();return _C(vC(s,i))}).setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),Ed(([e])=>{const t=Gd(e).toVar(),s=Ld(aC(t.x)).toVar(),i=Ld(aC(t.y)).toVar(),r=Ld(aC(t.z)).toVar();return _C(vC(s,i,r))}).setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),Ed(([e])=>{const t=Hd(e).toVar(),s=Ld(aC(t.x)).toVar(),i=Ld(aC(t.y)).toVar(),r=Ld(aC(t.z)).toVar(),n=Ld(aC(t.w)).toVar();return _C(vC(s,i,r,n))}).setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]})]),NC=MM([Ed(([e])=>{const t=Dd(e).toVar(),s=Ld(aC(t)).toVar();return Gd(_C(vC(s,Ld(0))),_C(vC(s,Ld(1))),_C(vC(s,Ld(2))))}).setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),Ed(([e])=>{const t=Vd(e).toVar(),s=Ld(aC(t.x)).toVar(),i=Ld(aC(t.y)).toVar();return Gd(_C(vC(s,i,Ld(0))),_C(vC(s,i,Ld(1))),_C(vC(s,i,Ld(2))))}).setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),Ed(([e])=>{const t=Gd(e).toVar(),s=Ld(aC(t.x)).toVar(),i=Ld(aC(t.y)).toVar(),r=Ld(aC(t.z)).toVar();return Gd(_C(vC(s,i,r,Ld(0))),_C(vC(s,i,r,Ld(1))),_C(vC(s,i,r,Ld(2))))}).setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),Ed(([e])=>{const t=Hd(e).toVar(),s=Ld(aC(t.x)).toVar(),i=Ld(aC(t.y)).toVar(),r=Ld(aC(t.z)).toVar(),n=Ld(aC(t.w)).toVar();return Gd(_C(vC(s,i,r,n,Ld(0))),_C(vC(s,i,r,n,Ld(1))),_C(vC(s,i,r,n,Ld(2))))}).setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]})]),EC=Ed(([e,t,s,i])=>{const r=Dd(i).toVar(),n=Dd(s).toVar(),o=Ld(t).toVar(),a=Gd(e).toVar(),l=Dd(0).toVar(),h=Dd(1).toVar();return C_(o,()=>{l.addAssign(h.mul(SC(a))),h.mulAssign(r),a.mulAssign(n)}),l}).setLayout({name:"mx_fractal_noise_float",type:"float",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),CC=Ed(([e,t,s,i])=>{const r=Dd(i).toVar(),n=Dd(s).toVar(),o=Ld(t).toVar(),a=Gd(e).toVar(),l=Gd(0).toVar(),h=Dd(1).toVar();return C_(o,()=>{l.addAssign(h.mul(MC(a))),h.mulAssign(r),a.mulAssign(n)}),l}).setLayout({name:"mx_fractal_noise_vec3",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),RC=Ed(([e,t,s,i])=>{const r=Dd(i).toVar(),n=Dd(s).toVar(),o=Ld(t).toVar(),a=Gd(e).toVar();return Vd(EC(a,o,n,r),EC(a.add(Gd(Ld(19),Ld(193),Ld(17))),o,n,r))}).setLayout({name:"mx_fractal_noise_vec2",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),PC=Ed(([e,t,s,i])=>{const r=Dd(i).toVar(),n=Dd(s).toVar(),o=Ld(t).toVar(),a=Gd(e).toVar(),l=Gd(CC(a,o,n,r)).toVar(),h=Dd(EC(a.add(Gd(Ld(19),Ld(193),Ld(17))),o,n,r)).toVar();return Hd(l,h)}).setLayout({name:"mx_fractal_noise_vec4",type:"vec4",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),BC=MM([Ed(([e,t,s,i,r,n,o])=>{const a=Ld(o).toVar(),l=Dd(n).toVar(),h=Ld(r).toVar(),u=Ld(i).toVar(),c=Ld(s).toVar(),d=Ld(t).toVar(),p=Vd(e).toVar(),m=Gd(NC(Vd(d.add(u),c.add(h)))).toVar(),f=Vd(m.x,m.y).toVar();f.subAssign(.5),f.mulAssign(l),f.addAssign(.5);const g=Vd(Vd(Dd(d),Dd(c)).add(f)).toVar(),y=Vd(g.sub(p)).toVar();return Pd(a.equal(Ld(2)),()=>Ym(y.x).add(Ym(y.y))),Pd(a.equal(Ld(3)),()=>df(Ym(y.x),Ym(y.y))),yf(y,y)}).setLayout({name:"mx_worley_distance_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),Ed(([e,t,s,i,r,n,o,a,l])=>{const h=Ld(l).toVar(),u=Dd(a).toVar(),c=Ld(o).toVar(),d=Ld(n).toVar(),p=Ld(r).toVar(),m=Ld(i).toVar(),f=Ld(s).toVar(),g=Ld(t).toVar(),y=Gd(e).toVar(),x=Gd(NC(Gd(g.add(p),f.add(d),m.add(c)))).toVar();x.subAssign(.5),x.mulAssign(u),x.addAssign(.5);const b=Gd(Gd(Dd(g),Dd(f),Dd(m)).add(x)).toVar(),_=Gd(b.sub(y)).toVar();return Pd(h.equal(Ld(2)),()=>Ym(_.x).add(Ym(_.y)).add(Ym(_.z))),Pd(h.equal(Ld(3)),()=>df(Ym(_.x),Ym(_.y),Ym(_.z))),yf(_,_)}).setLayout({name:"mx_worley_distance_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"zoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),IC=Ed(([e,t,s])=>{const i=Ld(s).toVar(),r=Dd(t).toVar(),n=Vd(e).toVar(),o=Ld().toVar(),a=Ld().toVar(),l=Vd(lC(n.x,o),lC(n.y,a)).toVar(),h=Dd(1e6).toVar();return C_({start:-1,end:Ld(1),name:"x",condition:"<="},({x:e})=>{C_({start:-1,end:Ld(1),name:"y",condition:"<="},({y:t})=>{const s=Dd(BC(l,e,t,o,a,r,i)).toVar();h.assign(cf(h,s))})}),Pd(i.equal(Ld(0)),()=>{h.assign(Om(h))}),h}).setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),DC=Ed(([e,t,s])=>{const i=Ld(s).toVar(),r=Dd(t).toVar(),n=Vd(e).toVar(),o=Ld().toVar(),a=Ld().toVar(),l=Vd(lC(n.x,o),lC(n.y,a)).toVar(),h=Vd(1e6,1e6).toVar();return C_({start:-1,end:Ld(1),name:"x",condition:"<="},({x:e})=>{C_({start:-1,end:Ld(1),name:"y",condition:"<="},({y:t})=>{const s=Dd(BC(l,e,t,o,a,r,i)).toVar();Pd(s.lessThan(h.x),()=>{h.y.assign(h.x),h.x.assign(s)}).ElseIf(s.lessThan(h.y),()=>{h.y.assign(s)})})}),Pd(i.equal(Ld(0)),()=>{h.assign(Om(h))}),h}).setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),LC=Ed(([e,t,s])=>{const i=Ld(s).toVar(),r=Dd(t).toVar(),n=Vd(e).toVar(),o=Ld().toVar(),a=Ld().toVar(),l=Vd(lC(n.x,o),lC(n.y,a)).toVar(),h=Gd(1e6,1e6,1e6).toVar();return C_({start:-1,end:Ld(1),name:"x",condition:"<="},({x:e})=>{C_({start:-1,end:Ld(1),name:"y",condition:"<="},({y:t})=>{const s=Dd(BC(l,e,t,o,a,r,i)).toVar();Pd(s.lessThan(h.x),()=>{h.z.assign(h.y),h.y.assign(h.x),h.x.assign(s)}).ElseIf(s.lessThan(h.y),()=>{h.z.assign(h.y),h.y.assign(s)}).ElseIf(s.lessThan(h.z),()=>{h.z.assign(s)})})}),Pd(i.equal(Ld(0)),()=>{h.assign(Om(h))}),h}).setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),FC=MM([IC,Ed(([e,t,s])=>{const i=Ld(s).toVar(),r=Dd(t).toVar(),n=Gd(e).toVar(),o=Ld().toVar(),a=Ld().toVar(),l=Ld().toVar(),h=Gd(lC(n.x,o),lC(n.y,a),lC(n.z,l)).toVar(),u=Dd(1e6).toVar();return C_({start:-1,end:Ld(1),name:"x",condition:"<="},({x:e})=>{C_({start:-1,end:Ld(1),name:"y",condition:"<="},({y:t})=>{C_({start:-1,end:Ld(1),name:"z",condition:"<="},({z:s})=>{const n=Dd(BC(h,e,t,s,o,a,l,r,i)).toVar();u.assign(cf(u,n))})})}),Pd(i.equal(Ld(0)),()=>{u.assign(Om(u))}),u}).setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),OC=MM([DC,Ed(([e,t,s])=>{const i=Ld(s).toVar(),r=Dd(t).toVar(),n=Gd(e).toVar(),o=Ld().toVar(),a=Ld().toVar(),l=Ld().toVar(),h=Gd(lC(n.x,o),lC(n.y,a),lC(n.z,l)).toVar(),u=Vd(1e6,1e6).toVar();return C_({start:-1,end:Ld(1),name:"x",condition:"<="},({x:e})=>{C_({start:-1,end:Ld(1),name:"y",condition:"<="},({y:t})=>{C_({start:-1,end:Ld(1),name:"z",condition:"<="},({z:s})=>{const n=Dd(BC(h,e,t,s,o,a,l,r,i)).toVar();Pd(n.lessThan(u.x),()=>{u.y.assign(u.x),u.x.assign(n)}).ElseIf(n.lessThan(u.y),()=>{u.y.assign(n)})})})}),Pd(i.equal(Ld(0)),()=>{u.assign(Om(u))}),u}).setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),VC=MM([LC,Ed(([e,t,s])=>{const i=Ld(s).toVar(),r=Dd(t).toVar(),n=Gd(e).toVar(),o=Ld().toVar(),a=Ld().toVar(),l=Ld().toVar(),h=Gd(lC(n.x,o),lC(n.y,a),lC(n.z,l)).toVar(),u=Gd(1e6,1e6,1e6).toVar();return C_({start:-1,end:Ld(1),name:"x",condition:"<="},({x:e})=>{C_({start:-1,end:Ld(1),name:"y",condition:"<="},({y:t})=>{C_({start:-1,end:Ld(1),name:"z",condition:"<="},({z:s})=>{const n=Dd(BC(h,e,t,s,o,a,l,r,i)).toVar();Pd(n.lessThan(u.x),()=>{u.z.assign(u.y),u.y.assign(u.x),u.x.assign(n)}).ElseIf(n.lessThan(u.y),()=>{u.z.assign(u.y),u.y.assign(n)}).ElseIf(n.lessThan(u.z),()=>{u.z.assign(n)})})})}),Pd(i.equal(Ld(0)),()=>{u.assign(Om(u))}),u}).setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),zC=Ed(([e,t,s,i,r,n,o,a,l,h,u])=>{const c=Ld(e).toVar(),d=Vd(t).toVar(),p=Vd(s).toVar(),m=Vd(i).toVar(),f=Dd(r).toVar(),g=Dd(n).toVar(),y=Dd(o).toVar(),x=Od(a).toVar(),b=Ld(l).toVar(),_=Dd(h).toVar(),w=Dd(u).toVar(),v=d.mul(p).add(m),T=Dd(0).toVar();return Pd(c.equal(Ld(0)),()=>{T.assign(MC(v))}),Pd(c.equal(Ld(1)),()=>{T.assign(NC(v))}),Pd(c.equal(Ld(2)),()=>{T.assign(VC(v,f,Ld(0)))}),Pd(c.equal(Ld(3)),()=>{T.assign(CC(Gd(v,0),b,_,w))}),T.assign(T.mul(y.sub(g)).add(g)),Pd(x,()=>{T.assign(Nf(T,g,y))}),T}).setLayout({name:"mx_unifiednoise2d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"texcoord",type:"vec2"},{name:"freq",type:"vec2"},{name:"offset",type:"vec2"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),kC=Ed(([e,t,s,i,r,n,o,a,l,h,u])=>{const c=Ld(e).toVar(),d=Gd(t).toVar(),p=Gd(s).toVar(),m=Gd(i).toVar(),f=Dd(r).toVar(),g=Dd(n).toVar(),y=Dd(o).toVar(),x=Od(a).toVar(),b=Ld(l).toVar(),_=Dd(h).toVar(),w=Dd(u).toVar(),v=d.mul(p).add(m),T=Dd(0).toVar();return Pd(c.equal(Ld(0)),()=>{T.assign(MC(v))}),Pd(c.equal(Ld(1)),()=>{T.assign(NC(v))}),Pd(c.equal(Ld(2)),()=>{T.assign(VC(v,f,Ld(0)))}),Pd(c.equal(Ld(3)),()=>{T.assign(CC(v,b,_,w))}),T.assign(T.mul(y.sub(g)).add(g)),Pd(x,()=>{T.assign(Nf(T,g,y))}),T}).setLayout({name:"mx_unifiednoise3d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"position",type:"vec3"},{name:"freq",type:"vec3"},{name:"offset",type:"vec3"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),UC=Ed(([e])=>{const t=e.y,s=e.z,i=Gd().toVar();return Pd(t.lessThan(1e-4),()=>{i.assign(Gd(s,s,s))}).Else(()=>{let r=e.x;r=r.sub(zm(r)).mul(6).toVar();const n=Ld(nf(r)),o=r.sub(Dd(n)),a=s.mul(t.oneMinus()),l=s.mul(t.mul(o).oneMinus()),h=s.mul(t.mul(o.oneMinus()).oneMinus());Pd(n.equal(Ld(0)),()=>{i.assign(Gd(s,h,a))}).ElseIf(n.equal(Ld(1)),()=>{i.assign(Gd(l,s,a))}).ElseIf(n.equal(Ld(2)),()=>{i.assign(Gd(a,s,h))}).ElseIf(n.equal(Ld(3)),()=>{i.assign(Gd(a,l,s))}).ElseIf(n.equal(Ld(4)),()=>{i.assign(Gd(h,a,s))}).Else(()=>{i.assign(Gd(s,a,l))})}),i}).setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),GC=Ed(([e])=>{const t=Gd(e).toVar(),s=Dd(t.x).toVar(),i=Dd(t.y).toVar(),r=Dd(t.z).toVar(),n=Dd(cf(s,cf(i,r))).toVar(),o=Dd(df(s,df(i,r))).toVar(),a=Dd(o.sub(n)).toVar(),l=Dd().toVar(),h=Dd().toVar(),u=Dd().toVar();return u.assign(o),Pd(o.greaterThan(0),()=>{h.assign(a.div(o))}).Else(()=>{h.assign(0)}),Pd(h.lessThanEqual(0),()=>{l.assign(0)}).Else(()=>{Pd(s.greaterThanEqual(o),()=>{l.assign(i.sub(r).div(a))}).ElseIf(i.greaterThanEqual(o),()=>{l.assign(Zp(2,r.sub(s).div(a)))}).Else(()=>{l.assign(Zp(4,s.sub(i).div(a)))}),l.mulAssign(1/6),Pd(l.lessThan(0),()=>{l.addAssign(1)})}),Gd(l,h,u)}).setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]}),jC=Ed(([e])=>{const t=Gd(e).toVar(),s=Wd(rm(t,Gd(.04045))).toVar(),i=Gd(t.div(12.92)).toVar(),r=Gd(bf(df(t.add(Gd(.055)),Gd(0)).div(1.055),Gd(2.4))).toVar();return Af(i,r,s)}).setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),$C=(e,t)=>{e=Dd(e),t=Dd(t);const s=Vd(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return Rf(e.sub(s),e.add(s),t)},WC=(e,t,s,i)=>Af(e,t,s[i].clamp()),HC=(e,t,s,i,r)=>Af(e,t,$C(s,i[r])),qC=Ed(([e,t,s])=>{const i=Um(e).toVar(),r=Qp(Dd(.5).mul(t.sub(s)),tx).div(i).toVar(),n=Qp(Dd(-.5).mul(t.sub(s)),tx).div(i).toVar(),o=Gd().toVar();o.x=i.x.greaterThan(Dd(0)).select(r.x,n.x),o.y=i.y.greaterThan(Dd(0)).select(r.y,n.y),o.z=i.z.greaterThan(Dd(0)).select(r.z,n.z);const a=cf(o.x,o.y,o.z).toVar();return tx.add(i.mul(a)).toVar().sub(s)}),XC=Ed(([e,t])=>{const s=e.x,i=e.y,r=e.z;let n=t.element(0).mul(.886227);return n=n.add(t.element(1).mul(1.023328).mul(i)),n=n.add(t.element(2).mul(1.023328).mul(r)),n=n.add(t.element(3).mul(1.023328).mul(s)),n=n.add(t.element(4).mul(.858086).mul(s).mul(i)),n=n.add(t.element(5).mul(.858086).mul(i).mul(r)),n=n.add(t.element(6).mul(r.mul(r).mul(.743125).sub(.247708))),n=n.add(t.element(7).mul(.858086).mul(s).mul(r)),n=n.add(t.element(8).mul(.429043).mul(Kp(s,s).sub(Kp(i,i)))),n});var YC=Object.freeze({__proto__:null,BRDF_GGX:tv,BRDF_Lambert:kw,BasicPointShadowFilter:XE,BasicShadowFilter:TE,Break:R_,Const:Qf,Continue:()=>Fg("continue").toStack(),DFGLUT:rv,D_GGX:Kw,Discard:Og,EPSILON:Tm,F_Schlick:zw,Fn:Ed,HALF_PI:Em,INFINITY:Sm,If:Pd,Loop:C_,NodeAccess:vc,NodeShaderStage:_c,NodeType:{BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},NodeUpdateType:wc,OnBeforeMaterialUpdate:e=>dA(cA.BEFORE_MATERIAL,e),OnBeforeObjectUpdate:e=>dA(cA.BEFORE_OBJECT,e),OnMaterialUpdate:e=>dA(cA.MATERIAL,e),OnObjectUpdate:e=>dA(cA.OBJECT,e),PCFShadowFilter:SE,PCFSoftShadowFilter:ME,PI:Mm,PI2:Am,PointShadowFilter:YE,Return:()=>Fg("return").toStack(),Schlick_to_F0:av,ScriptableNodeResources:cN,ShaderNode:xd,Stack:Bd,Switch:(...e)=>Gc.Switch(...e),TBNViewMatrix:ub,TWO_PI:Nm,VSMShadowFilter:AE,V_GGX_SmithCorrelated:Zw,Var:Zf,VarIntent:Kf,abs:Ym,acesFilmicToneMapping:QA,acos:qm,add:Zp,addMethodChaining:$c,addNodeElement:function(e){Yo("TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add",e)},agxToneMapping:tN,all:Cm,alphaT:gp,and:am,anisotropy:yp,anisotropyB:bp,anisotropyT:xp,any:Rm,append:e=>(Yo("TSL: append() has been renamed to Stack()."),Bd(e)),array:jp,arrayBuffer:e=>new kc(e,"ArrayBuffer"),asin:Hm,assign:Wp,atan:Xm,atan2:Ff,atomicAdd:(e,t)=>DN(BN.ATOMIC_ADD,e,t),atomicAnd:(e,t)=>DN(BN.ATOMIC_AND,e,t),atomicFunc:DN,atomicLoad:e=>DN(BN.ATOMIC_LOAD,e,null),atomicMax:(e,t)=>DN(BN.ATOMIC_MAX,e,t),atomicMin:(e,t)=>DN(BN.ATOMIC_MIN,e,t),atomicOr:(e,t)=>DN(BN.ATOMIC_OR,e,t),atomicStore:(e,t)=>DN(BN.ATOMIC_STORE,e,t),atomicSub:(e,t)=>DN(BN.ATOMIC_SUB,e,t),atomicXor:(e,t)=>DN(BN.ATOMIC_XOR,e,t),attenuationColor:Bp,attenuationDistance:Pp,attribute:Hg,attributeArray:(e,t="float")=>{let s,i;!0===t.isStruct?(s=t.layout.getLength(),i=cc("float")):(s=dc(t),i=cc(t));const r=new mA(e,s,i);return c_(r,t,e)},backgroundBlurriness:_A,backgroundIntensity:wA,backgroundRotation:vA,batch:S_,bentNormalView:db,billboarding:PM,bitAnd:cm,bitNot:dm,bitOr:pm,bitXor:mm,bitangentGeometry:ob,bitangentLocal:ab,bitangentView:lb,bitangentWorld:hb,bitcast:iM,blendBurn:hw,blendColor:pw,blendDodge:uw,blendOverlay:dw,blendScreen:cw,blur:oT,bool:Od,buffer:ry,bufferAttribute:wg,builtin:ly,builtinAOContext:Hf,builtinShadowContext:Wf,bumpMap:_b,burn:(...e)=>(Yo('TSL: "burn" has been renamed. Use "blendBurn" instead.'),hw(e)),bvec2:Ud,bvec3:Wd,bvec4:Yd,bypass:Pg,cache:Cg,call:qp,cameraFar:Ty,cameraIndex:wy,cameraNear:vy,cameraNormalMatrix:Ey,cameraPosition:Cy,cameraProjectionMatrix:Sy,cameraProjectionMatrixInverse:My,cameraViewMatrix:Ay,cameraViewport:Ry,cameraWorldMatrix:Ny,cbrt:Sf,cdl:zA,ceil:km,checker:iC,cineonToneMapping:YA,clamp:Nf,clearcoat:hp,clearcoatNormalView:gx,clearcoatRoughness:up,code:rN,color:Id,colorSpaceToWorking:hg,colorToDirection:e=>bd(e).mul(2).sub(1),compute:Ag,computeKernel:Mg,computeSkinning:(e,t=null)=>{const s=new A_(e);return s.positionNode=c_(new nu(e.geometry.getAttribute("position").array,3),"vec3").setPBO(!0).toReadOnly().element(m_).toVar(),s.skinIndexNode=c_(new nu(new Uint32Array(e.geometry.getAttribute("skinIndex").array),4),"uvec4").setPBO(!0).toReadOnly().element(m_).toVar(),s.skinWeightNode=c_(new nu(e.geometry.getAttribute("skinWeight").array,4),"vec4").setPBO(!0).toReadOnly().element(m_).toVar(),s.bindMatrixNode=Up(e.bindMatrix,"mat4"),s.bindMatrixInverseNode=Up(e.bindMatrixInverse,"mat4"),s.boneMatricesNode=ry(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length),s.toPositionNode=t,bd(s)},context:Gf,convert:ep,convertColorSpace:(e,t,s)=>bd(new ag(bd(e),t,s)),convertToTexture:(e,...t)=>e.isSampleNode||e.isTextureNode?e:e.isPassNode?e.getTextureNode():rA(e,...t),cos:$m,countLeadingZeros:lM,countOneBits:hM,countTrailingZeros:aM,cross:xf,cubeTexture:Dx,cubeTextureBase:Ix,dFdx:ef,dFdy:tf,dashSize:Mp,debug:Ug,decrement:_m,decrementBefore:xm,defaultBuildStages:Sc,defaultShaderStages:Tc,defined:gd,degrees:Bm,deltaTime:NM,densityFog:function(e,t){return Yo('TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.'),yN(e,gN(t))},densityFogFactor:gN,depth:ew,depthPass:(e,t,s)=>new WA(WA.DEPTH,e,t,s),determinant:lf,difference:gf,diffuseColor:rp,diffuseContribution:np,directPointLight:tC,directionToColor:pb,directionToFaceDirection:lx,dispersion:Ip,disposeShadowMaterial:CE,distance:ff,div:Jp,dodge:(...e)=>(Yo('TSL: "dodge" has been renamed. Use "blendDodge" instead.'),uw(e)),dot:yf,drawIndex:x_,dynamicBufferAttribute:(e,t=null,s=0,i=0)=>_g(e,t,s,i,zo),element:Jd,emissive:op,equal:tm,equals:uf,equirectUV:Aw,exp:Im,exp2:Dm,expression:Fg,faceDirection:ax,faceForward:Pf,faceforward:Of,float:Dd,floatBitsToInt:e=>new sM(e,"int","float"),floatBitsToUint:rM,floor:zm,fog:yN,fract:Gm,frameGroup:Op,frameId:EM,frontFacing:ox,fwidth:of,gain:(e,t)=>e.lessThan(.5)?cM(e.mul(2),t).div(2):Qp(1,cM(Kp(Qp(1,e),2),t).div(2)),gapSize:Ap,getConstNodeType:yd,getCurrentStack:Rd,getDirection:sT,getDistanceAttenuation:eC,getGeometryRoughness:Xw,getNormalFromDepth:aA,getParallaxCorrectNormal:qC,getRoughness:Yw,getScreenPosition:oA,getShIrradianceAt:XC,getShadowMaterial:EE,getShadowRenderObjectFunction:BE,getTextureIndex:JS,getViewPosition:nA,ggxConvolution:uT,globalId:AN,glsl:(e,t)=>rN(e,t,"glsl"),glslFn:(e,t)=>oN(e,t,"glsl"),grayscale:DA,greaterThan:rm,greaterThanEqual:om,hash:uM,highpModelNormalViewMatrix:Qy,highpModelViewMatrix:Zy,hue:OA,increment:bm,incrementBefore:ym,inspector:$g,instance:__,instanceIndex:m_,instancedArray:(e,t="float")=>{let s,i;!0===t.isStruct?(s=t.layout.getLength(),i=cc("float")):(s=dc(t),i=cc(t));const r=new pA(e,s,i);return c_(r,t,e)},instancedBufferAttribute:vg,instancedDynamicBufferAttribute:Tg,instancedMesh:v_,int:Ld,intBitsToFloat:e=>new sM(e,"float","int"),interleavedGradientNoise:lA,inverse:hf,inverseSqrt:Vm,inversesqrt:Vf,invocationLocalIndex:y_,invocationSubgroupIndex:g_,ior:Ep,iridescence:pp,iridescenceIOR:mp,iridescenceThickness:fp,isolate:Eg,ivec2:zd,ivec3:jd,ivec4:qd,js:(e,t)=>rN(e,t,"js"),label:qf,length:Qm,lengthSq:Mf,lessThan:im,lessThanEqual:nm,lightPosition:cE,lightProjectionUV:uE,lightShadowMatrix:hE,lightTargetDirection:mE,lightTargetPosition:dE,lightViewPosition:pE,lightingContext:z_,lights:(e=[])=>(new xE).setLights(e),linearDepth:tw,linearToneMapping:qA,localId:NN,log:Lm,log2:Fm,logarithmicDepthToViewZ:(e,t,s)=>{const i=e.mul(Lm(s.div(t)));return Dd(Math.E).pow(i).mul(t).negate()},luminance:VA,mat2:Zd,mat3:Qd,mat4:Kd,matcapUV:HT,materialAO:n_,materialAlphaTest:Tb,materialAnisotropy:Gb,materialAnisotropyVector:o_,materialAttenuationColor:Zb,materialAttenuationDistance:Yb,materialClearcoat:Fb,materialClearcoatNormal:Vb,materialClearcoatRoughness:Ob,materialColor:Sb,materialDispersion:i_,materialEmissive:Ab,materialEnvIntensity:Mx,materialEnvRotation:Ax,materialIOR:Xb,materialIridescence:jb,materialIridescenceIOR:$b,materialIridescenceThickness:Wb,materialLightMap:r_,materialLineDashOffset:t_,materialLineDashSize:Kb,materialLineGapSize:Jb,materialLineScale:Qb,materialLineWidth:e_,materialMetalness:Db,materialNormal:Lb,materialOpacity:Nb,materialPointSize:s_,materialReference:kx,materialReflectivity:Bb,materialRefractionRatio:Sx,materialRotation:zb,materialRoughness:Ib,materialSheen:kb,materialSheenRoughness:Ub,materialShininess:Mb,materialSpecular:Eb,materialSpecularColor:Rb,materialSpecularIntensity:Cb,materialSpecularStrength:Pb,materialThickness:qb,materialTransmission:Hb,max:df,maxMipLevel:Qg,mediumpModelViewMatrix:Yy,metalness:lp,min:cf,mix:Af,mixElement:If,mod:em,modInt:wm,modelDirection:ky,modelNormalMatrix:Hy,modelPosition:Gy,modelRadius:Wy,modelScale:jy,modelViewMatrix:Xy,modelViewPosition:$y,modelViewProjection:a_,modelWorldMatrix:Uy,modelWorldMatrixInverse:qy,morphReference:L_,mrt:tM,mul:Kp,mx_aastep:$C,mx_add:(e,t=Dd(0))=>Zp(e,t),mx_atan2:(e=Dd(0),t=Dd(1))=>Xm(e,t),mx_cell_noise_float:(e=qg())=>AC(e.convert("vec2|vec3")),mx_contrast:(e,t=1,s=.5)=>Dd(e).sub(s).mul(t).add(s),mx_divide:(e,t=Dd(1))=>Jp(e,t),mx_fractal_noise_float:(e=qg(),t=3,s=2,i=.5,r=1)=>EC(e,Ld(t),s,i).mul(r),mx_fractal_noise_vec2:(e=qg(),t=3,s=2,i=.5,r=1)=>RC(e,Ld(t),s,i).mul(r),mx_fractal_noise_vec3:(e=qg(),t=3,s=2,i=.5,r=1)=>CC(e,Ld(t),s,i).mul(r),mx_fractal_noise_vec4:(e=qg(),t=3,s=2,i=.5,r=1)=>PC(e,Ld(t),s,i).mul(r),mx_frame:()=>EM,mx_heighttonormal:(e,t)=>(e=Gd(e),t=Dd(t),_b(e,t)),mx_hsvtorgb:UC,mx_ifequal:(e,t,s,i)=>e.equal(t).mix(s,i),mx_ifgreater:(e,t,s,i)=>e.greaterThan(t).mix(s,i),mx_ifgreatereq:(e,t,s,i)=>e.greaterThanEqual(t).mix(s,i),mx_invert:(e,t=Dd(1))=>Qp(t,e),mx_modulo:(e,t=Dd(1))=>em(e,t),mx_multiply:(e,t=Dd(1))=>Kp(e,t),mx_noise_float:(e=qg(),t=1,s=0)=>SC(e.convert("vec2|vec3")).mul(t).add(s),mx_noise_vec3:(e=qg(),t=1,s=0)=>MC(e.convert("vec2|vec3")).mul(t).add(s),mx_noise_vec4:(e=qg(),t=1,s=0)=>{e=e.convert("vec2|vec3");return Hd(MC(e),SC(e.add(Vd(19,73)))).mul(t).add(s)},mx_place2d:(e,t=Vd(.5,.5),s=Vd(1,1),i=Dd(0),r=Vd(0,0))=>{let n=e;if(t&&(n=n.sub(t)),s&&(n=n.mul(s)),i){const e=i.mul(Math.PI/180),t=e.cos(),s=e.sin();n=Vd(n.x.mul(t).sub(n.y.mul(s)),n.x.mul(s).add(n.y.mul(t)))}return t&&(n=n.add(t)),r&&(n=n.add(r)),n},mx_power:(e,t=Dd(1))=>bf(e,t),mx_ramp4:(e,t,s,i,r=qg())=>{const n=r.x.clamp(),o=r.y.clamp(),a=Af(e,t,n),l=Af(s,i,n);return Af(a,l,o)},mx_ramplr:(e,t,s=qg())=>WC(e,t,s,"x"),mx_ramptb:(e,t,s=qg())=>WC(e,t,s,"y"),mx_rgbtohsv:GC,mx_rotate2d:(e,t)=>{e=Vd(e);const s=(t=Dd(t)).mul(Math.PI/180);return ZT(e,s)},mx_rotate3d:(e,t,s)=>{e=Gd(e),t=Dd(t),s=Gd(s);const i=t.mul(Math.PI/180),r=s.normalize(),n=i.cos(),o=i.sin(),a=Dd(1).sub(n);return e.mul(n).add(r.cross(e).mul(o)).add(r.mul(r.dot(e)).mul(a))},mx_safepower:(e,t=1)=>(e=Dd(e)).abs().pow(t).mul(e.sign()),mx_separate:(e,t=null)=>{if("string"==typeof t){const s={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3},i=t.replace(/^out/,"").toLowerCase();if(void 0!==s[i])return e.element(s[i])}if("number"==typeof t)return e.element(t);if("string"==typeof t&&1===t.length){const s={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3};if(void 0!==s[t])return e.element(s[t])}return e},mx_splitlr:(e,t,s,i=qg())=>HC(e,t,s,i,"x"),mx_splittb:(e,t,s,i=qg())=>HC(e,t,s,i,"y"),mx_srgb_texture_to_lin_rec709:jC,mx_subtract:(e,t=Dd(0))=>Qp(e,t),mx_timer:()=>AM,mx_transform_uv:(e=1,t=0,s=qg())=>s.mul(e).add(t),mx_unifiednoise2d:(e,t=qg(),s=Vd(1,1),i=Vd(0,0),r=1,n=0,o=1,a=!1,l=1,h=2,u=.5)=>zC(e,t.convert("vec2|vec3"),s,i,r,n,o,a,l,h,u),mx_unifiednoise3d:(e,t=qg(),s=Vd(1,1),i=Vd(0,0),r=1,n=0,o=1,a=!1,l=1,h=2,u=.5)=>kC(e,t.convert("vec2|vec3"),s,i,r,n,o,a,l,h,u),mx_worley_noise_float:(e=qg(),t=1)=>FC(e.convert("vec2|vec3"),t,Ld(1)),mx_worley_noise_vec2:(e=qg(),t=1)=>OC(e.convert("vec2|vec3"),t,Ld(1)),mx_worley_noise_vec3:(e=qg(),t=1)=>VC(e.convert("vec2|vec3"),t,Ld(1)),negate:Km,neutralToneMapping:sN,nodeArray:vd,nodeImmutable:Sd,nodeObject:bd,nodeObjectIntent:_d,nodeObjects:wd,nodeProxy:Td,nodeProxyIntent:Md,normalFlat:cx,normalGeometry:hx,normalLocal:ux,normalMap:gb,normalView:mx,normalViewGeometry:dx,normalWorld:fx,normalWorldGeometry:px,normalize:Um,not:hm,notEqual:sm,numWorkgroups:SN,objectDirection:Iy,objectGroup:zp,objectPosition:Ly,objectRadius:Vy,objectScale:Fy,objectViewPosition:Oy,objectWorldMatrix:Dy,oneMinus:Jm,or:lm,orthographicDepthToViewZ:(e,t,s)=>t.sub(s).mul(e).sub(t),oscSawtooth:(e=AM)=>e.fract(),oscSine:(e=AM)=>e.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5),oscSquare:(e=AM)=>e.fract().round(),oscTriangle:(e=AM)=>e.add(.5).fract().mul(2).sub(1).abs(),output:Sp,outputStruct:KS,overlay:(...e)=>(Yo('TSL: "overlay" has been renamed. Use "blendOverlay" instead.'),dw(e)),overloadingFn:MM,packHalf2x16:fM,packSnorm2x16:pM,packUnorm2x16:mM,parabola:cM,parallaxDirection:cb,parallaxUV:(e,t)=>e.sub(cb.mul(t)),parameter:(e,t)=>new HS(e,t),pass:(e,t,s)=>new WA(WA.COLOR,e,t,s),passTexture:(e,t)=>new jA(e,t),pcurve:(e,t,s)=>bf(Jp(bf(e,t),Zp(bf(e,t),bf(Qp(1,e),s))),1/t),perspectiveDepthToViewZ:Q_,pmremTexture:IT,pointShadow:KE,pointUV:gA,pointWidth:Np,positionGeometry:Ky,positionLocal:Jy,positionPrevious:ex,positionView:ix,positionViewDirection:rx,positionWorld:tx,positionWorldDirection:sx,posterize:UA,pow:bf,pow2:_f,pow3:wf,pow4:vf,premultiplyAlpha:mw,property:sp,quadBroadcast:oE,quadSwapDiagonal:eE,quadSwapX:KN,quadSwapY:JN,radians:Pm,rand:Bf,range:wN,rangeFog:function(e,t,s){return Yo('TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.'),yN(e,fN(t,s))},rangeFogFactor:fN,reciprocal:rf,reference:Ox,referenceBuffer:Vx,reflect:mf,reflectVector:Cx,reflectView:Nx,reflector:e=>new ZM(e),refract:Cf,refractVector:Rx,refractView:Ex,reinhardToneMapping:XA,remap:Ig,remapClamp:Dg,renderGroup:Vp,renderOutput:zg,rendererReference:pg,replaceDefaultUV:function(e,t=null){return Gf(t,{getUV:e})},rotate:ZT,rotateUV:CM,roughness:ap,round:sf,rtt:rA,sRGBTransferEOTF:rg,sRGBTransferOETF:ng,sample:(e,t=null)=>new uA(e,bd(t)),sampler:e=>(!0===e.isNode?e:ty(e)).convert("sampler"),samplerComparison:e=>(!0===e.isNode?e:ty(e)).convert("samplerComparison"),saturate:Ef,saturation:LA,screen:(...e)=>(Yo('TSL: "screen" has been renamed. Use "blendScreen" instead.'),cw(e)),screenCoordinate:fy,screenDPR:dy,screenSize:my,screenUV:py,scriptable:pN,scriptableValue:lN,select:kf,setCurrentStack:Cd,setName:$f,shaderStages:Mc,shadow:zE,shadowPositionWorld:_E,shapeCircle:rC,sharedUniformGroup:Fp,sheen:cp,sheenRoughness:dp,shiftLeft:fm,shiftRight:gm,shininess:Tp,sign:Zm,sin:jm,sinc:(e,t)=>jm(Mm.mul(t.mul(e).sub(1))).div(Mm.mul(t.mul(e).sub(1))),skinning:N_,smoothstep:Rf,smoothstepElement:Df,specularColor:_p,specularColorBlended:wp,specularF90:vp,spherizeUV:RM,split:(e,t)=>bd(new Lc(bd(e),t)),spritesheetUV:DM,sqrt:Om,stack:XS,step:pf,stepElement:Lf,storage:c_,storageBarrier:()=>CN("storage").toStack(),storageObject:(e,t,s)=>(Yo('TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.'),c_(e,t,s).setPBO(!0)),storageTexture:SA,string:(e="")=>new kc(e,"string"),struct:(e,t=null)=>{const s=new YS(e,t),i=(...t)=>{let i=null;if(t.length>0)if(t[0].isNode){i={};const s=Object.keys(e);for(let e=0;e<t.length;e++)i[s[e]]=t[e]}else i=t[0];return new ZS(s,i)};return i.layout=s,i.isStruct=!0,i},sub:Qp,subBuild:eg,subgroupAdd:VN,subgroupAll:YN,subgroupAnd:$N,subgroupAny:ZN,subgroupBallot:ON,subgroupBroadcast:tE,subgroupBroadcastFirst:QN,subgroupElect:FN,subgroupExclusiveAdd:kN,subgroupExclusiveMul:jN,subgroupInclusiveAdd:zN,subgroupInclusiveMul:GN,subgroupIndex:f_,subgroupMax:XN,subgroupMin:qN,subgroupMul:UN,subgroupOr:WN,subgroupShuffle:sE,subgroupShuffleDown:nE,subgroupShuffleUp:rE,subgroupShuffleXor:iE,subgroupSize:EN,subgroupXor:HN,tan:Wm,tangentGeometry:tb,tangentLocal:sb,tangentView:ib,tangentWorld:rb,texture:ty,texture3D:NA,texture3DLevel:(e,t,s)=>NA(e,t).level(s),texture3DLoad:(...e)=>NA(...e).setSampler(!1),textureBarrier:()=>CN("texture").toStack(),textureBicubic:Av,textureBicubicLevel:Mv,textureCubeUV:iT,textureLevel:(e,t,s)=>ty(e,t).level(s),textureLoad:sy,textureSize:Yg,textureStore:(e,t,s)=>{const i=SA(e,t,s);return null!==s&&i.toStack(),i},thickness:Rp,time:AM,toneMapping:fg,toneMappingExposure:gg,toonOutlinePass:(e,t,s=new eh(0,0,0),i=.003,r=1)=>bd(new HA(e,t,bd(s),bd(i),bd(r))),transformDirection:Tf,transformNormal:yx,transformNormalToView:xx,transformedClearcoatNormalView:wx,transformedNormalView:bx,transformedNormalWorld:_x,transmission:Cp,transpose:af,triNoise3D:vM,triplanarTexture:(...e)=>LM(...e),triplanarTextures:LM,trunc:nf,uint:Fd,uintBitsToFloat:e=>new sM(e,"float","uint"),uniform:Up,uniformArray:ay,uniformCubeTexture:(e=Px)=>Ix(e),uniformFlow:jf,uniformGroup:Lp,uniformTexture:(e=Kg)=>ty(e),unpackHalf2x16:bM,unpackNormal:mb,unpackSnorm2x16:yM,unpackUnorm2x16:xM,unpremultiplyAlpha:fw,userData:(e,t,s)=>new EA(e,t,s),uv:qg,uvec2:kd,uvec3:$d,uvec4:Xd,varying:sg,varyingProperty:ip,vec2:Vd,vec3:Gd,vec4:Hd,vectorComponents:Ac,velocity:IA,vertexColor:lw,vertexIndex:p_,vertexStage:ig,vibrance:FA,viewZToLogarithmicDepth:K_,viewZToOrthographicDepth:Y_,viewZToPerspectiveDepth:Z_,viewport:gy,viewportCoordinate:xy,viewportDepthTexture:q_,viewportLinearDepth:sw,viewportMipTexture:$_,viewportResolution:_y,viewportSafeUV:BM,viewportSharedTexture:Tw,viewportSize:yy,viewportTexture:j_,viewportUV:by,vogelDiskSample:hA,wgsl:(e,t)=>rN(e,t,"wgsl"),wgslFn:(e,t)=>oN(e,t,"wgsl"),workgroupArray:(e,t)=>new PN("Workgroup",e,t),workgroupBarrier:()=>CN("workgroup").toStack(),workgroupId:MN,workingToColorSpace:lg,xor:um});const ZC=new WS;class QC extends dS{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,s){const i=this.renderer,r=this.nodes.getBackgroundNode(e)||e.background;let n=!1;if(null===r)i._clearColor.getRGB(ZC),ZC.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(ZC),ZC.a=1,n=!0;else if(!0===r.isNode){const s=this.get(e),n=r;ZC.copy(i._clearColor);let o=s.backgroundMesh;if(void 0===o){let e=function(){r.removeEventListener("dispose",e),o.material.dispose(),o.geometry.dispose()};const t=Hd(n).mul(wA).context({getUV:()=>vA.mul(px),getTextureLevel:()=>_A}),i=Sy.element(3).element(3).equal(1),a=Jp(1,Sy.element(1).element(1)).mul(3),l=i.select(Jy.mul(a),Jy);let h=Sy.mul(Xy.mul(Hd(l,0)));h=h.setZ(h.w);const u=new gw;u.name="Background.material",u.side=1,u.depthTest=!1,u.depthWrite=!1,u.allowOverride=!1,u.fog=!1,u.lights=!1,u.vertexNode=h,u.colorNode=t,s.backgroundMeshNode=t,s.backgroundMesh=o=new Fh(new Su(1,32,32),u),o.frustumCulled=!1,o.name="Background.mesh",r.addEventListener("dispose",e)}const a=n.getCacheKey();s.backgroundCacheKey!==a&&(s.backgroundMeshNode.node=Hd(n).mul(wA),s.backgroundMeshNode.needsUpdate=!0,o.material.needsUpdate=!0,s.backgroundCacheKey=a),t.unshift(o,o.geometry,o.material,0,0,null,null)}else Zo("Renderer: Unsupported background configuration.",r);const o=i.xr.getEnvironmentBlendMode();if("additive"===o?ZC.set(0,0,0,1):"alpha-blend"===o&&ZC.set(0,0,0,0),!0===i.autoClear||!0===n){const e=s.clearColorValue;e.r=ZC.r,e.g=ZC.g,e.b=ZC.b,e.a=ZC.a,!0!==i.backend.isWebGLBackend&&!0!==i.alpha||(e.r*=e.a,e.g*=e.a,e.b*=e.a),s.depthClearValue=i._clearDepth,s.stencilClearValue=i._clearStencil,s.clearColor=!0===i.autoClearColor,s.clearDepth=!0===i.autoClearDepth,s.clearStencil=!0===i.autoClearStencil}else s.clearColor=!1,s.clearDepth=!1,s.clearStencil=!1}}let KC=0;class JC{constructor(e="",t=[],s=0,i=[]){this.name=e,this.bindings=t,this.index=s,this.bindingsReference=i,this.id=KC++}}class eR{constructor(e,t,s,i,r,n,o,a,l,h=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=s,this.transforms=h,this.nodeAttributes=i,this.bindings=r,this.updateNodes=n,this.updateBeforeNodes=o,this.updateAfterNodes=a,this.observer=l,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const s=new JC(t.name,[],t.index,t.bindingsReference);e.push(s);for(const e of t.bindings)s.bindings.push(e.clone())}else e.push(t)}return e}}class tR{constructor(e,t,s=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=s}}class sR{constructor(e,t,s){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=s}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}}class iR{constructor(e,t,s=!1,i=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=s,this.count=i}}class rR extends iR{constructor(e,t,s=null,i=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=s,this.interpolationSampling=i}}class nR{constructor(e,t,s=""){this.name=e,this.type=t,this.code=s,Object.defineProperty(this,"isNodeCode",{value:!0})}}let oR=0;class aR{constructor(e=null){this.id=oR++,this.nodesData=new WeakMap,this.parent=e}getData(e){let t=this.nodesData.get(e);return void 0===t&&null!==this.parent&&(t=this.parent.getData(e)),t}setData(e,t){this.nodesData.set(e,t)}}class lR{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class hR{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0}setValue(e){this.value=e}getValue(){return this.value}}class uR extends hR{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class cR extends hR{constructor(e,t=new ua){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class dR extends hR{constructor(e,t=new da){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class pR extends hR{constructor(e,t=new Pa){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class mR extends hR{constructor(e,t=new eh){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class fR extends hR{constructor(e,t=new Ju){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class gR extends hR{constructor(e,t=new fa){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class yR extends hR{constructor(e,t=new ll){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class xR extends uR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class bR extends cR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class _R extends dR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class wR extends pR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class vR extends mR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class TR extends fR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class SR extends gR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class MR extends yR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let AR=0;const NR=new WeakMap,ER=new WeakMap,CR=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),RR=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class PR{constructor(e,t,s){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=s,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=XS(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new aR,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.activeStacks=[],this.subBuildFn=null,this.fnCall=null,Object.defineProperty(this,"id",{value:AR++})}isOpaque(){const e=this.material;return!1===e.transparent&&1===e.blending&&!1===e.alphaToCoverage}getBindGroupsCache(){let e=ER.get(this.renderer);return void 0===e&&(e=new aS,ER.set(this.renderer,e)),e}createRenderTarget(e,t,s){return new Ba(e,t,s)}createCubeRenderTarget(e,t){return new Nw(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const s=this.getBindGroupsCache(),i=[];let r,n=!0;for(const e of t)i.push(e),n=n&&!0!==e.groupNode.shared;return n?(r=s.get(i),void 0===r&&(r=new JC(e,i,this.bindingsIndexes[e].group,i),s.set(i,r))):r=new JC(e,i,this.bindingsIndexes[e].group,i),r}getBindGroupArray(e,t){const s=this.bindings[t];let i=s[e];return void 0===i&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),s[e]=i=[]),i}getBindings(){let e=this.bindGroups;if(null===e){const t={},s=this.bindings;for(const e of Mc)for(const i in s[e]){const r=s[e][i];(t[i]||(t[i]=[])).push(...r)}e=[];for(const s in t){const i=t[s],r=this._getBindGroup(s,i);e.push(r)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort((e,t)=>e.bindings[0].groupNode.order-t.bindings[0].groupNode.order);for(let t=0;t<e.length;t++){const s=e[t];this.bindingsIndexes[s.name].group=t,s.index=t}}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){!1===this.nodes.includes(e)&&(this.nodes.push(e),this.setHashNode(e,e.getHash(this)))}addSequentialNode(e){!1===this.sequentialNodes.includes(e)&&this.sequentialNodes.push(e)}buildUpdateNodes(){for(const e of this.nodes){e.getUpdateType()!==wc.NONE&&this.updateNodes.push(e)}for(const e of this.sequentialNodes){const t=e.getUpdateBeforeType(),s=e.getUpdateAfterType();t!==wc.NONE&&this.updateBeforeNodes.push(e),s!==wc.NONE&&this.updateAfterNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===xn||e.magFilter===bn||e.magFilter===yn||e.magFilter===_n||e.minFilter===xn||e.minFilter===bn||e.minFilter===yn||e.minFilter===_n}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("NodeBuilder: Invalid node chaining!")}getMethod(e){return e}getTernary(){return null}getNodeFromHash(e){return this.hashNodes[e]}addFlow(e,t){return this.flowNodes[e].push(t),t}setContext(e){this.context=e}getContext(){return this.context}addContext(e){const t=this.getContext();return this.setContext({...this.context,...e}),t}getSharedContext(){const e={...this.context};return delete e.material,delete e.getUV,delete e.getOutput,delete e.getTextureLevel,delete e.getAO,delete e.getShadow,e}setCache(e){this.cache=e}getCache(){return this.cache}getCacheFromNode(e,t=!0){const s=this.getDataFromNode(e);return void 0===s.cache&&(s.cache=new aR(t?this.getCache():null)),s.cache}isAvailable(){return!1}getVertexIndex(){Yo("Abstract function.")}getInstanceIndex(){Yo("Abstract function.")}getDrawIndex(){Yo("Abstract function.")}getFrontFacing(){Yo("Abstract function.")}getFragCoord(){Yo("Abstract function.")}isFlipY(){return!1}increaseUsage(e){const t=this.getDataFromNode(e);return t.usageCount=void 0===t.usageCount?1:t.usageCount+1,t.usageCount}generateTexture(){Yo("Abstract function.")}generateTextureLod(){Yo("Abstract function.")}generateArrayDeclaration(e,t){return this.getType(e)+"[ "+t+" ]"}generateArray(e,t,s=null){let i=this.generateArrayDeclaration(e,t)+"( ";for(let r=0;r<t;r++){const n=s?s[r]:null;i+=null!==n?n.build(this,e):this.generateConst(e),r<t-1&&(i+=", ")}return i+=" )",i}generateStruct(e,t,s=null){const i=[];for(const e of t){const{name:t,type:r}=e;s&&s[t]&&s[t].isNode?i.push(s[t].build(this,r)):i.push(this.generateConst(r))}return e+"( "+i.join(", ")+" )"}generateConst(e,t=null){if(null===t&&("float"===e||"int"===e||"uint"===e?t=0:"bool"===e?t=!1:"color"===e?t=new eh:"vec2"===e||"uvec2"===e||"ivec2"===e?t=new ua:"vec3"===e||"uvec3"===e||"ivec3"===e?t=new da:"vec4"!==e&&"uvec4"!==e&&"ivec4"!==e||(t=new Pa)),"float"===e)return RR(t);if("int"===e)return`${Math.round(t)}`;if("uint"===e)return t>=0?`${Math.round(t)}u`:"0u";if("bool"===e)return t?"true":"false";if("color"===e)return`${this.getType("vec3")}( ${RR(t.r)}, ${RR(t.g)}, ${RR(t.b)} )`;const s=this.getTypeLength(e),i=this.getComponentType(e),r=e=>this.generateConst(i,e);if(2===s)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)} )`;if(3===s)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)} )`;if(4===s&&"mat2"!==e)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)}, ${r(t.w)} )`;if(s>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(r).join(", ")} )`;if(s>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' not found in generate constant attempt.`)}getType(e){return"color"===e?"vec3":e}hasGeometryAttribute(e){return this.geometry&&void 0!==this.geometry.getAttribute(e)}getAttribute(e,t){const s=this.attributes;for(const t of s)if(t.name===e)return t;const i=new tR(e,t);return this.registerDeclaration(i),s.push(i),i}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return"void"===e||"property"===e||"sampler"===e||"samplerComparison"===e||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===Mn)return"int";if(t===An)return"uint"}return"float"}getElementType(e){return"mat2"===e?"vec2":"mat3"===e?"vec3":"mat4"===e?"vec4":this.getComponentType(e)}getComponentType(e){if("float"===(e=this.getVectorType(e))||"bool"===e||"int"===e||"uint"===e)return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return null===t?null:"b"===t[1]?"bool":"i"===t[1]?"int":"u"===t[1]?"uint":"float"}getVectorType(e){return"color"===e?"vec3":"texture"===e||"cubeTexture"===e||"storageTexture"===e||"texture3D"===e?"vec4":e}getTypeFromLength(e,t="float"){if(1===e)return t;let s=uc(e);const i="float"===t?"":t[0];return!0===/mat2/.test(t)&&(s=s.replace("vec","mat")),i+s}getTypeFromArray(e){return CR.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const s=t.array,i=e.itemSize,r=e.normalized;let n;return e instanceof fh||!0===r||(n=this.getTypeFromArray(s)),this.getTypeFromLength(i,n)}getTypeLength(e){const t=this.getVectorType(e),s=/vec([2-4])/.exec(t);return null!==s?Number(s[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/mat2/.test(e)?4:!0===/mat3/.test(e)?9:!0===/mat4/.test(e)?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return"int"===t||"uint"===t?e:this.changeComponentType(e,"int")}setActiveStack(e){this.activeStacks.push(e)}removeActiveStack(e){if(this.activeStacks[this.activeStacks.length-1]!==e)throw new Error("NodeBuilder: Invalid active stack removal.");this.activeStacks.pop()}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=XS(this.stack);const e=Rd();return this.stacks.push(e),Cd(this.stack),this.stack}removeStack(){const e=this.stack;for(const t of e.nodes){this.getDataFromNode(t).stack=e}return this.stack=e.parent,Cd(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,s=null){let i=(s=null===s?e.isGlobal(this)?this.globalCache:this.cache:s).getData(e);void 0===i&&(i={},s.setData(e,i)),void 0===i[t]&&(i[t]={});let r=i[t];const n=i.any?i.any.subBuilds:null,o=this.getClosestSubBuild(n);return o&&(void 0===r.subBuildsCache&&(r.subBuildsCache={}),r=r.subBuildsCache[o]||(r.subBuildsCache[o]={}),r.subBuilds=n),r}getNodeProperties(e,t="any"){const s=this.getDataFromNode(e,t);return s.properties||(s.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const s=this.getDataFromNode(e,"vertex");let i=s.bufferAttribute;if(void 0===i){const r=this.uniforms.index++;i=new tR("nodeAttribute"+r,t,e),this.bufferAttributes.push(i),s.bufferAttribute=i}return i}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,s=null,i=this.shaderStage){const r=this.getDataFromNode(e,i,this.globalCache);let n=r.structType;if(void 0===n){const o=this.structs.index++;null===s&&(s="StructType"+o),n=new lR(s,t),this.structs[i].push(n),this.types[i][s]=e,r.structType=n}return n}getOutputStructTypeFromNode(e,t){const s=this.getStructTypeFromNode(e,t,"OutputType","fragment");return s.output=!0,s}getUniformFromNode(e,t,s=this.shaderStage,i=null){const r=this.getDataFromNode(e,s,this.globalCache);let n=r.uniform;if(void 0===n){const o=this.uniforms.index++;n=new sR(i||"nodeUniform"+o,t,e),this.uniforms[s].push(n),this.registerDeclaration(n),r.uniform=n}return n}getVarFromNode(e,t=null,s=e.getNodeType(this),i=this.shaderStage,r=!1){const n=this.getDataFromNode(e,i),o=this.getSubBuildProperty("variable",n.subBuilds);let a=n[o];if(void 0===a){const l=r?"_const":"_var",h=this.vars[i]||(this.vars[i]=[]),u=this.vars[l]||(this.vars[l]=0);null===t&&(t=(r?"nodeConst":"nodeVar")+u,this.vars[l]++),"variable"!==o&&(t=this.getSubBuildProperty(t,n.subBuilds));const c=e.getArrayCount(this);a=new iR(t,s,r,c),r||h.push(a),this.registerDeclaration(a),n[o]=a}return a}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode))&&(!e.cNode||this.isDeterministic(e.cNode));if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode));if(e.isArrayNode){if(null!==e.values)for(const t of e.values)if(!this.isDeterministic(t))return!1;return!0}return!!e.isConstNode}getVaryingFromNode(e,t=null,s=e.getNodeType(this),i=null,r=null){const n=this.getDataFromNode(e,"any"),o=this.getSubBuildProperty("varying",n.subBuilds);let a=n[o];if(void 0===a){const e=this.varyings,l=e.length;null===t&&(t="nodeVarying"+l),"varying"!==o&&(t=this.getSubBuildProperty(t,n.subBuilds)),a=new rR(t,s,i,r),e.push(a),this.registerDeclaration(a),n[o]=a}return a}registerDeclaration(e){const t=this.shaderStage,s=this.declarations[t]||(this.declarations[t]={}),i=this.getPropertyName(e);let r=1,n=i;for(;void 0!==s[n];)n=i+"_"+r++;r>1&&(e.name=n,Yo(`TSL: Declaration name '${i}' of '${e.type}' already in use. Renamed to '${n}'.`)),s[n]=e}getCodeFromNode(e,t,s=this.shaderStage){const i=this.getDataFromNode(e);let r=i.code;if(void 0===r){const e=this.codes[s]||(this.codes[s]=[]),n=e.length;r=new nR("nodeCode"+n,t),e.push(r),i.code=r}return r}addFlowCodeHierarchy(e,t){const{flowCodes:s,flowCodeBlock:i}=this.getDataFromNode(e);let r=!0,n=t;for(;n;){if(!0===i.get(n)){r=!1;break}n=this.getDataFromNode(n).parentNodeBlock}if(r)for(const e of s)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,s){const i=this.getDataFromNode(e),r=i.flowCodes||(i.flowCodes=[]),n=i.flowCodeBlock||(i.flowCodeBlock=new WeakMap);r.push(t),n.set(s,!0)}addLineFlowCode(e,t=null){return""===e||(null!==t&&this.context.nodeBlock&&this.addLineFlowCodeBlock(t,e,this.context.nodeBlock),e=this.tab+e,/;\s*$/.test(e)||(e+=";\n"),this.flow.code+=e),this}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+="\t",this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(e){return this.flowsData.get(e)}flowNode(e){const t=e.getNodeType(this),s=this.flowChildNode(e,t);return this.flowsData.set(e,s),s}addInclude(e){null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=new nN,s=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=s,t}flowShaderNode(e){const t=e.layout,s={[Symbol.iterator](){let e=0;const t=Object.values(this);return{next:()=>({value:t[e],done:e++>=t.length})}}};for(const e of t.inputs)s[e.name]=new HS(e.type,e.name);e.layout=null;const i=e.call(s),r=this.flowStagesNode(i,t.type);return e.layout=t,r}flowBuildStage(e,t,s=null){const i=this.getBuildStage();this.setBuildStage(t);const r=e.build(this,s);return this.setBuildStage(i),r}flowStagesNode(e,t=null){const s=this.flow,i=this.vars,r=this.declarations,n=this.cache,o=this.buildStage,a=this.stack,l={code:""};this.flow=l,this.vars={},this.declarations={},this.cache=new aR,this.stack=XS();for(const s of Sc)this.setBuildStage(s),l.result=e.build(this,t);return l.vars=this.getVars(this.shaderStage),this.flow=s,this.vars=i,this.declarations=r,this.cache=n,this.stack=a,this.setBuildStage(o),l}getFunctionOperator(){return null}buildFunctionCode(){Yo("Abstract function.")}flowChildNode(e,t=null){const s=this.flow,i={code:""};return this.flow=i,i.result=e.build(this,t),this.flow=s,i}flowNodeFromShaderStage(e,t,s=null,i=null){const r=this.tab,n=this.cache,o=this.shaderStage,a=this.context;this.setShaderStage(e);const l={...this.context};delete l.nodeBlock,this.cache=this.globalCache,this.tab="\t",this.context=l;let h=null;if("generate"===this.buildStage){const r=this.flowChildNode(t,s);null!==i&&(r.code+=`${this.tab+i} = ${r.result};\n`),this.flowCode[e]=this.flowCode[e]+r.code,h=r}else h=t.build(this);return this.setShaderStage(o),this.cache=n,this.tab=r,this.context=a,h}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){Yo("Abstract function.")}getVaryings(){Yo("Abstract function.")}getVar(e,t,s=null){return`${null!==s?this.generateArrayDeclaration(e,s):this.getType(e)} ${t}`}getVars(e){let t="";const s=this.vars[e];if(void 0!==s)for(const e of s)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){Yo("Abstract function.")}getCodes(e){const t=this.codes[e];let s="";if(void 0!==t)for(const e of t)s+=e.code+"\n";return s}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(e){this.shaderStage=e}getShaderStage(){return this.shaderStage}setBuildStage(e){this.buildStage=e}getBuildStage(){return this.buildStage}buildCode(){Yo("Abstract function.")}get subBuild(){return this.subBuildLayers[this.subBuildLayers.length-1]||null}addSubBuild(e){this.subBuildLayers.push(e)}removeSubBuild(){return this.subBuildLayers.pop()}getClosestSubBuild(e){let t;if(t=e&&e.isNode?e.isShaderCallNodeInternal?e.shaderNode.subBuilds:e.isStackNode?[e.subBuild]:this.getDataFromNode(e,"any").subBuilds:e instanceof Set?[...e]:e,!t)return null;const s=this.subBuildLayers;for(let e=t.length-1;e>=0;e--){const i=t[e];if(s.includes(i))return i}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let s,i;return s=null!==t?this.getClosestSubBuild(t):this.subBuildFn,i=s?e?s+"_"+e:s:e,i}build(){const{object:e,material:t,renderer:s}=this;if(null!==t){let e=s.library.fromMaterial(t);null===e&&(Zo(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new gw),e.build(this)}else this.addFlow("compute",e);for(const e of Sc){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of Mc){this.setShaderStage(t);const s=this.flowNodes[t];for(const t of s)"generate"===e?this.flowNode(t):t.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=NR.get(e);return void 0===t&&(t={}),t}getNodeUniform(e,t){const s=this.getSharedDataFromNode(e);let i=s.cache;if(void 0===i){if("float"===t||"int"===t||"uint"===t)i=new xR(e);else if("vec2"===t||"ivec2"===t||"uvec2"===t)i=new bR(e);else if("vec3"===t||"ivec3"===t||"uvec3"===t)i=new _R(e);else if("vec4"===t||"ivec4"===t||"uvec4"===t)i=new wR(e);else if("color"===t)i=new vR(e);else if("mat2"===t)i=new TR(e);else if("mat3"===t)i=new SR(e);else{if("mat4"!==t)throw new Error(`Uniform "${t}" not implemented.`);i=new MR(e)}s.cache=i}return i}format(e,t,s){if((t=this.getVectorType(t))===(s=this.getVectorType(s))||null===s||this.isReference(s))return e;const i=this.getTypeLength(t),r=this.getTypeLength(s);return 16===i&&9===r?`${this.getType(s)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:9===i&&4===r?`${this.getType(s)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:i>4||r>4||0===r?e:i===r?`${this.getType(s)}( ${e} )`:i>r?(e="bool"===s?`all( ${e} )`:`${e}.${"xyz".slice(0,r)}`,this.format(e,this.getTypeFromLength(r,this.getComponentType(t)),s)):4===r&&i>1?`${this.getType(s)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===i?`${this.getType(s)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===i&&r>1&&t!==this.getComponentType(s)&&(e=`${this.getType(this.getComponentType(s))}( ${e} )`),`${this.getType(s)}( ${e} )`)}getSignature(){return`// Three.js r${Xr} - Node System\n`}}class BR{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let s=e.get(t);return void 0===s&&(s={renderId:0,frameId:0},e.set(t,s)),s}updateBeforeNode(e){const t=e.getUpdateBeforeType(),s=e.updateReference(this);if(t===wc.FRAME){const t=this._getMaps(this.updateBeforeMap,s);if(t.frameId!==this.frameId){const s=t.frameId;t.frameId=this.frameId,!1===e.updateBefore(this)&&(t.frameId=s)}}else if(t===wc.RENDER){const t=this._getMaps(this.updateBeforeMap,s);if(t.renderId!==this.renderId){const s=t.renderId;t.renderId=this.renderId,!1===e.updateBefore(this)&&(t.renderId=s)}}else t===wc.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),s=e.updateReference(this);if(t===wc.FRAME){const t=this._getMaps(this.updateAfterMap,s);t.frameId!==this.frameId&&!1!==e.updateAfter(this)&&(t.frameId=this.frameId)}else if(t===wc.RENDER){const t=this._getMaps(this.updateAfterMap,s);t.renderId!==this.renderId&&!1!==e.updateAfter(this)&&(t.renderId=this.renderId)}else t===wc.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),s=e.updateReference(this);if(t===wc.FRAME){const t=this._getMaps(this.updateMap,s);t.frameId!==this.frameId&&!1!==e.update(this)&&(t.frameId=this.frameId)}else if(t===wc.RENDER){const t=this._getMaps(this.updateMap,s);t.renderId!==this.renderId&&!1!==e.update(this)&&(t.renderId=this.renderId)}else t===wc.OBJECT&&e.update(this)}update(){this.frameId++,void 0===this.lastTime&&(this.lastTime=performance.now()),this.deltaTime=(performance.now()-this.lastTime)/1e3,this.lastTime=performance.now(),this.time+=this.deltaTime}}class IR{constructor(e,t,s=null,i="",r=!1){this.type=e,this.name=t,this.count=s,this.qualifier=i,this.isConst=r}}IR.isNodeFunctionInput=!0;class DR extends JE{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:mE(this.light),lightColor:e}}}const LR=new ll,FR=new ll;let OR=null;class VR extends JE{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=Up(new da).setGroup(Vp),this.halfWidth=Up(new da).setGroup(Vp),this.updateType=wc.RENDER}update(e){super.update(e);const{light:t}=this,s=e.camera.matrixWorldInverse;FR.identity(),LR.copy(t.matrixWorld),LR.premultiply(s),FR.extractRotation(LR),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(FR),this.halfHeight.value.applyMatrix4(FR)}setupDirectRectArea(e){let t,s;e.isAvailable("float32Filterable")?(t=ty(OR.LTC_FLOAT_1),s=ty(OR.LTC_FLOAT_2)):(t=ty(OR.LTC_HALF_1),s=ty(OR.LTC_HALF_2));const{colorNode:i,light:r}=this;return{lightColor:i,lightPosition:pE(r),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:s}}static setLTC(e){OR=e}}class zR extends JE{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=Up(0).setGroup(Vp),this.penumbraCosNode=Up(0).setGroup(Vp),this.cutoffDistanceNode=Up(0).setGroup(Vp),this.decayExponentNode=Up(0).setGroup(Vp),this.colorNode=Up(this.color).setGroup(Vp)}update(e){super.update(e);const{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e,t){const{coneCosNode:s,penumbraCosNode:i}=this;return Rf(s,i,t)}getLightCoord(e){const t=e.getNodeProperties(this);let s=t.projectionUV;return void 0===s&&(s=uE(this.light,e.context.positionWorld),t.projectionUV=s),s}setupDirect(e){const{colorNode:t,cutoffDistanceNode:s,decayExponentNode:i,light:r}=this,n=this.getLightVector(e),o=n.normalize(),a=o.dot(mE(r)),l=this.getSpotAttenuation(e,a),h=n.length(),u=eC({lightDistance:h,cutoffDistance:s,decayExponent:i});let c,d,p=t.mul(l).mul(u);if(r.colorNode?(d=this.getLightCoord(e),c=r.colorNode(d)):r.map&&(d=this.getLightCoord(e),c=ty(r.map,d.xy).onRenderUpdate(()=>r.map)),c){p=d.mul(2).sub(1).abs().lessThan(1).all().select(p.mul(c),p)}return{lightColor:p,lightDirection:o}}}class kR extends zR{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e,t){const s=this.light.iesMap;let i=null;if(s&&!0===s.isTexture){const e=t.acos().mul(1/Math.PI);i=ty(s,Vd(e,0),0).r}else i=super.getSpotAttenuation(t);return i}}const UR=Ed(([e,t])=>{const s=e.abs().sub(t);return Qm(df(s,0)).add(cf(df(s.x,s.y),0))});class GR extends zR{static get type(){return"ProjectorLightNode"}update(e){super.update(e);const t=this.light;if(this.penumbraCosNode.value=Math.min(Math.cos(t.angle*(1-t.penumbra)),.99999),null===t.aspect){let e=1;null!==t.map&&(e=t.map.width/t.map.height),t.shadow.aspect=e}else t.shadow.aspect=t.aspect}getSpotAttenuation(e){const t=Dd(0),s=this.penumbraCosNode,i=hE(this.light).mul(e.context.positionWorld||tx);return Pd(i.w.greaterThan(0),()=>{const e=i.xyz.div(i.w),r=UR(e.xy.sub(Vd(.5)),Vd(.5)),n=Jp(-1,Qp(1,qm(s)).sub(1));t.assign(Ef(r.mul(-2).mul(n)))}),t}}class jR extends JE{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class $R extends JE{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=cE(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Up(new eh).setGroup(Vp)}update(e){const{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){const{colorNode:t,groundColorNode:s,lightDirectionNode:i}=this,r=fx.dot(i).mul(.5).add(.5),n=Af(s,t,r);e.context.irradiance.addAssign(n)}}class WR extends JE{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new da);this.lightProbe=ay(t)}update(e){const{light:t}=this;super.update(e);for(let e=0;e<9;e++)this.lightProbe.array[e].copy(t.sh.coefficients[e]).multiplyScalar(t.intensity)}setup(e){const t=XC(fx,this.lightProbe);e.context.irradiance.addAssign(t)}}class HR{parseFunction(){Yo("Abstract function.")}}class qR{constructor(e,t,s="",i=""){this.type=e,this.inputs=t,this.name=s,this.precision=i}getCode(){Yo("Abstract function.")}}qR.isNodeFunction=!0;const XR=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,YR=/[a-z_0-9]+/gi,ZR="#pragma main";class QR extends qR{constructor(e){const{type:t,inputs:s,name:i,precision:r,inputsCode:n,blockCode:o,headerCode:a}=(e=>{const t=(e=e.trim()).indexOf(ZR),s=-1!==t?e.slice(t+12):e,i=s.match(XR);if(null!==i&&5===i.length){const r=i[4],n=[];let o=null;for(;null!==(o=YR.exec(r));)n.push(o);const a=[];let l=0;for(;l<n.length;){const e="const"===n[l][0];!0===e&&l++;let t=n[l][0];"in"===t||"out"===t||"inout"===t?l++:t="";const s=n[l++][0];let i=Number.parseInt(n[l][0]);!1===Number.isNaN(i)?l++:i=null;const r=n[l++][0];a.push(new IR(s,r,i,t,e))}const h=s.substring(i[0].length),u=void 0!==i[3]?i[3]:"";return{type:i[2],inputs:a,name:u,precision:void 0!==i[1]?i[1]:"",inputsCode:r,blockCode:h,headerCode:-1!==t?e.slice(0,t):""}}throw new Error("FunctionNode: Function is not a GLSL code.")})(e);super(t,s,i,r),this.inputsCode=n,this.blockCode=o,this.headerCode=a}getCode(e=this.name){let t;const s=this.blockCode;if(""!==s){const{type:i,inputsCode:r,headerCode:n,precision:o}=this;let a=`${i} ${e} ( ${r.trim()} )`;""!==o&&(a=`${o} ${a}`),t=n+a+s}else t="";return t}}class KR extends HR{parseFunction(e){return new QR(e)}}const JR=new WeakMap,eP=[],tP=[];class sP extends dS{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new BR,this.nodeBuilderCache=new Map,this.callHashCache=new aS,this.groupsData=new aS,this.cacheLib={}}updateGroup(e){const t=e.groupNode,s=t.name;if(s===zp.name)return!0;if(s===Vp.name){const t=this.get(e),s=this.nodeFrame.renderId;return t.renderId!==s&&(t.renderId=s,!0)}if(s===Op.name){const t=this.get(e),s=this.nodeFrame.frameId;return t.frameId!==s&&(t.frameId=s,!0)}eP[0]=t,eP[1]=e;let i=this.groupsData.get(eP);return void 0===i&&this.groupsData.set(eP,i={}),eP.length=0,i.version!==t.version&&(i.version=t.version,!0)}getForRenderCacheKey(e){return e.initialCacheKey}getForRender(e){const t=this.get(e);let s=t.nodeBuilderState;if(void 0===s){const{nodeBuilderCache:i}=this,r=this.getForRenderCacheKey(e);if(s=i.get(r),void 0===s){const t=t=>{const s=this.backend.createNodeBuilder(e.object,this.renderer);return s.scene=e.scene,s.material=t,s.camera=e.camera,s.context.material=t,s.lightsNode=e.lightsNode,s.environmentNode=this.getEnvironmentNode(e.scene),s.fogNode=this.getFogNode(e.scene),s.clippingContext=e.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&s.enableMultiview(),s};let n=t(e.material);try{n.build()}catch(e){n=t(new gw),n.build(),Zo("TSL: "+e)}s=this._createNodeBuilderState(n),i.set(r,s)}s.usedTimes++,t.nodeBuilderState=s}return s}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e))}return super.delete(e)}getForCompute(e){const t=this.get(e);let s=t.nodeBuilderState;if(void 0===s){const i=this.backend.createNodeBuilder(e,this.renderer);i.build(),s=this._createNodeBuilderState(i),t.nodeBuilderState=s}return s}_createNodeBuilderState(e){return new eR(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.transforms)}getEnvironmentNode(e){this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{const s=this.get(e);s.environmentNode&&(t=s.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{const s=this.get(e);s.backgroundNode&&(t=s.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){eP[0]=e,eP[1]=t;const s=this.renderer.info.calls,i=this.callHashCache.get(eP)||{};if(i.callId!==s){const r=this.getEnvironmentNode(e),n=this.getFogNode(e);t&&tP.push(t.getCacheKey(!0)),r&&tP.push(r.getCacheKey()),n&&tP.push(n.getCacheKey()),tP.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),tP.push(this.renderer.shadowMap.enabled?1:0),tP.push(this.renderer.shadowMap.type),i.callId=s,i.cacheKey=oc(tP),this.callHashCache.set(eP,i),tP.length=0}return eP.length=0,i.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),s=e.background;if(s){const i=0===e.backgroundBlurriness&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==s||i){const r=this.getCacheNode("background",s,()=>{if(!0===s.isCubeTexture||303===s.mapping||304===s.mapping||306===s.mapping){if(e.backgroundBlurriness>0||306===s.mapping)return IT(s);{let e;return e=!0===s.isCubeTexture?Dx(s):ty(s),Bw(e)}}if(!0===s.isTexture)return ty(s,py.flipY()).setUpdateMatrix(!0);!0!==s.isColor&&Zo("WebGPUNodes: Unsupported background configuration.",s)},i);t.backgroundNode=r,t.background=s,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,s,i=!1){const r=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let n=r.get(t);return(void 0===n||i)&&(n=s(),r.set(t,n)),n}updateFog(e){const t=this.get(e),s=e.fog;if(s){if(t.fog!==s){const e=this.getCacheNode("fog",s,()=>{if(s.isFogExp2){const e=Ox("color","color",s).setGroup(Vp),t=Ox("density","float",s).setGroup(Vp);return yN(e,gN(t))}if(s.isFog){const e=Ox("color","color",s).setGroup(Vp),t=Ox("near","float",s).setGroup(Vp),i=Ox("far","float",s).setGroup(Vp);return yN(e,fN(t,i))}Zo("Renderer: Unsupported fog configuration.",s)});t.fogNode=e,t.fog=s}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),s=e.environment;if(s){if(t.environment!==s){const e=this.getCacheNode("environment",s,()=>!0===s.isCubeTexture?Dx(s):!0===s.isTexture?ty(s):void Zo("Nodes: Unsupported environment configuration.",s));t.environmentNode=e,t.environment=s}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,s=null,i=null,r=null){const n=this.nodeFrame;return n.renderer=e,n.scene=t,n.object=s,n.camera=i,n.material=r,n}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}hasOutputChange(e){return JR.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,s=this.getOutputCacheKey(),i=e.isArrayTexture?NA(e,Gd(py,ly("gl_ViewID_OVR"))).renderOutput(t.toneMapping,t.currentColorSpace):ty(e,py).renderOutput(t.toneMapping,t.currentColorSpace);return JR.set(e,s),i}updateBefore(e){const t=e.getNodeBuilderState();for(const s of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(s)}updateAfter(e){const t=e.getNodeBuilderState();for(const s of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(s)}updateForCompute(e){const t=this.getNodeFrame(),s=this.getForCompute(e);for(const e of s.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),s=e.getNodeBuilderState();for(const e of s.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new BR,this.nodeBuilderCache=new Map,this.cacheLib={}}}const iP=new hu;class rP{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new fa,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,null!==e&&(this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass,this.viewMatrix=e.viewMatrix)}projectPlanes(e,t,s){const i=e.length;for(let r=0;r<i;r++){iP.copy(e[r]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const i=t[s+r],n=iP.normal;i.x=-n.x,i.y=-n.y,i.z=-n.z,i.w=iP.constant}}updateGlobal(e,t){this.shadowPass=null!==e.overrideMaterial&&e.overrideMaterial.isShadowPassMaterial,this.viewMatrix=t.matrixWorldInverse,this.viewNormalMatrix.getNormalMatrix(this.viewMatrix)}update(e,t){let s=!1;e.version!==this.parentVersion&&(this.intersectionPlanes=Array.from(e.intersectionPlanes),this.unionPlanes=Array.from(e.unionPlanes),this.parentVersion=e.version),this.clipIntersection!==t.clipIntersection&&(this.clipIntersection=t.clipIntersection,this.clipIntersection?this.unionPlanes.length=e.unionPlanes.length:this.intersectionPlanes.length=e.intersectionPlanes.length);const i=t.clippingPlanes,r=i.length;let n,o;if(this.clipIntersection?(n=this.intersectionPlanes,o=e.intersectionPlanes.length):(n=this.unionPlanes,o=e.unionPlanes.length),n.length!==o+r){n.length=o+r;for(let e=0;e<r;e++)n[o+e]=new Pa;s=!0}this.projectPlanes(i,n,o),s&&(this.version++,this.cacheKey=`${this.intersectionPlanes.length}:${this.unionPlanes.length}`)}getGroupContext(e){if(this.shadowPass&&!e.clipShadows)return this;let t=this.clippingGroupContexts.get(e);return void 0===t&&(t=new rP(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class nP{constructor(e,t){this.bundleGroup=e,this.camera=t}}const oP=[];class aP{constructor(){this.bundles=new aS}get(e,t){const s=this.bundles;oP[0]=e,oP[1]=t;let i=s.get(oP);return void 0===i&&(i=new nP(e,t),s.set(oP,i)),oP.length=0,i}dispose(){this.bundles=new aS}}class lP{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null;const s=this.getMaterialNodeClass(e.type);if(null!==s){t=new s;for(const s in e)t[s]=e[s]}return t}addToneMapping(e,t){this.addType(e,t,this.toneMappingNodes)}getToneMappingFunction(e){return this.toneMappingNodes.get(e)||null}getMaterialNodeClass(e){return this.materialNodes.get(e)||null}addMaterial(e,t){this.addType(e,t,this.materialNodes)}getLightNodeClass(e){return this.lightNodes.get(e)||null}addLight(e,t){this.addClass(e,t,this.lightNodes)}addType(e,t,s){if(s.has(t))Yo(`Redefinition of node ${t}`);else{if("function"!=typeof e)throw new Error(`Node class ${e.name} is not a class.`);if("function"==typeof t||"object"==typeof t)throw new Error(`Base class ${t} is not a class.`);s.set(t,e)}}addClass(e,t,s){if(s.has(t))Yo(`Redefinition of node ${t.name}`);else{if("function"!=typeof e)throw new Error(`Node class ${e.name} is not a class.`);if("function"!=typeof t)throw new Error(`Base class ${t.name} is not a class.`);s.set(t,e)}}}const hP=new xE,uP=[];class cP extends aS{constructor(){super()}createNode(e=[]){return(new xE).setLights(e)}getNode(e,t){if(e.isQuadMesh)return hP;uP[0]=e,uP[1]=t;let s=this.get(uP);return void 0===s&&(s=this.createNode(),this.set(uP,s)),uP.length=0,s}}class dP extends Ba{constructor(e=1,t=1,s={}){super(e,t,s),this.isXRRenderTarget=!0,this._hasExternalTextures=!1,this._autoAllocateDepthBuffer=!0,this._isOpaqueFramebuffer=!1}copy(e){return super.copy(e),this._hasExternalTextures=e._hasExternalTextures,this._autoAllocateDepthBuffer=e._autoAllocateDepthBuffer,this._isOpaqueFramebuffer=e._isOpaqueFramebuffer,this}}const pP=new da,mP=new da;class fP extends Ko{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new Wh,this._cameraL.viewport=new Pa,this._cameraR=new Wh,this._cameraR.viewport=new Pa,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new Qu,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._sessionUsesLayers=!1,this._supportsGlBinding="undefined"!=typeof XRWebGLBinding,this._frameBufferTargets=null,this._createXRLayer=_P.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new ua,this._onSessionEvent=yP.bind(this),this._onSessionEnd=xP.bind(this),this._onInputSourcesChange=bP.bind(this),this._onAnimationFrame=wP.bind(this),this._referenceSpace=null,this._referenceSpaceType="local-floor",this._customReferenceSpace=null,this._framebufferScaleFactor=1,this._foveation=1,this._session=null,this._glBaseLayer=null,this._glBinding=null,this._glProjLayer=null,this._xrFrame=null,this._supportsLayers=this._supportsGlBinding&&"createProjectionLayer"in XRWebGLBinding.prototype,this._useMultiviewIfPossible=t,this._useMultiview=!1}getController(e){return this._getController(e).getTargetRaySpace()}getControllerGrip(e){return this._getController(e).getGripSpace()}getHand(e){return this._getController(e).getHandSpace()}getFoveation(){if(null!==this._glProjLayer||null!==this._glBaseLayer)return this._foveation}setFoveation(e){this._foveation=e,null!==this._glProjLayer&&(this._glProjLayer.fixedFoveation=e),null!==this._glBaseLayer&&void 0!==this._glBaseLayer.fixedFoveation&&(this._glBaseLayer.fixedFoveation=e)}getFramebufferScaleFactor(){return this._framebufferScaleFactor}setFramebufferScaleFactor(e){this._framebufferScaleFactor=e,!0===this.isPresenting&&Yo("XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,!0===this.isPresenting&&Yo("XRManager: Cannot change reference space type while presenting.")}getReferenceSpace(){return this._customReferenceSpace||this._referenceSpace}setReferenceSpace(e){this._customReferenceSpace=e}getCamera(){return this._cameraXR}getEnvironmentBlendMode(){if(null!==this._session)return this._session.environmentBlendMode}getBinding(){return null===this._glBinding&&this._supportsGlBinding&&(this._glBinding=new XRWebGLBinding(this._session,this._gl)),this._glBinding}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,s,i,r,n,o,a={}){const l=new Tu(e,t),h=new dP(r,n,{format:Ln,type:wn,depthTexture:new _u(r,n,a.stencil?Pn:An,void 0,void 0,void 0,void 0,void 0,void 0,a.stencil?On:Fn),stencilBuffer:a.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});h._autoAllocateDepthBuffer=!0;const u=new rh({color:16777215,side:0});u.map=h.texture,u.map.offset.y=1,u.map.repeat.y=-1;const c=new Fh(l,u);c.position.copy(s),c.quaternion.copy(i);const d={type:"quad",width:e,height:t,translation:s,quaternion:i,pixelwidth:r,pixelheight:n,plane:c,material:u,rendercall:o,renderTarget:h};if(this._layers.push(d),null!==this._session){d.plane.material=new rh({color:16777215,side:0}),d.plane.material.blending=5,d.plane.material.blendEquation=Yr,d.plane.material.blendSrc=Kr,d.plane.material.blendDst=Kr,d.xrlayer=this._createXRLayer(d);const e=this._session.renderState.layers;e.unshift(d.xrlayer),this._session.updateRenderState({layers:e})}else h.isXRRenderTarget=!1;return c}createCylinderLayer(e,t,s,i,r,n,o,a,l={}){const h=new vu(e,e,e*t/s,64,64,!0,Math.PI-t/2,t),u=new dP(n,o,{format:Ln,type:wn,depthTexture:new _u(n,o,l.stencil?Pn:An,void 0,void 0,void 0,void 0,void 0,void 0,l.stencil?On:Fn),stencilBuffer:l.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});u._autoAllocateDepthBuffer=!0;const c=new rh({color:16777215,side:1});c.map=u.texture,c.map.offset.y=1,c.map.repeat.y=-1;const d=new Fh(h,c);d.position.copy(i),d.quaternion.copy(r);const p={type:"cylinder",radius:e,centralAngle:t,aspectratio:s,translation:i,quaternion:r,pixelwidth:n,pixelheight:o,plane:d,material:c,rendercall:a,renderTarget:u};if(this._layers.push(p),null!==this._session){p.plane.material=new rh({color:16777215,side:1}),p.plane.material.blending=5,p.plane.material.blendEquation=Yr,p.plane.material.blendSrc=Kr,p.plane.material.blendDst=Kr,p.xrlayer=this._createXRLayer(p);const e=this._session.renderState.layers;e.unshift(p.xrlayer),this._session.updateRenderState({layers:e})}else u.isXRRenderTarget=!1;return d}renderLayers(){const e=new da,t=new ca,s=this._renderer,i=this.isPresenting,r=s.getOutputRenderTarget(),n=s._frameBufferTarget;this.isPresenting=!1;const o=new ua;s.getSize(o);const a=s._quad;for(const i of this._layers)if(i.renderTarget.isXRRenderTarget=null!==this._session,i.renderTarget._hasExternalTextures=i.renderTarget.isXRRenderTarget,i.renderTarget.isXRRenderTarget&&this._sessionUsesLayers){i.xrlayer.transform=new XRRigidTransform(i.plane.getWorldPosition(e),i.plane.getWorldQuaternion(t));const r=this._glBinding.getSubImage(i.xrlayer,this._xrFrame);s.backend.setXRRenderTargetTextures(i.renderTarget,r.colorTexture,void 0),s._setXRLayerSize(i.renderTarget.width,i.renderTarget.height),s.setOutputRenderTarget(i.renderTarget),s.setRenderTarget(null),s._frameBufferTarget=null,this._frameBufferTargets||(this._frameBufferTargets=new WeakMap);const{frameBufferTarget:n,quad:o}=this._frameBufferTargets.get(i.renderTarget)||{frameBufferTarget:null,quad:null};n?(s._frameBufferTarget=n,s._quad=o):(s._quad=new tA(new gw),this._frameBufferTargets.set(i.renderTarget,{frameBufferTarget:s._getFrameBufferTarget(),quad:s._quad})),i.rendercall(),s._frameBufferTarget=null}else s.setRenderTarget(i.renderTarget),i.rendercall();s.setRenderTarget(null),s.setOutputRenderTarget(r),s._frameBufferTarget=n,s._setXRLayerSize(o.x,o.y),s._quad=a,this.isPresenting=i}getSession(){return this._session}async setSession(e){const t=this._renderer,s=t.backend;this._gl=t.getContext();const i=this._gl,r=i.getContextAttributes();if(this._session=e,null!==e){if(!0===s.isWebGPUBackend)throw new Error('THREE.XRManager: XR is currently not supported with a WebGPU backend. Use WebGL by passing "{ forceWebGL: true }" to the constructor of the renderer.');if(e.addEventListener("select",this._onSessionEvent),e.addEventListener("selectstart",this._onSessionEvent),e.addEventListener("selectend",this._onSessionEvent),e.addEventListener("squeeze",this._onSessionEvent),e.addEventListener("squeezestart",this._onSessionEvent),e.addEventListener("squeezeend",this._onSessionEvent),e.addEventListener("end",this._onSessionEnd),e.addEventListener("inputsourceschange",this._onInputSourcesChange),await s.makeXRCompatible(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),!0===this._supportsLayers){let s=null,n=null,o=null;t.depth&&(o=t.stencil?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24,s=t.stencil?On:Fn,n=t.stencil?Pn:An);const a={colorFormat:i.RGBA8,depthFormat:o,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(a.textureType="texture-array",this._useMultiview=!0),this._glBinding=this.getBinding();const l=this._glBinding.createProjectionLayer(a),h=[l];this._glProjLayer=l,t.setPixelRatio(1),t._setXRLayerSize(l.textureWidth,l.textureHeight);const u=this._useMultiview?2:1,c=new _u(l.textureWidth,l.textureHeight,n,void 0,void 0,void 0,void 0,void 0,void 0,s,u);if(this._xrRenderTarget=new dP(l.textureWidth,l.textureHeight,{format:Ln,type:wn,colorSpace:t.outputColorSpace,depthTexture:c,stencilBuffer:t.stencil,samples:r.antialias?4:0,resolveDepthBuffer:!1===l.ignoreDepthValues,resolveStencilBuffer:!1===l.ignoreDepthValues,depth:this._useMultiview?2:1,multiview:this._useMultiview}),this._xrRenderTarget._hasExternalTextures=!0,this._xrRenderTarget.depth=this._useMultiview?2:1,this._sessionUsesLayers=e.enabledFeatures.includes("layers"),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._sessionUsesLayers)for(const e of this._layers)e.plane.material=new rh({color:16777215,side:"cylinder"===e.type?1:0}),e.plane.material.blending=5,e.plane.material.blendEquation=Yr,e.plane.material.blendSrc=Kr,e.plane.material.blendDst=Kr,e.xrlayer=this._createXRLayer(e),h.unshift(e.xrlayer);e.updateRenderState({layers:h})}else{const s={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},r=new XRWebGLLayer(e,i,s);this._glBaseLayer=r,e.updateRenderState({baseLayer:r}),t.setPixelRatio(1),t._setXRLayerSize(r.framebufferWidth,r.framebufferHeight),this._xrRenderTarget=new dP(r.framebufferWidth,r.framebufferHeight,{format:Ln,type:wn,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:!1===r.ignoreDepthValues,resolveStencilBuffer:!1===r.ignoreDepthValues}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}this.setFoveation(this.getFoveation()),t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(null===t)return;const s=e.near,i=e.far,r=this._cameraXR,n=this._cameraL,o=this._cameraR;r.near=o.near=n.near=s,r.far=o.far=n.far=i,r.isMultiViewCamera=this._useMultiview,this._currentDepthNear===r.near&&this._currentDepthFar===r.far||(t.updateRenderState({depthNear:r.near,depthFar:r.far}),this._currentDepthNear=r.near,this._currentDepthFar=r.far),r.layers.mask=6|e.layers.mask,n.layers.mask=3&r.layers.mask,o.layers.mask=5&r.layers.mask;const a=e.parent,l=r.cameras;gP(r,a);for(let e=0;e<l.length;e++)gP(l[e],a);2===l.length?function(e,t,s){pP.setFromMatrixPosition(t.matrixWorld),mP.setFromMatrixPosition(s.matrixWorld);const i=pP.distanceTo(mP),r=t.projectionMatrix.elements,n=s.projectionMatrix.elements,o=r[14]/(r[10]-1),a=r[14]/(r[10]+1),l=(r[9]+1)/r[5],h=(r[9]-1)/r[5],u=(r[8]-1)/r[0],c=(n[8]+1)/n[0],d=o*u,p=o*c,m=i/(-u+c),f=m*-u;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(f),e.translateZ(m),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),-1===r[10])e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{const t=o+m,s=a+m,r=d-f,n=p+(i-f),u=l*a/s*t,c=h*a/s*t;e.projectionMatrix.makePerspective(r,n,u,c,t,s),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}(r,n,o):r.projectionMatrix.copy(n.projectionMatrix),function(e,t,s){null===s?e.matrix.copy(t.matrixWorld):(e.matrix.copy(s.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld));e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=2*sa*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,r,a)}_getController(e){let t=this._controllers[e];return void 0===t&&(t=new Kh,this._controllers[e]=t),t}}function gP(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}function yP(e){const t=this._controllerInputSources.indexOf(e.inputSource);if(-1===t)return;const s=this._controllers[t];if(void 0!==s){const t=this.getReferenceSpace();s.update(e.inputSource,e.frame,t),s.dispatchEvent({type:e.type,data:e.inputSource})}}function xP(){const e=this._session,t=this._renderer;e.removeEventListener("select",this._onSessionEvent),e.removeEventListener("selectstart",this._onSessionEvent),e.removeEventListener("selectend",this._onSessionEvent),e.removeEventListener("squeeze",this._onSessionEvent),e.removeEventListener("squeezestart",this._onSessionEvent),e.removeEventListener("squeezeend",this._onSessionEvent),e.removeEventListener("end",this._onSessionEnd),e.removeEventListener("inputsourceschange",this._onInputSourcesChange);for(let e=0;e<this._controllers.length;e++){const t=this._controllerInputSources[e];null!==t&&(this._controllerInputSources[e]=null,this._controllers[e].disconnect(t))}if(this._currentDepthNear=null,this._currentDepthFar=null,t._resetXRState(),this._session=null,this._xrRenderTarget=null,this._glBinding=null,this._glBaseLayer=null,this._glProjLayer=null,!0===this._sessionUsesLayers)for(const e of this._layers)e.renderTarget=new dP(e.pixelwidth,e.pixelheight,{format:Ln,type:wn,depthTexture:new _u(e.pixelwidth,e.pixelheight,e.stencilBuffer?Pn:An,void 0,void 0,void 0,void 0,void 0,void 0,e.stencilBuffer?On:Fn),stencilBuffer:e.stencilBuffer,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),e.renderTarget.isXRRenderTarget=!1,e.plane.material=e.material,e.material.map=e.renderTarget.texture,e.material.map.offset.y=1,e.material.map.repeat.y=-1,delete e.xrlayer;this.isPresenting=!1,this._useMultiview=!1,t._animation.stop(),t._animation.setAnimationLoop(this._currentAnimationLoop),t._animation.setContext(this._currentAnimationContext),t._animation.start(),t.setPixelRatio(this._currentPixelRatio),t.setSize(this._currentSize.width,this._currentSize.height,!1),this.dispatchEvent({type:"sessionend"})}function bP(e){const t=this._controllers,s=this._controllerInputSources;for(let i=0;i<e.removed.length;i++){const r=e.removed[i],n=s.indexOf(r);n>=0&&(s[n]=null,t[n].disconnect(r))}for(let i=0;i<e.added.length;i++){const r=e.added[i];let n=s.indexOf(r);if(-1===n){for(let e=0;e<t.length;e++){if(e>=s.length){s.push(r),n=e;break}if(null===s[e]){s[e]=r,n=e;break}}if(-1===n)break}const o=t[n];o&&o.connect(r)}}function _P(e){return"quad"===e.type?this._glBinding.createQuadLayer({transform:new XRRigidTransform(e.translation,e.quaternion),width:e.width/2,height:e.height/2,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(e.translation,e.quaternion),radius:e.radius,centralAngle:e.centralAngle,aspectRatio:e.aspectRatio,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1})}function wP(e,t){if(void 0===t)return;const s=this._cameraXR,i=this._renderer,r=i.backend,n=this._glBaseLayer,o=this.getReferenceSpace(),a=t.getViewerPose(o);if(this._xrFrame=t,null!==a){const e=a.views;null!==this._glBaseLayer&&r.setXRTarget(n.framebuffer);let t=!1;e.length!==s.cameras.length&&(s.cameras.length=0,t=!0);for(let i=0;i<e.length;i++){const o=e[i];let a;if(!0===this._supportsLayers){const e=this._glBinding.getViewSubImage(this._glProjLayer,o);a=e.viewport,0===i&&r.setXRRenderTargetTextures(this._xrRenderTarget,e.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:e.depthStencilTexture)}else a=n.getViewport(o);let l=this._cameras[i];void 0===l&&(l=new Wh,l.layers.enable(i),l.viewport=new Pa,this._cameras[i]=l),l.matrix.fromArray(o.transform.matrix),l.matrix.decompose(l.position,l.quaternion,l.scale),l.projectionMatrix.fromArray(o.projectionMatrix),l.projectionMatrixInverse.copy(l.projectionMatrix).invert(),l.viewport.set(a.x,a.y,a.width,a.height),0===i&&(s.matrix.copy(l.matrix),s.matrix.decompose(s.position,s.quaternion,s.scale)),!0===t&&s.cameras.push(l)}i.setOutputRenderTarget(this._xrRenderTarget)}for(let e=0;e<this._controllers.length;e++){const s=this._controllerInputSources[e],i=this._controllers[e];null!==s&&void 0!==i&&i.update(s,t,o)}this._currentAnimationLoop&&this._currentAnimationLoop(e,t),t.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:t}),this._xrFrame=null}class vP extends Ko{constructor(e){super(),this.domElement=e,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new Pa(0,0,this._width,this._height),this._scissor=new Pa(0,0,this._width,this._height),this._scissorTest=!1,this.colorTexture=new bu,this.depthTexture=new _u}getPixelRatio(){return this._pixelRatio}getDrawingBufferSize(e){return e.set(this._width*this._pixelRatio,this._height*this._pixelRatio).floor()}getSize(e){return e.set(this._width,this._height)}setPixelRatio(e=1){this._pixelRatio!==e&&(this._pixelRatio=e,this.setSize(this._width,this._height,!1))}setDrawingBufferSize(e,t,s){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=s,this.domElement.width=Math.floor(e*s),this.domElement.height=Math.floor(t*s),this.setViewport(0,0,e,t),this._dispatchResize())}setSize(e,t,s=!0){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===s&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._dispatchResize())}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,s,i){const r=this._scissor;e.isVector4?r.copy(e):r.set(e,t,s,i)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,s,i,r=0,n=1){const o=this._viewport;e.isVector4?o.copy(e):o.set(e,t,s,i),o.minDepth=r,o.maxDepth=n}_dispatchResize(){this.dispatchEvent({type:"resize"})}dispose(){this.dispatchEvent({type:"dispose"})}}const TP=new Jh,SP=new ua,MP=new Pa,AP=new pu,NP=new gu,EP=new ll,CP=new Pa;class RP{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:s=!1,alpha:i=!0,depth:r=!0,stencil:n=!1,antialias:o=!1,samples:a=0,getFallback:l=null,outputBufferType:h=En,multiview:u=!1}=t;this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=i,this.logarithmicDepthBuffer=s,this.outputColorSpace=Mo,this.toneMapping=0,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=r,this.stencil=n,this.info=new vS,this.contextNode=Gf(),this.library=new lP,this.lighting=new cP,this._samples=a||!0===o?4:0,this._onCanvasTargetResize=this._onCanvasTargetResize.bind(this),this._canvasTarget=new vP(e.getDomElement()),this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize),this._canvasTarget.isDefaultCanvasTarget=!0,this._inspector=new Gg,this._inspector.setRenderer(this),this._getFallback=l,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quad=new tA(new gw),this._quad.name="Output Color Transform",this._quad.material.name="outputColorTransform",this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTarget=null;const c=!0===this.alpha?0:1;this._clearColor=new WS(0,0,0,c),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._outputRenderTarget=null,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._isDeviceLost=!1,this.onDeviceLost=this._onDeviceLost,this._outputBufferType=h,this._cacheShadowNodes=new WeakMap,this._initialized=!1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,type:1},this.xr=new fP(this,u),this.debug={checkShaderErrors:!0,onShaderError:null,getShaderAsync:async(e,t,s)=>{await this.compileAsync(e,t);const i=this._renderLists.get(e,t),r=this._renderContexts.get(e,t,this._renderTarget,this._mrt),n=e.overrideMaterial||s.material,o=this._objects.get(s,n,e,t,i.lightsNode,r,r.clippingContext),{fragmentShader:a,vertexShader:l}=o.getNodeBuilderState();return{fragmentShader:a,vertexShader:l}}}}async init(){return null!==this._initPromise||(this._initPromise=new Promise(async(e,t)=>{let s=this.backend;try{await s.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=s=this._getFallback(e),await s.init(this)}catch(e){return void t(e)}}this._nodes=new sP(this,s),this._animation=new oS(this,this._nodes,this.info),this._attributes=new xS(s),this._background=new QC(this,this._nodes),this._geometries=new wS(this._attributes,this.info),this._textures=new $S(this,s,this.info),this._pipelines=new ES(s,this._nodes),this._bindings=new CS(s,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new cS(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new LS(this.lighting),this._bundles=new aP,this._renderContexts=new GS,this._animation.start(),this._initialized=!0,this._inspector.init(),e(this)})),this._initPromise}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,s=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const i=this._nodes.nodeFrame,r=i.renderId,n=this._currentRenderContext,o=this._currentRenderObjectFunction,a=this._compilationPromises,l=!0===e.isScene?e:TP;null===s&&(s=e);const h=this._renderTarget,u=this._renderContexts.get(s,t,h,this._mrt),c=this._activeMipmapLevel,d=[];this._currentRenderContext=u,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=d,i.renderId++,i.update(),u.depth=this.depth,u.stencil=this.stencil,u.clippingContext||(u.clippingContext=new rP),u.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,h);const p=this._renderLists.get(e,t);if(p.begin(),this._projectObject(e,t,0,p,u.clippingContext),s!==e&&s.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&p.pushLight(e)}),p.finish(),null!==h){this._textures.updateRenderTarget(h,c);const e=this._textures.get(h);u.textures=e.textures,u.depthTexture=e.depthTexture}else u.textures=null,u.depthTexture=null;this._background.update(l,p,u);const m=p.opaque,f=p.transparent,g=p.transparentDoublePass,y=p.lightsNode;!0===this.opaque&&m.length>0&&this._renderObjects(m,t,l,y),!0===this.transparent&&f.length>0&&this._renderTransparents(f,g,t,l,y),i.renderId=r,this._currentRenderContext=n,this._currentRenderObjectFunction=o,this._compilationPromises=a,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(d)}async renderAsync(e,t){Qo('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){Zo("Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.")}set inspector(e){null!==this._inspector&&this._inspector.setRenderer(null),this._inspector=e,this._inspector.setRenderer(this)}get inspector(){return this._inspector}set highPrecision(e){const t=this.contextNode.value;!0===e?(t.modelViewMatrix=Zy,t.modelNormalViewMatrix=Qy):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===Zy&&e.modelNormalViewMatrix===Qy}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return Qo('Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".'),this.getOutputBufferType()}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:\n\nMessage: ${e.message}`;e.reason&&(t+=`\nReason: ${e.reason}`),Zo(t),this._isDeviceLost=!0}_renderBundle(e,t,s){const{bundleGroup:i,camera:r,renderList:n}=e,o=this._currentRenderContext,a=this._bundles.get(i,r),l=this.backend.get(a);void 0===l.renderContexts&&(l.renderContexts=new Set);const h=i.version!==l.version,u=!1===l.renderContexts.has(o)||h;if(l.renderContexts.add(o),u){this.backend.beginBundle(o),(void 0===l.renderObjects||h)&&(l.renderObjects=[]),this._currentRenderBundle=a;const{transparentDoublePass:e,transparent:u,opaque:c}=n;!0===this.opaque&&c.length>0&&this._renderObjects(c,r,t,s),!0===this.transparent&&u.length>0&&this._renderTransparents(u,e,r,t,s),this._currentRenderBundle=null,this.backend.finishBundle(o,a),l.version=i.version}else{const{renderObjects:e}=l;for(let t=0,s=e.length;t<s;t++){const s=e[t];this._nodes.needsRefresh(s)&&(this._nodes.updateBefore(s),this._nodes.updateForRender(s),this._bindings.updateForRender(s),this._nodes.updateAfter(s))}}this.backend.addBundle(o,a)}render(e,t){if(!1===this._initialized)throw new Error('Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.');this._renderScene(e,t)}get initialized(){return this._initialized}_getFrameBufferTarget(){const{currentToneMapping:e,currentColorSpace:t}=this,s=0!==e,i=t!==_a.workingColorSpace;if(!1===s&&!1===i)return null;const{width:r,height:n}=this.getDrawingBufferSize(SP),{depth:o,stencil:a}=this;let l=this._frameBufferTarget;null===l&&(l=new Ba(r,n,{depthBuffer:o,stencilBuffer:a,type:this._outputBufferType,format:Ln,colorSpace:_a.workingColorSpace,generateMipmaps:!1,minFilter:xn,magFilter:xn,samples:this.samples}),l.isPostProcessingRenderTarget=!0,this._frameBufferTarget=l);const h=this.getOutputRenderTarget();l.depthBuffer=o,l.stencilBuffer=a,null!==h?l.setSize(h.width,h.height,h.depth):l.setSize(r,n,1);const u=this._canvasTarget;return l.viewport.copy(u._viewport),l.scissor.copy(u._scissor),l.viewport.multiplyScalar(u._pixelRatio),l.scissor.multiplyScalar(u._pixelRatio),l.scissorTest=u._scissorTest,l.multiview=null!==h&&h.multiview,l.resolveDepthBuffer=null===h||h.resolveDepthBuffer,l._autoAllocateDepthBuffer=null!==h&&h._autoAllocateDepthBuffer,l}_renderScene(e,t,s=!0){if(!0===this._isDeviceLost)return;const i=s?this._getFrameBufferTarget():null,r=this._nodes.nodeFrame,n=r.renderId,o=this._currentRenderContext,a=this._currentRenderObjectFunction,l=!0===e.isScene?e:TP,h=this._renderTarget||this._outputRenderTarget,u=this._activeCubeFace,c=this._activeMipmapLevel;let d;null!==i?(d=i,this.setRenderTarget(d)):d=h;const p=this._renderContexts.get(e,t,d,this._mrt);this._currentRenderContext=p,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,r.renderId=this.info.calls,this.backend.updateTimeStampUID(p),this.inspector.beginRender(this.backend.getTimestampUID(p),e,t,d);const m=this.coordinateSystem,f=this.xr;if(t.coordinateSystem!==m&&!1===f.isPresenting&&(t.coordinateSystem=m,t.updateProjectionMatrix(),t.isArrayCamera))for(const e of t.cameras)e.coordinateSystem=m,e.updateProjectionMatrix();!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0===f.enabled&&!0===f.isPresenting&&(!0===f.cameraAutoUpdate&&f.updateCamera(t),t=f.getCamera());const g=this._canvasTarget;let y=g._viewport,x=g._scissor,b=g._pixelRatio;null!==d&&(y=d.viewport,x=d.scissor,b=1),this.getDrawingBufferSize(SP),MP.set(0,0,SP.width,SP.height);const _=void 0===y.minDepth?0:y.minDepth,w=void 0===y.maxDepth?1:y.maxDepth;p.viewportValue.copy(y).multiplyScalar(b).floor(),p.viewportValue.width>>=c,p.viewportValue.height>>=c,p.viewportValue.minDepth=_,p.viewportValue.maxDepth=w,p.viewport=!1===p.viewportValue.equals(MP),p.scissorValue.copy(x).multiplyScalar(b).floor(),p.scissor=g._scissorTest&&!1===p.scissorValue.equals(MP),p.scissorValue.width>>=c,p.scissorValue.height>>=c,p.clippingContext||(p.clippingContext=new rP),p.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,d);const v=t.isArrayCamera?NP:AP;t.isArrayCamera||(EP.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),v.setFromProjectionMatrix(EP,t.coordinateSystem,t.reversedDepth));const T=this._renderLists.get(e,t);if(T.begin(),this._projectObject(e,t,0,T,p.clippingContext),T.finish(),!0===this.sortObjects&&T.sort(this._opaqueSort,this._transparentSort),null!==d){this._textures.updateRenderTarget(d,c);const e=this._textures.get(d);p.textures=e.textures,p.depthTexture=e.depthTexture,p.width=e.width,p.height=e.height,p.renderTarget=d,p.depth=d.depthBuffer,p.stencil=d.stencilBuffer}else p.textures=null,p.depthTexture=null,p.width=SP.width,p.height=SP.height,p.depth=this.depth,p.stencil=this.stencil;p.width>>=c,p.height>>=c,p.activeCubeFace=u,p.activeMipmapLevel=c,p.occlusionQueryCount=T.occlusionQueryCount,p.scissorValue.max(CP.set(0,0,0,0)),p.scissorValue.x+p.scissorValue.width>p.width&&(p.scissorValue.width=Math.max(p.width-p.scissorValue.x,0)),p.scissorValue.y+p.scissorValue.height>p.height&&(p.scissorValue.height=Math.max(p.height-p.scissorValue.y,0)),this._background.update(l,T,p),p.camera=t,this.backend.beginRender(p);const{bundles:S,lightsNode:M,transparentDoublePass:A,transparent:N,opaque:E}=T;return S.length>0&&this._renderBundles(S,l,M),!0===this.opaque&&E.length>0&&this._renderObjects(E,t,l,M),!0===this.transparent&&N.length>0&&this._renderTransparents(N,A,t,l,M),this.backend.finishRender(p),r.renderId=n,this._currentRenderContext=o,this._currentRenderObjectFunction=a,null!==i&&(this.setRenderTarget(h,u,c),this._renderOutput(d)),l.onAfterRender(this,e,t,d),this.inspector.finishRender(this.backend.getTimestampUID(p)),p}_setXRLayerSize(e,t){this._canvasTarget._width=e,this._canvasTarget._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._quad;this._nodes.hasOutputChange(e.texture)&&(t.material.fragmentNode=this._nodes.getOutputNode(e.texture),t.material.needsUpdate=!0);const s=this.autoClear,i=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(t,t.camera,!1),this.autoClear=s,this.xr.enabled=i}getMaxAnisotropy(){return this.backend.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}getAnimationLoop(){return this._animation.getAnimationLoop()}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._canvasTarget.getPixelRatio()}getDrawingBufferSize(e){return this._canvasTarget.getDrawingBufferSize(e)}getSize(e){return this._canvasTarget.getSize(e)}setPixelRatio(e=1){this._canvasTarget.setPixelRatio(e)}setDrawingBufferSize(e,t,s){this.xr&&this.xr.isPresenting||this._canvasTarget.setDrawingBufferSize(e,t,s)}setSize(e,t,s=!0){this.xr&&this.xr.isPresenting||this._canvasTarget.setSize(e,t,s)}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){return this._canvasTarget.getScissor(e)}setScissor(e,t,s,i){this._canvasTarget.setScissor(e,t,s,i)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,s,i,r=0,n=1){this._canvasTarget.setViewport(e,t,s,i,r,n)}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,s=!0){if(!1===this._initialized)throw new Error('Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.');const i=this._renderTarget||this._getFrameBufferTarget();let r=null;if(null!==i){this._textures.updateRenderTarget(i);const e=this._textures.get(i);r=this._renderContexts.getForClear(i),r.textures=e.textures,r.depthTexture=e.depthTexture,r.width=e.width,r.height=e.height,r.renderTarget=i,r.depth=i.depthBuffer,r.stencil=i.stencilBuffer,r.clearColorValue=this.backend.getClearColor(),r.activeCubeFace=this.getActiveCubeFace(),r.activeMipmapLevel=this.getActiveMipmapLevel()}this.backend.clear(e,t,s,r),null!==i&&null===this._renderTarget&&this._renderOutput(i)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,s=!0){Qo('Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.clear(e,t,s)}async clearColorAsync(){Qo('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){Qo('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){Qo('Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!1,!0)}get needsFrameBufferTarget(){const e=0!==this.currentToneMapping,t=this.currentColorSpace!==_a.workingColorSpace;return e||t}get samples(){return this._samples}get currentSamples(){let e=this._samples;return null!==this._renderTarget?e=this._renderTarget.samples:this.needsFrameBufferTarget&&(e=0),e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:0}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:_a.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){!0===this._initialized&&(this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),null!==this._frameBufferTarget&&this._frameBufferTarget.dispose(),Object.values(this.backend.timestampQueryPool).forEach(e=>{null!==e&&e.dispose()})),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,s=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=s}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}setCanvasTarget(e){this._canvasTarget.removeEventListener("resize",this._onCanvasTargetResize),this._canvasTarget=e,this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize)}getCanvasTarget(){return this._canvasTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null),this._frameBufferTarget.dispose(),this._frameBufferTarget=null}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e,t=null){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return Yo("Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e,t);const s=this._nodes.nodeFrame,i=s.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,s.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);const r=this.backend,n=this._pipelines,o=this._bindings,a=this._nodes,l=Array.isArray(e)?e:[e];if(void 0===l[0]||!0!==l[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");r.beginCompute(e);for(const s of l){if(!1===n.has(s)){const e=()=>{s.removeEventListener("dispose",e),n.delete(s),o.deleteForCompute(s),a.delete(s)};s.addEventListener("dispose",e);const t=s.onInitFunction;null!==t&&t.call(s,{renderer:this})}a.updateForCompute(s),o.updateForCompute(s);const i=o.getForCompute(s),l=n.getForCompute(s,i);r.compute(e,s,i,l,t)}r.finishCompute(e),s.renderId=i,this.inspector.finishCompute(this.backend.getTimestampUID(e))}async computeAsync(e,t=null){!1===this._initialized&&await this.init(),this.compute(e,t)}async hasFeatureAsync(e){return Qo('Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){if(!1===this._initialized)throw new Error('Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.');return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){Qo('Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.initTexture(e)}initTexture(e){if(!1===this._initialized)throw new Error('Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateTexture(e)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=CP.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void Zo("Renderer.copyFramebufferToTexture: Invalid rectangle.");t=CP.copy(t).floor()}else t=CP.set(0,0,e.image.width,e.image.height);let s,i=this._currentRenderContext;null!==i?s=i.renderTarget:(s=this._renderTarget||this._getFrameBufferTarget(),null!==s&&(this._textures.updateRenderTarget(s),i=this._textures.get(s))),this._textures.updateTexture(e,{renderTarget:s}),this.backend.copyFramebufferToTexture(e,i,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,s=null,i=null,r=0,n=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,s,i,r,n),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,s,i,r,n=0,o=0){return this.backend.copyTextureToBuffer(e.textures[n],t,s,i,r,o)}_projectObject(e,t,s,i,r){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)s=e.renderOrder,e.isClippingGroup&&e.enabled&&(r=r.getGroupContext(e));else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)i.pushLight(e);else if(e.isSprite){const n=t.isArrayCamera?NP:AP;if(!e.frustumCulled||n.intersectsSprite(e,t)){!0===this.sortObjects&&CP.setFromMatrixPosition(e.matrixWorld).applyMatrix4(EP);const{geometry:t,material:n}=e;n.visible&&i.push(e,t,n,s,CP.z,null,r)}}else if(e.isLineLoop)Zo("Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const n=t.isArrayCamera?NP:AP;if(!e.frustumCulled||n.intersectsObject(e,t)){const{geometry:t,material:n}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),CP.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(EP)),Array.isArray(n)){const o=t.groups;for(let a=0,l=o.length;a<l;a++){const l=o[a],h=n[l.materialIndex];h&&h.visible&&i.push(e,t,h,s,CP.z,l,r)}}else n.visible&&i.push(e,t,n,s,CP.z,null,r)}}if(!0===e.isBundleGroup&&void 0!==this.backend.beginBundle){const s=i;(i=this._renderLists.get(e,t)).begin(),s.pushBundle({bundleGroup:e,camera:t,renderList:i}),i.finish()}const n=e.children;for(let e=0,o=n.length;e<o;e++)this._projectObject(n[e],t,s,i,r)}_renderBundles(e,t,s){for(const i of e)this._renderBundle(i,t,s)}_renderTransparents(e,t,s,i,r){if(t.length>0){for(const{material:e}of t)e.side=1;this._renderObjects(t,s,i,r,"backSide");for(const{material:e}of t)e.side=0;this._renderObjects(e,s,i,r);for(const{material:e}of t)e.side=2}else this._renderObjects(e,s,i,r)}_renderObjects(e,t,s,i,r=null){for(let n=0,o=e.length;n<o;n++){const{object:o,geometry:a,material:l,group:h,clippingContext:u}=e[n];this._currentRenderObjectFunction(o,s,t,a,l,h,i,u,r)}}_getShadowNodes(e){const t=e.version;let s=this._cacheShadowNodes.get(e);if(void 0===s||s.version!==t){const i=null!==e.map,r=e.colorNode&&e.colorNode.isNode,n=e.castShadowNode&&e.castShadowNode.isNode;let o=null,a=null,l=null;if(i||r||n){let t,s;n?(t=e.castShadowNode.rgb,s=e.castShadowNode.a):(t=Gd(0),s=Dd(1)),i&&(s=s.mul(Ox("map","texture",e).a)),r&&(s=s.mul(e.colorNode.a)),a=Hd(t,s)}e.depthNode&&e.depthNode.isNode&&(l=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?o=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(o=e.positionNode),s={version:t,colorNode:a,depthNode:l,positionNode:o},this._cacheShadowNodes.set(e,s)}return s}renderObject(e,t,s,i,r,n,o,a=null,l=null){let h,u,c,d,p=!1;if(e.onBeforeRender(this,t,s,i,r,n),!0===r.allowOverride&&null!==t.overrideMaterial){const e=t.overrideMaterial;if(p=!0,h=t.overrideMaterial.colorNode,u=t.overrideMaterial.depthNode,c=t.overrideMaterial.positionNode,d=t.overrideMaterial.side,r.positionNode&&r.positionNode.isNode&&(e.positionNode=r.positionNode),e.alphaTest=r.alphaTest,e.alphaMap=r.alphaMap,e.transparent=r.transparent||r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode||r.backdropNode&&r.backdropNode.isNode,e.isShadowPassMaterial){const{colorNode:t,depthNode:s,positionNode:i}=this._getShadowNodes(r);e.side=null===r.shadowSide?r.side:r.shadowSide,null!==t&&(e.colorNode=t),null!==s&&(e.depthNode=s),null!==i&&(e.positionNode=i)}r=e}!0===r.transparent&&2===r.side&&!1===r.forceSinglePass?(r.side=1,this._handleObjectFunction(e,r,t,s,o,n,a,"backSide"),r.side=0,this._handleObjectFunction(e,r,t,s,o,n,a,l),r.side=2):this._handleObjectFunction(e,r,t,s,o,n,a,l),p&&(t.overrideMaterial.colorNode=h,t.overrideMaterial.depthNode=u,t.overrideMaterial.positionNode=c,t.overrideMaterial.side=d),e.onAfterRender(this,t,s,i,r,n)}_renderObjectDirect(e,t,s,i,r,n,o,a){const l=this._objects.get(e,t,s,i,r,this._currentRenderContext,o,a);l.drawRange=e.geometry.drawRange,l.group=n;const h=this._nodes.needsRefresh(l);if(h&&(this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l)),this._pipelines.updateForRender(l),null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(l),l.bundle=this._currentRenderBundle.bundleGroup}this.backend.draw(l,this.info),h&&this._nodes.updateAfter(l)}_createObjectPipeline(e,t,s,i,r,n,o,a){const l=this._objects.get(e,t,s,i,r,this._currentRenderContext,o,a);l.drawRange=e.geometry.drawRange,l.group=n,this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l),this._pipelines.getForRender(l,this._compilationPromises),this._nodes.updateAfter(l)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}get compile(){return this.compileAsync}}class PP{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}getVisibility(){return this.visibility}clone(){return Object.assign(new this.constructor,this)}}let BP=class extends PP{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t,this._updateRanges=[]}get updateRanges(){return this._updateRanges}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}get byteLength(){return(e=this._buffer.byteLength)+(yS-e%yS)%yS;var e}get buffer(){return this._buffer}update(){return!0}};class IP extends BP{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let DP=0;class LP extends IP{constructor(e,t){super("UniformBuffer_"+DP++,e?e.value:null),this.nodeUniform=e,this.groupNode=t,this.isNodeUniformBuffer=!0}set updateRanges(e){this.nodeUniform.updateRanges=e}get updateRanges(){return this.nodeUniform.updateRanges}addUpdateRange(e,t){this.nodeUniform.addUpdateRange(e,t)}clearUpdateRanges(){this.nodeUniform.clearUpdateRanges()}get buffer(){return this.nodeUniform.value}}class FP extends IP{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[]}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let s=0,i=this.uniforms.length;s<i;s++){const i=this.uniforms[s],r=i.boundary,n=i.itemSize*e,o=t%yS,a=o%r,l=o+a;t+=a,0!==l&&yS-l<n&&(t+=yS-l),i.offset=t/e,t+=n}return Math.ceil(t/yS)*yS}update(){let e=!1;for(const t of this.uniforms)!0===this.updateByType(t)&&(e=!0);return e}updateByType(e){return e.isNumberUniform?this.updateNumber(e):e.isVector2Uniform?this.updateVector2(e):e.isVector3Uniform?this.updateVector3(e):e.isVector4Uniform?this.updateVector4(e):e.isColorUniform?this.updateColor(e):e.isMatrix3Uniform?this.updateMatrix3(e):e.isMatrix4Uniform?this.updateMatrix4(e):void Zo("WebGPUUniformsGroup: Unsupported uniform type.",e)}updateNumber(e){let t=!1;const s=this.values,i=e.getValue(),r=e.offset,n=e.getType();if(s[r]!==i){this._getBufferForType(n)[r]=s[r]=i,t=!0}return t}updateVector2(e){let t=!1;const s=this.values,i=e.getValue(),r=e.offset,n=e.getType();if(s[r+0]!==i.x||s[r+1]!==i.y){const e=this._getBufferForType(n);e[r+0]=s[r+0]=i.x,e[r+1]=s[r+1]=i.y,t=!0}return t}updateVector3(e){let t=!1;const s=this.values,i=e.getValue(),r=e.offset,n=e.getType();if(s[r+0]!==i.x||s[r+1]!==i.y||s[r+2]!==i.z){const e=this._getBufferForType(n);e[r+0]=s[r+0]=i.x,e[r+1]=s[r+1]=i.y,e[r+2]=s[r+2]=i.z,t=!0}return t}updateVector4(e){let t=!1;const s=this.values,i=e.getValue(),r=e.offset,n=e.getType();if(s[r+0]!==i.x||s[r+1]!==i.y||s[r+2]!==i.z||s[r+4]!==i.w){const e=this._getBufferForType(n);e[r+0]=s[r+0]=i.x,e[r+1]=s[r+1]=i.y,e[r+2]=s[r+2]=i.z,e[r+3]=s[r+3]=i.w,t=!0}return t}updateColor(e){let t=!1;const s=this.values,i=e.getValue(),r=e.offset;if(s[r+0]!==i.r||s[r+1]!==i.g||s[r+2]!==i.b){const e=this.buffer;e[r+0]=s[r+0]=i.r,e[r+1]=s[r+1]=i.g,e[r+2]=s[r+2]=i.b,t=!0}return t}updateMatrix3(e){let t=!1;const s=this.values,i=e.getValue().elements,r=e.offset;if(s[r+0]!==i[0]||s[r+1]!==i[1]||s[r+2]!==i[2]||s[r+4]!==i[3]||s[r+5]!==i[4]||s[r+6]!==i[5]||s[r+8]!==i[6]||s[r+9]!==i[7]||s[r+10]!==i[8]){const e=this.buffer;e[r+0]=s[r+0]=i[0],e[r+1]=s[r+1]=i[1],e[r+2]=s[r+2]=i[2],e[r+4]=s[r+4]=i[3],e[r+5]=s[r+5]=i[4],e[r+6]=s[r+6]=i[5],e[r+8]=s[r+8]=i[6],e[r+9]=s[r+9]=i[7],e[r+10]=s[r+10]=i[8],t=!0}return t}updateMatrix4(e){let t=!1;const s=this.values,i=e.getValue().elements,r=e.offset;if(!1===function(e,t,s){for(let i=0,r=t.length;i<r;i++)if(e[s+i]!==t[i])return!1;return!0}(s,i,r)){this.buffer.set(i,r),function(e,t,s){for(let i=0,r=t.length;i<r;i++)e[s+i]=t[i]}(s,i,r),t=!0}return t}_getBufferForType(e){return"int"===e||"ivec2"===e||"ivec3"===e||"ivec4"===e?new Int32Array(this.buffer.buffer):"uint"===e||"uvec2"===e||"uvec3"===e||"uvec4"===e?new Uint32Array(this.buffer.buffer):this.buffer}}let OP=0;class VP extends FP{constructor(e,t){super(e),this.id=OP++,this.groupNode=t,this.isNodeUniformsGroup=!0}}class zP extends PP{constructor(e,t){super(e),this._texture=null,this._onTextureDispose=()=>{this.generation=null,this.version=0},this.texture=t,this.version=t?t.version:0,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture&&this._texture.removeEventListener("dispose",this._onTextureDispose),this._texture=e,this.generation=null,this.version=0,this._texture&&this._texture.addEventListener("dispose",this._onTextureDispose))}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}clone(){const e=super.clone();return e._texture=null,e._onTextureDispose=()=>{e.generation=null,e.version=0},e.texture=this.texture,e}}let kP=0;class UP extends zP{constructor(e,t){super(e,t),this.id=kP++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class GP extends UP{constructor(e,t,s,i=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s,this.access=i}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class jP extends GP{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledCubeTexture=!0}}class $P extends GP{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledTexture3D=!0}}const WP={bitcast_int_uint:new iN("uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }"),bitcast_uint_int:new iN("uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }")},HP={textureDimensions:"textureSize",equals:"equal",bitcast_float_int:"floatBitsToInt",bitcast_int_float:"intBitsToFloat",bitcast_uint_float:"uintBitsToFloat",bitcast_float_uint:"floatBitsToUint",bitcast_uint_int:"tsl_bitcast_uint_to_int",bitcast_int_uint:"tsl_bitcast_int_to_uint",floatpack_snorm_2x16:"packSnorm2x16",floatpack_unorm_2x16:"packUnorm2x16",floatpack_float16_2x16:"packHalf2x16",floatunpack_snorm_2x16:"unpackSnorm2x16",floatunpack_unorm_2x16:"unpackUnorm2x16",floatunpack_float16_2x16:"unpackHalf2x16"},qP={low:"lowp",medium:"mediump",high:"highp"},XP={swizzleAssign:!0,storageBuffer:!1},YP={perspective:"smooth",linear:"noperspective"},ZP={centroid:"centroid"},QP="\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp sampler3D;\nprecision highp samplerCube;\nprecision highp sampler2DArray;\n\nprecision highp usampler2D;\nprecision highp usampler3D;\nprecision highp usamplerCube;\nprecision highp usampler2DArray;\n\nprecision highp isampler2D;\nprecision highp isampler3D;\nprecision highp isamplerCube;\nprecision highp isampler2DArray;\n\nprecision lowp sampler2DShadow;\nprecision lowp sampler2DArrayShadow;\nprecision lowp samplerCubeShadow;\n";class KP extends PR{constructor(e,t){super(e,t,new KR),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==So}_include(e){const t=WP[e];return t.build(this),this.addInclude(t),t}getMethod(e){return void 0!==WP[e]&&this._include(e),HP[e]||e}getBitcastMethod(e,t){return this.getMethod(`bitcast_${t}_${e}`)}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,s){return`${e} ? ${t} : ${s}`}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,s=this.flowShaderNode(e),i=[];for(const e of t.inputs)i.push(this.getType(e.type)+" "+e.name);return`${this.getType(t.type)} ${t.name}( ${i.join(", ")} ) {\n\n\t${s.vars}\n\n${s.code}\n\treturn ${s.result};\n\n}`}setupPBO(e){const t=e.value;if(void 0===t.pbo){const e=t.array,s=t.count*t.itemSize,{itemSize:i}=t,r=t.array.constructor.name.toLowerCase().includes("int");let n=r?zn:Vn;2===i?n=r?Un:kn:3===i?n=r?1032:Dn:4===i&&(n=r?Gn:Ln);const o={Float32Array:Nn,Uint8Array:wn,Uint16Array:Sn,Uint32Array:An,Int8Array:vn,Int16Array:Tn,Int32Array:Mn,Uint8ClampedArray:wn},a=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(s/i))));let l=Math.ceil(s/i/a);a*l*i<s&&l++;const h=a*l*i,u=new e.constructor(h);u.set(e,0),t.array=u;const c=new ru(t.array,a,l,n,o[t.array.constructor.name]||Nn);c.needsUpdate=!0,c.isPBOTexture=!0;const d=new Jg(c,null,null);d.setPrecision("high"),t.pboNode=d,t.pbo=d.value,this.getUniformFromNode(t.pboNode,"texture",this.shaderStage,this.context.nodeName)}}getPropertyName(e,t=this.shaderStage){return e.isNodeUniform&&!0!==e.node.isTextureNode&&!0!==e.node.isBufferNode?t.charAt(0)+"_"+e.name:super.getPropertyName(e,t)}generatePBO(e){const{node:t,indexNode:s}=e,i=t.value;if(this.renderer.backend.has(i)){this.renderer.backend.get(i).pbo=i.pbo}const r=this.getUniformFromNode(i.pboNode,"texture",this.shaderStage,this.context.nodeName),n=this.getPropertyName(r);this.increaseUsage(s);const o=s.build(this,"uint"),a=this.getDataFromNode(e);let l=a.propertyName;if(void 0===l){const s=this.getVarFromNode(e);l=this.getPropertyName(s);const r=this.getDataFromNode(t);let h=r.propertySizeName;void 0===h&&(h=l+"Size",this.getVarFromNode(t,h,"uint"),this.addLineFlowCode(`${h} = uint( textureSize( ${n}, 0 ).x )`,e),r.propertySizeName=h);const{itemSize:u}=i,c="."+Ac.join("").slice(0,u),d=`ivec2(${o} % ${h}, ${o} / ${h})`,p=this.generateTextureLoad(null,n,d,"0",null,null);let m="vec4";i.pbo.type===An?m="uvec4":i.pbo.type===Mn&&(m="ivec4"),this.addLineFlowCode(`${l} = ${m}(${p})${c}`,e),a.propertyName=l}return l}generateTextureLoad(e,t,s,i,r,n){let o;return null===i&&(i="0"),o=r?n?`texelFetchOffset( ${t}, ivec3( ${s}, ${r} ), ${i}, ${n} )`:`texelFetch( ${t}, ivec3( ${s}, ${r} ), ${i} )`:n?`texelFetchOffset( ${t}, ${s}, ${i}, ${n} )`:`texelFetch( ${t}, ${s}, ${i} )`,null!==e&&e.isDepthTexture&&(o+=".x"),o}generateTexture(e,t,s,i,r){return i&&(s=`vec3( ${s}, ${i} )`),e.isDepthTexture?r?`textureOffset( ${t}, ${s}, ${r} ).x`:`texture( ${t}, ${s} ).x`:r?`textureOffset( ${t}, ${s}, ${r} )`:`texture( ${t}, ${s} )`}generateTextureLevel(e,t,s,i,r){return r?`textureLodOffset( ${t}, ${s}, ${i}, ${r} )`:`textureLod( ${t}, ${s}, ${i} )`}generateTextureBias(e,t,s,i,r){return r?`textureOffset( ${t}, ${s}, ${r}, ${i} )`:`texture( ${t}, ${s}, ${i} )`}generateTextureGrad(e,t,s,i,r){return r?`textureGradOffset( ${t}, ${s}, ${i[0]}, ${i[1]}, ${r} )`:`textureGrad( ${t}, ${s}, ${i[0]}, ${i[1]} )`}generateTextureCompare(e,t,s,i,r,n,o=this.shaderStage){if("fragment"===o)return e.isCubeTexture?`texture( ${t}, vec4( ${s}, ${i} ) )`:r?n?`textureOffset( ${t}, vec4( ${s}, ${r}, ${i} ), ${n} )`:`texture( ${t}, vec4( ${s}, ${r}, ${i} ) )`:n?`textureOffset( ${t}, vec3( ${s}, ${i} ), ${n} )`:`texture( ${t}, vec3( ${s}, ${i} ) )`;Zo(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${o} shader.`)}getVars(e){const t=[],s=this.vars[e];if(void 0!==s)for(const e of s)t.push(`${this.getVar(e.type,e.name,e.count)};`);return t.join("\n\t")}getUniforms(e){const t=this.uniforms[e],s=[],i={};for(const r of t){let t=null,n=!1;if("texture"===r.type||"texture3D"===r.type){const e=r.node.value;let s="";!0!==e.isDataTexture&&!0!==e.isData3DTexture||(e.type===An?s="u":e.type===Mn&&(s="i")),t="texture3D"===r.type&&!1===e.isArrayTexture?`${s}sampler3D ${r.name};`:e.compareFunction?!0===e.isArrayTexture?`sampler2DArrayShadow ${r.name};`:`sampler2DShadow ${r.name};`:!0===e.isArrayTexture||!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?`${s}sampler2DArray ${r.name};`:`${s}sampler2D ${r.name};`}else if("cubeTexture"===r.type)t=`samplerCube ${r.name};`;else if("cubeDepthTexture"===r.type)t=`samplerCubeShadow ${r.name};`;else if("buffer"===r.type){const e=r.node,s=this.getType(e.bufferType),i=e.bufferCount,n=i>0?i:"";t=`${e.name} {\n\t${s} ${r.name}[${n}];\n};\n`}else{t=`${this.getVectorType(r.type)} ${this.getPropertyName(r,e)};`,n=!0}const o=r.node.precision;if(null!==o&&(t=qP[o]+" "+t),n){t="\t"+t;const e=r.groupNode.name;(i[e]||(i[e]=[])).push(t)}else t="uniform "+t,s.push(t)}let r="";for(const t in i){const s=i[t];r+=this._getGLSLUniformStruct(e+"_"+t,s.join("\n"))+"\n"}return r+=s.join("\n"),r}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==Mn){let s=e;e.isInterleavedBufferAttribute&&(s=e.data);const i=s.array;!1==(i instanceof Uint32Array||i instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let s=0;for(const i of e)t+=`layout( location = ${s++} ) in ${i.type} ${i.name};\n`}return t}getStructMembers(e){const t=[];for(const s of e.members)t.push(`\t${s.type} ${s.name};`);return t.join("\n")}getStructs(e){const t=[],s=this.structs[e],i=[];for(const e of s)if(e.output)for(const t of e.members)i.push(`layout( location = ${t.index} ) out ${t.type} ${t.name};`);else{let s="struct "+e.name+" {\n";s+=this.getStructMembers(e),s+="\n};\n",t.push(s)}return 0===i.length&&i.push("layout( location = 0 ) out vec4 fragColor;"),"\n"+i.join("\n")+"\n\n"+t.join("\n")}getVaryings(e){let t="";const s=this.varyings;if("vertex"===e||"compute"===e)for(const i of s){"compute"===e&&(i.needsInterpolation=!0);const s=this.getType(i.type);if(i.needsInterpolation)if(i.interpolationType){t+=`${YP[i.interpolationType]||i.interpolationType} ${ZP[i.interpolationSampling]||""} out ${s} ${i.name};\n`}else{t+=`${s.includes("int")||s.includes("uv")||s.includes("iv")?"flat ":""}out ${s} ${i.name};\n`}else t+=`${s} ${i.name};\n`}else if("fragment"===e)for(const e of s)if(e.needsInterpolation){const s=this.getType(e.type);if(e.interpolationType){t+=`${YP[e.interpolationType]||e.interpolationType} ${ZP[e.interpolationSampling]||""} in ${s} ${e.name};\n`}else{t+=`${s.includes("int")||s.includes("uv")||s.includes("iv")?"flat ":""}in ${s} ${e.name};\n`}}for(const s of this.builtins[e])t+=`${s};\n`;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce((e,t)=>e*t,1)}u`}getSubgroupSize(){Zo("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){Zo("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){Zo("GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node")}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":null}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,s=this.shaderStage){const i=this.extensions[s]||(this.extensions[s]=new Map);!1===i.has(e)&&i.set(e,{name:e,behavior:t})}getExtensions(e){const t=[];if("vertex"===e){const t=this.renderer.backend.extensions;this.object.isBatchedMesh&&t.has("WEBGL_multi_draw")&&this.enableExtension("GL_ANGLE_multi_draw","require",e)}const s=this.extensions[e];if(void 0!==s)for(const{name:e,behavior:i}of s.values())t.push(`#extension ${e} : ${i}`);return t.join("\n")}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=XP[e];if(void 0===t){let s;switch(t=!1,e){case"float32Filterable":s="OES_texture_float_linear";break;case"clipDistance":s="WEBGL_clip_cull_distance"}if(void 0!==s){const e=this.renderer.backend.extensions;e.has(s)&&(e.get(s),t=!0)}XP[e]=t}return t}isFlipY(){return!0}enableHardwareClipping(e){this.enableExtension("GL_ANGLE_clip_cull_distance","require"),this.builtins.vertex.push(`out float gl_ClipDistance[ ${e} ]`)}enableMultiview(){this.enableExtension("GL_OVR_multiview2","require","fragment"),this.enableExtension("GL_OVR_multiview2","require","vertex"),this.builtins.vertex.push("layout(num_views = 2) in")}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let s=0;s<e.length;s++){const i=e[s],r=this.getPropertyName(i.attributeNode);r&&(t+=`${i.varyingName} = ${r};\n\t`)}return t}_getGLSLUniformStruct(e,t){return`\nlayout( std140 ) uniform ${e} {\n${t}\n};`}_getGLSLVertexCode(e){return`#version 300 es\n\n${this.getSignature()}\n\n// extensions\n${e.extensions}\n\n// precision\n${QP}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// attributes\n${e.attributes}\n\n// codes\n${e.codes}\n\nvoid main() {\n\n\t// vars\n\t${e.vars}\n\n\t// transforms\n\t${e.transforms}\n\n\t// flow\n\t${e.flow}\n\n\tgl_PointSize = 1.0;\n\n}\n`}_getGLSLFragmentCode(e){return`#version 300 es\n\n${this.getSignature()}\n\n// extensions\n${e.extensions}\n\n// precision\n${QP}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// codes\n${e.codes}\n\nvoid main() {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){let s="// code\n\n";s+=this.flowCode[t];const i=this.flowNodes[t],r=i[i.length-1];for(const e of i){const i=this.getFlowData(e),n=e.name;n&&(s.length>0&&(s+="\n"),s+=`\t// flow -> ${n}\n\t`),s+=`${i.code}\n\t`,e===r&&"compute"!==t&&(s+="// result\n\t","vertex"===t?(s+="gl_Position = ",s+=`${i.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(s+="fragColor = ",s+=`${i.result};`)))}const n=e[t];n.extensions=this.getExtensions(t),n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.vars=this.getVars(t),n.structs=this.getStructs(t),n.codes=this.getCodes(t),n.transforms=this.getTransforms(t),n.flow=s}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,s,i=null){const r=super.getUniformFromNode(e,t,s,i),n=this.getDataFromNode(e,s,this.globalCache);let o=n.uniformGPU;if(void 0===o){const i=e.groupNode,a=i.name,l=this.getBindGroupArray(a,s);if("texture"===t)o=new GP(r.name,r.node,i),l.push(o);else if("cubeTexture"===t||"cubeDepthTexture"===t)o=new jP(r.name,r.node,i),l.push(o);else if("texture3D"===t)o=new $P(r.name,r.node,i),l.push(o);else if("buffer"===t){r.name=`buffer${e.id}`;const t=this.getSharedDataFromNode(e);let s=t.buffer;void 0===s&&(e.name=`NodeBuffer_${e.id}`,s=new LP(e,i),s.name=e.name,t.buffer=s),l.push(s),o=s}else{const e=this.uniformGroups[s]||(this.uniformGroups[s]={});let n=e[a];void 0===n&&(n=new VP(s+"_"+a,i),e[a]=n,l.push(n)),o=this.getNodeUniform(r,t),n.addUniform(o)}n.uniformGPU=o}return r}}let JP=null,eB=null;class tB{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[jo]:null,[Go]:null},this.trackTimestamp=!0===e.trackTimestamp}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(e){const t=this.get(e),s=this.renderer.info.frame;let i;i=!0===e.isComputeNode?"c:"+this.renderer.info.compute.frameCalls:"r:"+this.renderer.info.render.frameCalls,t.timestampUID=i+":"+e.id+":f"+s}getTimestampUID(e){return this.get(e).timestampUID}getTimestampFrames(e){const t=this.timestampQueryPool[e];return t?t.getTimestampFrames():[]}_getQueryPool(e){const t=e.startsWith("c:")?Go:jo;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}hasTimestamp(e){return this._getQueryPool(e).hasTimestamp(e)}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void Qo("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return;const s=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=s,s}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return JP=JP||new ua,this.renderer.getDrawingBufferSize(JP)}setScissorTest(){}getClearColor(){const e=this.renderer;return eB=eB||new WS,e.getClearColor(eB),eB.getRGB(eB),eB}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:function(){const e=Ho("canvas");return e.style.display="block",e}(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${Xr} webgpu`),this.domElement=e),e}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}deleteBindGroupData(){}dispose(){}}let sB,iB,rB=0;class nB{constructor(e,t){this.buffers=[e.bufferGPU,t],this.type=e.type,this.bufferType=e.bufferType,this.pbo=e.pbo,this.byteLength=e.byteLength,this.bytesPerElement=e.BYTES_PER_ELEMENT,this.version=e.version,this.isInteger=e.isInteger,this.activeBufferIndex=0,this.baseId=e.id}get id(){return`${this.baseId}|${this.activeBufferIndex}`}get bufferGPU(){return this.buffers[this.activeBufferIndex]}get transformBuffer(){return this.buffers[1^this.activeBufferIndex]}switchBuffers(){this.activeBufferIndex^=1}}class oB{constructor(e){this.backend=e}createAttribute(e,t){const s=this.backend,{gl:i}=s,r=e.array,n=e.usage||i.STATIC_DRAW,o=e.isInterleavedBufferAttribute?e.data:e,a=s.get(o);let l,h=a.bufferGPU;if(void 0===h&&(h=this._createBuffer(i,t,r,n),a.bufferGPU=h,a.bufferType=t,a.version=o.version),r instanceof Float32Array)l=i.FLOAT;else if("undefined"!=typeof Float16Array&&r instanceof Float16Array)l=i.HALF_FLOAT;else if(r instanceof Uint16Array)l=e.isFloat16BufferAttribute?i.HALF_FLOAT:i.UNSIGNED_SHORT;else if(r instanceof Int16Array)l=i.SHORT;else if(r instanceof Uint32Array)l=i.UNSIGNED_INT;else if(r instanceof Int32Array)l=i.INT;else if(r instanceof Int8Array)l=i.BYTE;else if(r instanceof Uint8Array)l=i.UNSIGNED_BYTE;else{if(!(r instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+r);l=i.UNSIGNED_BYTE}let u={bufferGPU:h,bufferType:t,type:l,byteLength:r.byteLength,bytesPerElement:r.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:l===i.INT||l===i.UNSIGNED_INT||e.gpuType===Mn,id:rB++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(i,t,r,n);u=new nB(u,e)}s.set(e,u)}updateAttribute(e){const t=this.backend,{gl:s}=t,i=e.array,r=e.isInterleavedBufferAttribute?e.data:e,n=t.get(r),o=n.bufferType,a=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(s.bindBuffer(o,n.bufferGPU),0===a.length)s.bufferSubData(o,0,i);else{for(let e=0,t=a.length;e<t;e++){const t=a[e];s.bufferSubData(o,t.start*i.BYTES_PER_ELEMENT,i,t.start,t.count)}r.clearUpdateRanges()}s.bindBuffer(o,null),n.version=r.version}destroyAttribute(e){const t=this.backend,{gl:s}=t;e.isInterleavedBufferAttribute&&t.delete(e.data);const i=t.get(e);s.deleteBuffer(i.bufferGPU),t.delete(e)}async getArrayBufferAsync(e){const t=this.backend,{gl:s}=t,i=e.isInterleavedBufferAttribute?e.data:e,{bufferGPU:r}=t.get(i),n=e.array,o=n.byteLength;s.bindBuffer(s.COPY_READ_BUFFER,r);const a=s.createBuffer();s.bindBuffer(s.COPY_WRITE_BUFFER,a),s.bufferData(s.COPY_WRITE_BUFFER,o,s.STREAM_READ),s.copyBufferSubData(s.COPY_READ_BUFFER,s.COPY_WRITE_BUFFER,0,0,o),await t.utils._clientWaitAsync();const l=new e.array.constructor(n.length);return s.bindBuffer(s.COPY_WRITE_BUFFER,a),s.getBufferSubData(s.COPY_WRITE_BUFFER,0,l),s.deleteBuffer(a),s.bindBuffer(s.COPY_READ_BUFFER,null),s.bindBuffer(s.COPY_WRITE_BUFFER,null),l.buffer}_createBuffer(e,t,s,i){const r=e.createBuffer();return e.bindBuffer(t,r),e.bufferData(t,s,i),e.bindBuffer(t,null),r}}class aB{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){const e=this.gl;sB={[Yr]:e.FUNC_ADD,[Zr]:e.FUNC_SUBTRACT,[Qr]:e.FUNC_REVERSE_SUBTRACT},iB={[Kr]:e.ZERO,[Jr]:e.ONE,[en]:e.SRC_COLOR,[sn]:e.SRC_ALPHA,[hn]:e.SRC_ALPHA_SATURATE,[an]:e.DST_COLOR,[nn]:e.DST_ALPHA,[tn]:e.ONE_MINUS_SRC_COLOR,[rn]:e.ONE_MINUS_SRC_ALPHA,[ln]:e.ONE_MINUS_DST_COLOR,[on]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),s=e.getParameter(e.VIEWPORT);this.currentScissor=(new Pa).fromArray(t),this.currentViewport=(new Pa).fromArray(s),this._tempVec4=new Pa}enable(e){const{enabled:t}=this;!0!==t[e]&&(this.gl.enable(e),t[e]=!0)}disable(e){const{enabled:t}=this;!1!==t[e]&&(this.gl.disable(e),t[e]=!1)}setFlipSided(e){if(this.currentFlipSided!==e){const{gl:t}=this;e?t.frontFace(t.CW):t.frontFace(t.CCW),this.currentFlipSided=e}}setCullFace(e){const{gl:t}=this;0!==e?(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(1===e?t.cullFace(t.BACK):2===e?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):this.disable(t.CULL_FACE),this.currentCullFace=e}setLineWidth(e){const{currentLineWidth:t,gl:s}=this;e!==t&&(s.lineWidth(e),this.currentLineWidth=e)}setMRTBlending(e){const t=this.gl,s=this.backend.drawBuffersIndexedExt;if(s)for(let i=1;i<e.length;i++)s.blendFuncSeparateiOES(i,t.ONE,t.ZERO,t.ONE,t.ZERO)}setBlending(e,t,s,i,r,n,o,a){const{gl:l}=this;if(0!==e){if(!1===this.currentBlendingEnabled&&(this.enable(l.BLEND),this.currentBlendingEnabled=!0),5===e)r=r||t,n=n||s,o=o||i,t===this.currentBlendEquation&&r===this.currentBlendEquationAlpha||(l.blendEquationSeparate(sB[t],sB[r]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=r),s===this.currentBlendSrc&&i===this.currentBlendDst&&n===this.currentBlendSrcAlpha&&o===this.currentBlendDstAlpha||(l.blendFuncSeparate(iB[s],iB[i],iB[n],iB[o]),this.currentBlendSrc=s,this.currentBlendDst=i,this.currentBlendSrcAlpha=n,this.currentBlendDstAlpha=o),this.currentBlending=e,this.currentPremultipledAlpha=!1;else if(e!==this.currentBlending||a!==this.currentPremultipledAlpha){if(this.currentBlendEquation===Yr&&this.currentBlendEquationAlpha===Yr||(l.blendEquation(l.FUNC_ADD),this.currentBlendEquation=Yr,this.currentBlendEquationAlpha=Yr),a)switch(e){case 1:l.blendFuncSeparate(l.ONE,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case 2:l.blendFunc(l.ONE,l.ONE);break;case 3:l.blendFuncSeparate(l.ZERO,l.ONE_MINUS_SRC_COLOR,l.ZERO,l.ONE);break;case 4:l.blendFuncSeparate(l.DST_COLOR,l.ONE_MINUS_SRC_ALPHA,l.ZERO,l.ONE);break;default:Zo("WebGLState: Invalid blending: ",e)}else switch(e){case 1:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case 2:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE,l.ONE,l.ONE);break;case 3:Zo("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:Zo("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:Zo("WebGLState: Invalid blending: ",e)}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=e,this.currentPremultipledAlpha=a}}else!0===this.currentBlendingEnabled&&(this.disable(l.BLEND),this.currentBlendingEnabled=!1)}setColorMask(e){this.currentColorMask!==e&&(this.gl.colorMask(e,e,e,e),this.currentColorMask=e)}setDepthTest(e){const{gl:t}=this;e?this.enable(t.DEPTH_TEST):this.disable(t.DEPTH_TEST)}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(this.currentDepthFunc!==e){const{gl:t}=this;switch(e){case 0:t.depthFunc(t.NEVER);break;case 1:t.depthFunc(t.ALWAYS);break;case 2:t.depthFunc(t.LESS);break;case 3:default:t.depthFunc(t.LEQUAL);break;case 4:t.depthFunc(t.EQUAL);break;case 5:t.depthFunc(t.GEQUAL);break;case 6:t.depthFunc(t.GREATER);break;case 7:t.depthFunc(t.NOTEQUAL)}this.currentDepthFunc=e}}scissor(e,t,s,i){const r=this._tempVec4.set(e,t,s,i);if(!1===this.currentScissor.equals(r)){const{gl:e}=this;e.scissor(r.x,r.y,r.z,r.w),this.currentScissor.copy(r)}}viewport(e,t,s,i){const r=this._tempVec4.set(e,t,s,i);if(!1===this.currentViewport.equals(r)){const{gl:e}=this;e.viewport(r.x,r.y,r.z,r.w),this.currentViewport.copy(r)}}setScissorTest(e){const t=this.gl;e?this.enable(t.SCISSOR_TEST):this.disable(t.SCISSOR_TEST)}setStencilTest(e){const{gl:t}=this;e?this.enable(t.STENCIL_TEST):this.disable(t.STENCIL_TEST)}setStencilMask(e){this.currentStencilMask!==e&&(this.gl.stencilMask(e),this.currentStencilMask=e)}setStencilFunc(e,t,s){this.currentStencilFunc===e&&this.currentStencilRef===t&&this.currentStencilFuncMask===s||(this.gl.stencilFunc(e,t,s),this.currentStencilFunc=e,this.currentStencilRef=t,this.currentStencilFuncMask=s)}setStencilOp(e,t,s){this.currentStencilFail===e&&this.currentStencilZFail===t&&this.currentStencilZPass===s||(this.gl.stencilOp(e,t,s),this.currentStencilFail=e,this.currentStencilZFail=t,this.currentStencilZPass=s)}setMaterial(e,t,s){const{gl:i}=this;2===e.side?this.disable(i.CULL_FACE):this.enable(i.CULL_FACE);let r=1===e.side;t&&(r=!r),this.setFlipSided(r),1===e.blending&&!1===e.transparent?this.setBlending(0):this.setBlending(e.blending,e.blendEquation,e.blendSrc,e.blendDst,e.blendEquationAlpha,e.blendSrcAlpha,e.blendDstAlpha,e.premultipliedAlpha),this.setDepthFunc(e.depthFunc),this.setDepthTest(e.depthTest),this.setDepthMask(e.depthWrite),this.setColorMask(e.colorWrite);const n=e.stencilWrite;if(this.setStencilTest(n),n&&(this.setStencilMask(e.stencilWriteMask),this.setStencilFunc(e.stencilFunc,e.stencilRef,e.stencilFuncMask),this.setStencilOp(e.stencilFail,e.stencilZFail,e.stencilZPass)),this.setPolygonOffset(e.polygonOffset,e.polygonOffsetFactor,e.polygonOffsetUnits),!0===e.alphaToCoverage&&this.backend.renderer.currentSamples>0?this.enable(i.SAMPLE_ALPHA_TO_COVERAGE):this.disable(i.SAMPLE_ALPHA_TO_COVERAGE),s>0&&this.currentClippingPlanes!==s){const e=12288;for(let t=0;t<8;t++)t<s?this.enable(e+t):this.disable(e+t)}}setPolygonOffset(e,t,s){const{gl:i}=this;e?(this.enable(i.POLYGON_OFFSET_FILL),this.currentPolygonOffsetFactor===t&&this.currentPolygonOffsetUnits===s||(i.polygonOffset(t,s),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=s)):this.disable(i.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e&&(this.gl.useProgram(e),this.currentProgram=e,!0)}setVertexState(e,t=null){const s=this.gl;return(this.currentVAO!==e||this.currentIndex!==t)&&(s.bindVertexArray(e),null!==t&&s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,t),this.currentVAO=e,this.currentIndex=t,!0)}resetVertexState(){const e=this.gl;e.bindVertexArray(null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),this.currentVAO=null,this.currentIndex=null}bindFramebuffer(e,t){const{gl:s,currentBoundFramebuffers:i}=this;return i[e]!==t&&(s.bindFramebuffer(e,t),i[e]=t,e===s.DRAW_FRAMEBUFFER&&(i[s.FRAMEBUFFER]=t),e===s.FRAMEBUFFER&&(i[s.DRAW_FRAMEBUFFER]=t),!0)}drawBuffers(e,t){const{gl:s}=this;let i=[],r=!1;if(null!==e.textures){i=this.currentDrawbuffers.get(t),void 0===i&&(i=[],this.currentDrawbuffers.set(t,i));const n=e.textures;if(i.length!==n.length||i[0]!==s.COLOR_ATTACHMENT0){for(let e=0,t=n.length;e<t;e++)i[e]=s.COLOR_ATTACHMENT0+e;i.length=n.length,r=!0}}else i[0]!==s.BACK&&(i[0]=s.BACK,r=!0);r&&s.drawBuffers(i)}activeTexture(e){const{gl:t,currentTextureSlot:s,maxTextures:i}=this;void 0===e&&(e=t.TEXTURE0+i-1),s!==e&&(t.activeTexture(e),this.currentTextureSlot=e)}bindTexture(e,t,s){const{gl:i,currentTextureSlot:r,currentBoundTextures:n,maxTextures:o}=this;void 0===s&&(s=null===r?i.TEXTURE0+o-1:r);let a=n[s];void 0===a&&(a={type:void 0,texture:void 0},n[s]=a),a.type===e&&a.texture===t||(r!==s&&(i.activeTexture(s),this.currentTextureSlot=s),i.bindTexture(e,t),a.type=e,a.texture=t)}bindBufferBase(e,t,s){const{gl:i}=this,r=`${e}-${t}`;return this.currentBoundBufferBases[r]!==s&&(i.bindBufferBase(e,t,s),this.currentBoundBufferBases[r]=s,!0)}unbindTexture(){const{gl:e,currentTextureSlot:t,currentBoundTextures:s}=this,i=s[t];void 0!==i&&void 0!==i.type&&(e.bindTexture(i.type,null),i.type=void 0,i.texture=void 0)}}class lB{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=""){const{gl:s,extensions:i}=this;let r;const n=_a.getTransfer(t);if(e===wn)return s.UNSIGNED_BYTE;if(e===Cn)return s.UNSIGNED_SHORT_4_4_4_4;if(e===Rn)return s.UNSIGNED_SHORT_5_5_5_1;if(e===Bn)return s.UNSIGNED_INT_5_9_9_9_REV;if(e===In)return s.UNSIGNED_INT_10F_11F_11F_REV;if(e===vn)return s.BYTE;if(e===Tn)return s.SHORT;if(e===Sn)return s.UNSIGNED_SHORT;if(e===Mn)return s.INT;if(e===An)return s.UNSIGNED_INT;if(e===Nn)return s.FLOAT;if(e===En)return s.HALF_FLOAT;if(1021===e)return s.ALPHA;if(e===Dn)return s.RGB;if(e===Ln)return s.RGBA;if(e===Fn)return s.DEPTH_COMPONENT;if(e===On)return s.DEPTH_STENCIL;if(e===Vn)return s.RED;if(e===zn)return s.RED_INTEGER;if(e===kn)return s.RG;if(e===Un)return s.RG_INTEGER;if(e===Gn)return s.RGBA_INTEGER;if(e===jn||e===$n||e===Wn||e===Hn)if(n===Eo){if(r=i.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(e===jn)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===$n)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===Wn)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===Hn)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=i.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(e===jn)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===$n)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===Wn)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===Hn)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e===qn||e===Xn||e===Yn||e===Zn){if(r=i.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(e===qn)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===Xn)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===Yn)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===Zn)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e===Qn||e===Kn||e===Jn||e===eo||e===to||e===so||e===io){if(r=i.get("WEBGL_compressed_texture_etc"),null===r)return null;if(e===Qn||e===Kn)return n===Eo?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(e===Jn)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(e===eo)return r.COMPRESSED_R11_EAC;if(e===to)return r.COMPRESSED_SIGNED_R11_EAC;if(e===so)return r.COMPRESSED_RG11_EAC;if(e===io)return r.COMPRESSED_SIGNED_RG11_EAC}if(e===ro||e===no||e===oo||e===ao||e===lo||e===ho||e===uo||e===co||e===po||e===mo||e===fo||e===go||e===yo||e===xo){if(r=i.get("WEBGL_compressed_texture_astc"),null===r)return null;if(e===ro)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===no)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===oo)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===ao)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===lo)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===ho)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===uo)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===co)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===po)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===mo)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===fo)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===go)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===yo)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===xo)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(e===bo){if(r=i.get("EXT_texture_compression_bptc"),null===r)return null;if(e===bo)return n===Eo?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT}if(e===_o||e===wo||e===vo||e===To){if(r=i.get("EXT_texture_compression_rgtc"),null===r)return null;if(e===_o)return r.COMPRESSED_RED_RGTC1_EXT;if(e===wo)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===vo)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===To)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return e===Pn?s.UNSIGNED_INT_24_8:void 0!==s[e]?s[e]:null}_clientWaitAsync(){const{gl:e}=this,t=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),new Promise((s,i)=>{!function r(){const n=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(n===e.WAIT_FAILED)return e.deleteSync(t),void i();n!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),s()):requestAnimationFrame(r)}()})}}let hB,uB,cB,dB=!1;class pB{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,!1===dB&&(this._init(),dB=!0)}_init(){const e=this.gl;hB={[dn]:e.REPEAT,[pn]:e.CLAMP_TO_EDGE,[mn]:e.MIRRORED_REPEAT},uB={[fn]:e.NEAREST,[gn]:e.NEAREST_MIPMAP_NEAREST,[yn]:e.NEAREST_MIPMAP_LINEAR,[xn]:e.LINEAR,[bn]:e.LINEAR_MIPMAP_NEAREST,[_n]:e.LINEAR_MIPMAP_LINEAR},cB={[Ro]:e.NEVER,[Oo]:e.ALWAYS,[Po]:e.LESS,[Io]:e.LEQUAL,[Bo]:e.EQUAL,[Fo]:e.GEQUAL,[Do]:e.GREATER,[Lo]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let s;return s=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!0===e.isArrayTexture||!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:!0===e.isData3DTexture?t.TEXTURE_3D:t.TEXTURE_2D,s}getInternalFormat(e,t,s,i,r=!1){const{gl:n,extensions:o}=this;if(null!==e){if(void 0!==n[e])return n[e];Yo("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let a=t;if(t===n.RED&&(s===n.FLOAT&&(a=n.R32F),s===n.HALF_FLOAT&&(a=n.R16F),s===n.UNSIGNED_BYTE&&(a=n.R8),s===n.UNSIGNED_SHORT&&(a=n.R16),s===n.UNSIGNED_INT&&(a=n.R32UI),s===n.BYTE&&(a=n.R8I),s===n.SHORT&&(a=n.R16I),s===n.INT&&(a=n.R32I)),t===n.RED_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.R8UI),s===n.UNSIGNED_SHORT&&(a=n.R16UI),s===n.UNSIGNED_INT&&(a=n.R32UI),s===n.BYTE&&(a=n.R8I),s===n.SHORT&&(a=n.R16I),s===n.INT&&(a=n.R32I)),t===n.RG&&(s===n.FLOAT&&(a=n.RG32F),s===n.HALF_FLOAT&&(a=n.RG16F),s===n.UNSIGNED_BYTE&&(a=n.RG8),s===n.UNSIGNED_SHORT&&(a=n.RG16),s===n.UNSIGNED_INT&&(a=n.RG32UI),s===n.BYTE&&(a=n.RG8I),s===n.SHORT&&(a=n.RG16I),s===n.INT&&(a=n.RG32I)),t===n.RG_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.RG8UI),s===n.UNSIGNED_SHORT&&(a=n.RG16UI),s===n.UNSIGNED_INT&&(a=n.RG32UI),s===n.BYTE&&(a=n.RG8I),s===n.SHORT&&(a=n.RG16I),s===n.INT&&(a=n.RG32I)),t===n.RGB){const e=r?No:_a.getTransfer(i);s===n.FLOAT&&(a=n.RGB32F),s===n.HALF_FLOAT&&(a=n.RGB16F),s===n.UNSIGNED_BYTE&&(a=n.RGB8),s===n.UNSIGNED_SHORT&&(a=n.RGB16),s===n.UNSIGNED_INT&&(a=n.RGB32UI),s===n.BYTE&&(a=n.RGB8I),s===n.SHORT&&(a=n.RGB16I),s===n.INT&&(a=n.RGB32I),s===n.UNSIGNED_BYTE&&(a=e===Eo?n.SRGB8:n.RGB8),s===n.UNSIGNED_SHORT_5_6_5&&(a=n.RGB565),s===n.UNSIGNED_SHORT_5_5_5_1&&(a=n.RGB5_A1),s===n.UNSIGNED_SHORT_4_4_4_4&&(a=n.RGB4),s===n.UNSIGNED_INT_5_9_9_9_REV&&(a=n.RGB9_E5),s===n.UNSIGNED_INT_10F_11F_11F_REV&&(a=n.R11F_G11F_B10F)}if(t===n.RGB_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.RGB8UI),s===n.UNSIGNED_SHORT&&(a=n.RGB16UI),s===n.UNSIGNED_INT&&(a=n.RGB32UI),s===n.BYTE&&(a=n.RGB8I),s===n.SHORT&&(a=n.RGB16I),s===n.INT&&(a=n.RGB32I)),t===n.RGBA){const e=r?No:_a.getTransfer(i);s===n.FLOAT&&(a=n.RGBA32F),s===n.HALF_FLOAT&&(a=n.RGBA16F),s===n.UNSIGNED_BYTE&&(a=n.RGBA8),s===n.UNSIGNED_SHORT&&(a=n.RGBA16),s===n.UNSIGNED_INT&&(a=n.RGBA32UI),s===n.BYTE&&(a=n.RGBA8I),s===n.SHORT&&(a=n.RGBA16I),s===n.INT&&(a=n.RGBA32I),s===n.UNSIGNED_BYTE&&(a=e===Eo?n.SRGB8_ALPHA8:n.RGBA8),s===n.UNSIGNED_SHORT_4_4_4_4&&(a=n.RGBA4),s===n.UNSIGNED_SHORT_5_5_5_1&&(a=n.RGB5_A1)}return t===n.RGBA_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.RGBA8UI),s===n.UNSIGNED_SHORT&&(a=n.RGBA16UI),s===n.UNSIGNED_INT&&(a=n.RGBA32UI),s===n.BYTE&&(a=n.RGBA8I),s===n.SHORT&&(a=n.RGBA16I),s===n.INT&&(a=n.RGBA32I)),t===n.DEPTH_COMPONENT&&(s===n.UNSIGNED_SHORT&&(a=n.DEPTH_COMPONENT16),s===n.UNSIGNED_INT&&(a=n.DEPTH_COMPONENT24),s===n.FLOAT&&(a=n.DEPTH_COMPONENT32F)),t===n.DEPTH_STENCIL&&s===n.UNSIGNED_INT_24_8&&(a=n.DEPTH24_STENCIL8),a!==n.R16F&&a!==n.R32F&&a!==n.RG16F&&a!==n.RG32F&&a!==n.RGBA16F&&a!==n.RGBA32F||o.get("EXT_color_buffer_float"),a}setTextureParameters(e,t){const{gl:s,extensions:i,backend:r}=this,n=_a.getPrimaries(_a.workingColorSpace),o=t.colorSpace===So?null:_a.getPrimaries(t.colorSpace),a=t.colorSpace===So||n===o?s.NONE:s.BROWSER_DEFAULT_WEBGL;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,t.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,t.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,a),s.texParameteri(e,s.TEXTURE_WRAP_S,hB[t.wrapS]),s.texParameteri(e,s.TEXTURE_WRAP_T,hB[t.wrapT]),e!==s.TEXTURE_3D&&e!==s.TEXTURE_2D_ARRAY||t.isArrayTexture||s.texParameteri(e,s.TEXTURE_WRAP_R,hB[t.wrapR]),s.texParameteri(e,s.TEXTURE_MAG_FILTER,uB[t.magFilter]);const l=void 0!==t.mipmaps&&t.mipmaps.length>0,h=t.minFilter===xn&&l?_n:t.minFilter;if(s.texParameteri(e,s.TEXTURE_MIN_FILTER,uB[h]),t.compareFunction&&(s.texParameteri(e,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(e,s.TEXTURE_COMPARE_FUNC,cB[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===fn)return;if(t.minFilter!==yn&&t.minFilter!==_n)return;if(t.type===Nn&&!1===i.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const n=i.get("EXT_texture_filter_anisotropic");s.texParameterf(e,n.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,r.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:s,defaultTextures:i}=this,r=this.getGLTextureType(e);let n=i[r];void 0===n&&(n=t.createTexture(),s.state.bindTexture(r,n),t.texParameteri(r,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(r,t.TEXTURE_MAG_FILTER,t.NEAREST),i[r]=n),s.set(e,{textureGPU:n,glTextureType:r})}createTexture(e,t){const{gl:s,backend:i}=this,{levels:r,width:n,height:o,depth:a}=t,l=i.utils.convert(e.format,e.colorSpace),h=i.utils.convert(e.type),u=this.getInternalFormat(e.internalFormat,l,h,e.colorSpace,e.isVideoTexture),c=s.createTexture(),d=this.getGLTextureType(e);i.state.bindTexture(d,c),this.setTextureParameters(d,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?s.texStorage3D(s.TEXTURE_2D_ARRAY,r,u,n,o,a):e.isData3DTexture?s.texStorage3D(s.TEXTURE_3D,r,u,n,o,a):e.isVideoTexture||s.texStorage2D(d,r,u,n,o),i.set(e,{textureGPU:c,glTextureType:d,glFormat:l,glType:h,glInternalFormat:u})}copyBufferToTexture(e,t){const{gl:s,backend:i}=this,{textureGPU:r,glTextureType:n,glFormat:o,glType:a}=i.get(t),{width:l,height:h}=t.source.data;s.bindBuffer(s.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(n,r),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,!1),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),s.texSubImage2D(n,0,0,0,l,h,o,a,0),s.bindBuffer(s.PIXEL_UNPACK_BUFFER,null),i.state.unbindTexture()}updateTexture(e,t){const{gl:s}=this,{width:i,height:r}=t,{textureGPU:n,glTextureType:o,glFormat:a,glType:l,glInternalFormat:h}=this.backend.get(e);if(!e.isRenderTargetTexture&&void 0!==n)if(this.backend.state.bindTexture(o,n),this.setTextureParameters(o,e),e.isCompressedTexture){const i=e.mipmaps,r=t.image;for(let t=0;t<i.length;t++){const n=i[t];e.isCompressedArrayTexture?e.format!==s.RGBA?null!==a?s.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,t,0,0,0,n.width,n.height,r.depth,a,n.data):Yo("WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()"):s.texSubImage3D(s.TEXTURE_2D_ARRAY,t,0,0,0,n.width,n.height,r.depth,a,l,n.data):null!==a?s.compressedTexSubImage2D(s.TEXTURE_2D,t,0,0,n.width,n.height,a,n.data):Yo("WebGLBackend: Unsupported compressed texture format")}}else if(e.isCubeTexture){const n=t.images,o=e.mipmaps;for(let e=0;e<6;e++){const t=mB(n[e]);s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,i,r,a,l,t);for(let t=0;t<o.length;t++){const i=mB(o[t].images[e]);s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+e,t+1,0,0,i.width,i.height,a,l,i)}}}else if(e.isDataArrayTexture||e.isArrayTexture){const i=t.image;if(e.layerUpdates.size>0){const t=ec(i.width,i.height,e.format,e.type);for(const r of e.layerUpdates){const e=i.data.subarray(r*t/i.data.BYTES_PER_ELEMENT,(r+1)*t/i.data.BYTES_PER_ELEMENT);s.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,r,i.width,i.height,1,a,l,e)}e.clearLayerUpdates()}else s.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,0,i.width,i.height,i.depth,a,l,i.data)}else if(e.isData3DTexture){const e=t.image;s.texSubImage3D(s.TEXTURE_3D,0,0,0,0,e.width,e.height,e.depth,a,l,e.data)}else if(e.isVideoTexture)e.update(),s.texImage2D(o,0,h,a,l,t.image);else{const n=e.mipmaps;if(n.length>0)for(let e=0,t=n.length;e<t;e++){const t=n[e],i=mB(t);s.texSubImage2D(o,e,0,0,t.width,t.height,a,l,i)}else{const e=mB(t.image);s.texSubImage2D(o,0,0,0,i,r,a,l,e)}}}generateMipmaps(e){const{gl:t,backend:s}=this,{textureGPU:i,glTextureType:r}=s.get(e);s.state.bindTexture(r,i),t.generateMipmap(r)}deallocateRenderBuffers(e){const{gl:t,backend:s}=this;if(e){const i=s.get(e);if(i.renderBufferStorageSetup=void 0,i.framebuffers){for(const e in i.framebuffers)t.deleteFramebuffer(i.framebuffers[e]);delete i.framebuffers}if(i.depthRenderbuffer&&(t.deleteRenderbuffer(i.depthRenderbuffer),delete i.depthRenderbuffer),i.stencilRenderbuffer&&(t.deleteRenderbuffer(i.stencilRenderbuffer),delete i.stencilRenderbuffer),i.msaaFrameBuffer&&(t.deleteFramebuffer(i.msaaFrameBuffer),delete i.msaaFrameBuffer),i.msaaRenderbuffers){for(let e=0;e<i.msaaRenderbuffers.length;e++)t.deleteRenderbuffer(i.msaaRenderbuffers[e]);delete i.msaaRenderbuffers}}}destroyTexture(e,t=!1){const{gl:s,backend:i}=this,{textureGPU:r,renderTarget:n}=i.get(e);this.deallocateRenderBuffers(n),!1===t&&s.deleteTexture(r),i.delete(e)}copyTextureToTexture(e,t,s=null,i=null,r=0,n=0){const{gl:o,backend:a}=this,{state:l}=this.backend,{textureGPU:h,glTextureType:u,glType:c,glFormat:d}=a.get(t);let p,m,f,g,y,x,b,_,w;l.bindTexture(u,h);const v=e.isCompressedTexture?e.mipmaps[n]:e.image;if(null!==s)p=s.max.x-s.min.x,m=s.max.y-s.min.y,f=s.isBox3?s.max.z-s.min.z:1,g=s.min.x,y=s.min.y,x=s.isBox3?s.min.z:0;else{const t=Math.pow(2,-r);p=Math.floor(v.width*t),m=Math.floor(v.height*t),f=e.isDataArrayTexture||e.isArrayTexture?v.depth:e.isData3DTexture?Math.floor(v.depth*t):1,g=0,y=0,x=0}null!==i?(b=i.x,_=i.y,w=i.z):(b=0,_=0,w=0),o.pixelStorei(o.UNPACK_FLIP_Y_WEBGL,t.flipY),o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),o.pixelStorei(o.UNPACK_ALIGNMENT,t.unpackAlignment);const T=o.getParameter(o.UNPACK_ROW_LENGTH),S=o.getParameter(o.UNPACK_IMAGE_HEIGHT),M=o.getParameter(o.UNPACK_SKIP_PIXELS),A=o.getParameter(o.UNPACK_SKIP_ROWS),N=o.getParameter(o.UNPACK_SKIP_IMAGES);o.pixelStorei(o.UNPACK_ROW_LENGTH,v.width),o.pixelStorei(o.UNPACK_IMAGE_HEIGHT,v.height),o.pixelStorei(o.UNPACK_SKIP_PIXELS,g),o.pixelStorei(o.UNPACK_SKIP_ROWS,y),o.pixelStorei(o.UNPACK_SKIP_IMAGES,x);const E=e.isDataArrayTexture||e.isData3DTexture||t.isArrayTexture,C=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isDepthTexture){const s=a.get(e),i=a.get(t),u=a.get(s.renderTarget),c=a.get(i.renderTarget),d=u.framebuffers[s.cacheKey],v=c.framebuffers[i.cacheKey];l.bindFramebuffer(o.READ_FRAMEBUFFER,d),l.bindFramebuffer(o.DRAW_FRAMEBUFFER,v);for(let e=0;e<f;e++)E&&(o.framebufferTextureLayer(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,s.textureGPU,r,x+e),o.framebufferTextureLayer(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0,h,n,w+e)),o.blitFramebuffer(g,y,p,m,b,_,p,m,o.DEPTH_BUFFER_BIT,o.NEAREST);l.bindFramebuffer(o.READ_FRAMEBUFFER,null),l.bindFramebuffer(o.DRAW_FRAMEBUFFER,null)}else if(0!==r||e.isRenderTargetTexture||a.has(e)){const t=a.get(e);null===this._srcFramebuffer&&(this._srcFramebuffer=o.createFramebuffer()),null===this._dstFramebuffer&&(this._dstFramebuffer=o.createFramebuffer()),l.bindFramebuffer(o.READ_FRAMEBUFFER,this._srcFramebuffer),l.bindFramebuffer(o.DRAW_FRAMEBUFFER,this._dstFramebuffer);for(let e=0;e<f;e++)E?o.framebufferTextureLayer(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,t.textureGPU,r,x+e):o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,t.textureGPU,r),C?o.framebufferTextureLayer(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0,h,n,w+e):o.framebufferTexture2D(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,h,n),0!==r?o.blitFramebuffer(g,y,p,m,b,_,p,m,o.COLOR_BUFFER_BIT,o.NEAREST):C?o.copyTexSubImage3D(u,n,b,_,w+e,g,y,p,m):o.copyTexSubImage2D(u,n,b,_,g,y,p,m);l.bindFramebuffer(o.READ_FRAMEBUFFER,null),l.bindFramebuffer(o.DRAW_FRAMEBUFFER,null)}else C?e.isDataTexture||e.isData3DTexture?o.texSubImage3D(u,n,b,_,w,p,m,f,d,c,v.data):t.isCompressedArrayTexture?o.compressedTexSubImage3D(u,n,b,_,w,p,m,f,d,v.data):o.texSubImage3D(u,n,b,_,w,p,m,f,d,c,v):e.isDataTexture?o.texSubImage2D(o.TEXTURE_2D,n,b,_,p,m,d,c,v.data):e.isCompressedTexture?o.compressedTexSubImage2D(o.TEXTURE_2D,n,b,_,v.width,v.height,d,v.data):o.texSubImage2D(o.TEXTURE_2D,n,b,_,p,m,d,c,v);o.pixelStorei(o.UNPACK_ROW_LENGTH,T),o.pixelStorei(o.UNPACK_IMAGE_HEIGHT,S),o.pixelStorei(o.UNPACK_SKIP_PIXELS,M),o.pixelStorei(o.UNPACK_SKIP_ROWS,A),o.pixelStorei(o.UNPACK_SKIP_IMAGES,N),0===n&&t.generateMipmaps&&o.generateMipmap(u),l.unbindTexture()}copyFramebufferToTexture(e,t,s){const{gl:i}=this,{state:r}=this.backend,{textureGPU:n}=this.backend.get(e),{x:o,y:a,z:l,w:h}=s,u=!0===e.isDepthTexture||t.renderTarget&&t.renderTarget.samples>0,c=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(u){const s=0!==o||0!==a;let u,d;if(!0===e.isDepthTexture?(u=i.DEPTH_BUFFER_BIT,d=i.DEPTH_ATTACHMENT,t.stencil&&(u|=i.STENCIL_BUFFER_BIT)):(u=i.COLOR_BUFFER_BIT,d=i.COLOR_ATTACHMENT0),s){const e=this.backend.get(t.renderTarget),s=e.framebuffers[t.getCacheKey()],d=e.msaaFrameBuffer;r.bindFramebuffer(i.DRAW_FRAMEBUFFER,s),r.bindFramebuffer(i.READ_FRAMEBUFFER,d);const p=c-a-h;i.blitFramebuffer(o,p,o+l,p+h,o,p,o+l,p+h,u,i.NEAREST),r.bindFramebuffer(i.READ_FRAMEBUFFER,s),r.bindTexture(i.TEXTURE_2D,n),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,o,p,l,h),r.unbindTexture()}else{const e=i.createFramebuffer();r.bindFramebuffer(i.DRAW_FRAMEBUFFER,e),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,d,i.TEXTURE_2D,n,0),i.blitFramebuffer(0,0,l,h,0,0,l,h,u,i.NEAREST),i.deleteFramebuffer(e)}}else r.bindTexture(i.TEXTURE_2D,n),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,o,c-h-a,l,h),r.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,s,i=!1){const{gl:r}=this,n=t.renderTarget,{depthTexture:o,depthBuffer:a,stencilBuffer:l,width:h,height:u}=n;if(r.bindRenderbuffer(r.RENDERBUFFER,e),a&&!l){let t=r.DEPTH_COMPONENT24;if(!0===i){this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(r.RENDERBUFFER,n.samples,t,h,u)}else s>0?(o&&o.isDepthTexture&&o.type===r.FLOAT&&(t=r.DEPTH_COMPONENT32F),r.renderbufferStorageMultisample(r.RENDERBUFFER,s,t,h,u)):r.renderbufferStorage(r.RENDERBUFFER,t,h,u);r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,e)}else a&&l&&(s>0?r.renderbufferStorageMultisample(r.RENDERBUFFER,s,r.DEPTH24_STENCIL8,h,u):r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,h,u),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,e));r.bindRenderbuffer(r.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,s,i,r,n){const{backend:o,gl:a}=this,{textureGPU:l,glFormat:h,glType:u}=this.backend.get(e),c=a.createFramebuffer();o.state.bindFramebuffer(a.READ_FRAMEBUFFER,c);const d=e.isCubeTexture?a.TEXTURE_CUBE_MAP_POSITIVE_X+n:a.TEXTURE_2D;a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,d,l,0);const p=this._getTypedArrayType(u),m=i*r*this._getBytesPerTexel(u,h),f=a.createBuffer();a.bindBuffer(a.PIXEL_PACK_BUFFER,f),a.bufferData(a.PIXEL_PACK_BUFFER,m,a.STREAM_READ),a.readPixels(t,s,i,r,h,u,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),await o.utils._clientWaitAsync();const g=new p(m/p.BYTES_PER_ELEMENT);return a.bindBuffer(a.PIXEL_PACK_BUFFER,f),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,g),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),o.state.bindFramebuffer(a.READ_FRAMEBUFFER,null),a.deleteFramebuffer(c),g}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_5_5_1)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_6_5)return Uint16Array;if(e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:s}=this;let i=0;return e===s.UNSIGNED_BYTE&&(i=1),e!==s.UNSIGNED_SHORT_4_4_4_4&&e!==s.UNSIGNED_SHORT_5_5_5_1&&e!==s.UNSIGNED_SHORT_5_6_5&&e!==s.UNSIGNED_SHORT&&e!==s.HALF_FLOAT||(i=2),e!==s.UNSIGNED_INT&&e!==s.FLOAT||(i=4),t===s.RGBA?4*i:t===s.RGB?3*i:t===s.ALPHA?i:void 0}dispose(){const{gl:e}=this;null!==this._srcFramebuffer&&e.deleteFramebuffer(this._srcFramebuffer),null!==this._dstFramebuffer&&e.deleteFramebuffer(this._dstFramebuffer)}}function mB(e){return e.isDataTexture?e.image.data:"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas?e:e.data}class fB{constructor(e){this.backend=e,this.gl=this.backend.gl,this.availableExtensions=this.gl.getSupportedExtensions(),this.extensions={}}get(e){let t=this.extensions[e];return void 0===t&&(t=this.gl.getExtension(e),this.extensions[e]=t),t}has(e){return this.availableExtensions.includes(e)}}class gB{constructor(e){this.backend=e,this.maxAnisotropy=null}getMaxAnisotropy(){if(null!==this.maxAnisotropy)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(!0===t.has("EXT_texture_filter_anisotropic")){const s=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const yB={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-s3tc",EXT_texture_compression_bptc:"texture-compression-bc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class xB{constructor(e){this.gl=e.gl,this.extensions=e.extensions,this.info=e.renderer.info,this.mode=null,this.index=0,this.type=null,this.object=null}render(e,t){const{gl:s,mode:i,object:r,type:n,info:o,index:a}=this;0!==a?s.drawElements(i,t,n,e):s.drawArrays(i,e,t),o.update(r,t,1)}renderInstances(e,t,s){const{gl:i,mode:r,type:n,index:o,object:a,info:l}=this;0!==s&&(0!==o?i.drawElementsInstanced(r,t,n,e,s):i.drawArraysInstanced(r,e,t,s),l.update(a,t,s))}renderMultiDraw(e,t,s){const{extensions:i,mode:r,object:n,info:o}=this;if(0===s)return;const a=i.get("WEBGL_multi_draw");if(null===a)for(let i=0;i<s;i++)this.render(e[i],t[i]);else{0!==this.index?a.multiDrawElementsWEBGL(r,t,0,this.type,e,0,s):a.multiDrawArraysWEBGL(r,e,0,t,0,s);let i=0;for(let e=0;e<s;e++)i+=t[e];o.update(n,i,1)}}renderMultiDrawInstances(e,t,s,i){const{extensions:r,mode:n,object:o,info:a}=this;if(0===s)return;const l=r.get("WEBGL_multi_draw");if(null===l)for(let r=0;r<s;r++)this.renderInstances(e[r],t[r],i[r]);else{0!==this.index?l.multiDrawElementsInstancedWEBGL(n,t,0,this.type,e,0,i,0,s):l.multiDrawArraysInstancedWEBGL(n,e,0,t,0,i,0,s);let r=0;for(let e=0;e<s;e++)r+=t[e]*i[e];a.update(o,r,1)}}}class bB{constructor(e=256){this.trackTimestamp=!0,this.maxQueries=e,this.currentQueryIndex=0,this.queryOffsets=new Map,this.isDisposed=!1,this.lastValue=0,this.frames=[],this.pendingResolve=!1,this.timestamps=new Map}getTimestampFrames(){return this.frames}getTimestamp(e){let t=this.timestamps.get(e);return void 0===t&&(Yo(`TimestampQueryPool: No timestamp available for uid ${e}.`),t=0),t}hasTimestamp(e){return this.timestamps.has(e)}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class _B extends bB{constructor(e,t,s=2048){if(super(s),this.gl=e,this.type=t,this.ext=e.getExtension("EXT_disjoint_timer_query_webgl2")||e.getExtension("EXT_disjoint_timer_query"),!this.ext)return Yo("EXT_disjoint_timer_query not supported; timestamps will be disabled."),void(this.trackTimestamp=!1);this.queries=[];for(let t=0;t<this.maxQueries;t++)this.queries.push(e.createQuery());this.activeQuery=null,this.queryStates=new Map}allocateQueriesForContext(e){if(!this.trackTimestamp)return null;if(this.currentQueryIndex+2>this.maxQueries)return Qo(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null==t)return;if(null!==this.activeQuery)return;const s=this.queries[t];if(s)try{"inactive"===this.queryStates.get(t)&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,s),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(e){Zo("Error in beginQuery:",e),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null!=t&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(e){Zo("Error in endQuery:",e),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{const e=new Map;for(const[t,s]of this.queryOffsets){if("ended"===this.queryStates.get(s)){const i=this.queries[s];e.set(t,this.resolveQuery(i))}}if(0===e.size)return this.lastValue;const t={},s=[];for(const[i,r]of e){const e=i.match(/^(.*):f(\d+)$/),n=parseInt(e[2]);!1===s.includes(n)&&s.push(n),void 0===t[n]&&(t[n]=0);const o=await r;this.timestamps.set(i,o),t[n]+=o}const i=t[s[s.length-1]];return this.lastValue=i,this.frames=s,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,i}catch(e){return Zo("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise(t=>{if(this.isDisposed)return void t(this.lastValue);let s,i=!1;const r=e=>{i||(i=!0,s&&(clearTimeout(s),s=null),t(e))},n=()=>{if(this.isDisposed)r(this.lastValue);else try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT))return void r(this.lastValue);if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE))return void(s=setTimeout(n,1));const i=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(i)/1e6)}catch(e){Zo("Error checking query:",e),t(this.lastValue)}};n()})}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}class wB extends tB{constructor(e={}){super(e),this.isWebGLBackend=!0,this.attributeUtils=null,this.extensions=null,this.capabilities=null,this.textureUtils=null,this.bufferRenderer=null,this.gl=null,this.state=null,this.utils=null,this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.disjoint=null,this.parallel=null,this._currentContext=null,this._knownBindings=new WeakSet,this._supportsInvalidateFramebuffer="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),this._xrFramebuffer=null}init(e){super.init(e);const t=this.parameters,s={antialias:e.currentSamples>0,alpha:!0,depth:e.depth,stencil:e.stencil},i=void 0!==t.context?t.context:e.domElement.getContext("webgl2",s);function r(t){t.preventDefault();const s={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(s)}this._onContextLost=r,e.domElement.addEventListener("webglcontextlost",r,!1),this.gl=i,this.extensions=new fB(this),this.capabilities=new gB(this),this.attributeUtils=new oB(this),this.textureUtils=new pB(this),this.bufferRenderer=new xB(this),this.state=new aB(this),this.utils=new lB(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile"),this.drawBuffersIndexedExt=this.extensions.get("OES_draw_buffers_indexed")}get coordinateSystem(){return ko}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,s=null){const i=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:i.RGBA8}),null!==s){const t=e.stencilBuffer?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:s,glInternalFormat:t}),!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!0===e._autoAllocateDepthBuffer&&!1===e.multiview&&Yo("WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e._autoAllocateDepthBuffer=!1}}initTimestampQuery(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new _B(this.gl,e,2048));const s=this.timestampQueryPool[e];null!==s.allocateQueriesForContext(t)&&s.beginQuery(t)}prepareTimestampBuffer(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e].endQuery(t)}getContext(){return this.gl}beginRender(e){const{state:t}=this,s=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:e,height:s}=this.getDrawingBufferSize();t.viewport(0,0,e,s)}if(e.scissor){const{x:s,y:i,width:r,height:n}=e.scissorValue;t.scissor(s,e.height-n-i,r,n)}this.initTimestampQuery(jo,this.getTimestampUID(e)),s.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const i=e.occlusionQueryCount;i>0&&(s.currentOcclusionQueries=s.occlusionQueries,s.currentOcclusionQueryObjects=s.occlusionQueryObjects,s.lastOcclusionObject=null,s.occlusionQueries=new Array(i),s.occlusionQueryObjects=new Array(i),s.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:s}=this,i=this.get(e),r=i.previousContext;s.resetVertexState();const n=e.occlusionQueryCount;n>0&&(n>i.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const o=e.textures;if(null!==o)for(let e=0;e<o.length;e++){const t=o[e];t.generateMipmaps&&this.generateMipmaps(t)}if(this._currentContext=r,this._resolveRenderTarget(e),null!==r)if(this._setFramebuffer(r),r.viewport)this.updateViewport(r);else{const{width:e,height:t}=this.getDrawingBufferSize();s.viewport(0,0,e,t)}this.prepareTimestampBuffer(jo,this.getTimestampUID(e))}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:s,currentOcclusionQueryObjects:i}=t;if(s&&i){const e=new WeakSet,{gl:r}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const n=()=>{let o=0;for(let t=0;t<s.length;t++){const n=s[t];null!==n&&(r.getQueryParameter(n,r.QUERY_RESULT_AVAILABLE)&&(0===r.getQueryParameter(n,r.QUERY_RESULT)&&e.add(i[t]),s[t]=null,r.deleteQuery(n),o++))}o<s.length?requestAnimationFrame(n):t.occluded=e};n()}}isOccluded(e,t){const s=this.get(e);return s.occluded&&s.occluded.has(t)}updateViewport(e){const{state:t}=this,{x:s,y:i,width:r,height:n}=e.viewportValue;t.viewport(s,e.height-n-i,r,n)}setScissorTest(e){this.state.setScissorTest(e)}getClearColor(){const e=super.getClearColor();return e.r*=e.a,e.g*=e.a,e.b*=e.a,e}clear(e,t,s,i=null,r=!0,n=!0){const{gl:o,renderer:a}=this;if(null===i){i={textures:null,clearColorValue:this.getClearColor()}}let l=0;if(e&&(l|=o.COLOR_BUFFER_BIT),t&&(l|=o.DEPTH_BUFFER_BIT),s&&(l|=o.STENCIL_BUFFER_BIT),0!==l){let h;h=i.clearColorValue?i.clearColorValue:this.getClearColor();const u=a.getClearDepth(),c=a.getClearStencil();if(t&&this.state.setDepthMask(!0),null===i.textures)o.clearColor(h.r,h.g,h.b,h.a),o.clear(l);else{if(r&&this._setFramebuffer(i),e)for(let e=0;e<i.textures.length;e++)0===e?o.clearBufferfv(o.COLOR,e,[h.r,h.g,h.b,h.a]):o.clearBufferfv(o.COLOR,e,[0,0,0,1]);t&&s?o.clearBufferfi(o.DEPTH_STENCIL,0,u,c):t?o.clearBufferfv(o.DEPTH,0,[u]):s&&o.clearBufferiv(o.STENCIL,0,[c]),r&&n&&this._resolveRenderTarget(i)}}}beginCompute(e){const{state:t,gl:s}=this;t.bindFramebuffer(s.FRAMEBUFFER,null),this.initTimestampQuery(Go,this.getTimestampUID(e))}compute(e,t,s,i,r=null){const{state:n,gl:o}=this;!1===this.discard&&(n.enable(o.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:a,transformBuffers:l,attributes:h}=this.get(i),u=this._getVaoKey(h),c=this.vaoCache[u];void 0===c?this.vaoCache[u]=this._createVao(h):n.setVertexState(c),n.useProgram(a),this._bindUniforms(s);const d=this._getTransformFeedback(l);o.bindTransformFeedback(o.TRANSFORM_FEEDBACK,d),o.beginTransformFeedback(o.POINTS),r=null!==r?r:t.count,Array.isArray(r)?(Qo("WebGLBackend.compute(): The count parameter must be a single number, not an array."),r=r[0]):r&&"object"==typeof r&&r.isIndirectStorageBufferAttribute&&(Qo("WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute"),r=t.count),h[0].isStorageInstancedBufferAttribute?o.drawArraysInstanced(o.POINTS,0,1,r):o.drawArrays(o.POINTS,0,r),o.endTransformFeedback(),o.bindTransformFeedback(o.TRANSFORM_FEEDBACK,null);for(let e=0;e<l.length;e++){const t=l[e];t.pbo&&this.has(t.pbo)&&this.textureUtils.copyBufferToTexture(t.transformBuffer,t.pbo),t.switchBuffers()}}finishCompute(e){const{state:t,gl:s}=this;this.discard=!1,t.disable(s.RASTERIZER_DISCARD),this.prepareTimestampBuffer(Go,this.getTimestampUID(e)),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isArrayTexture&&e.camera.isArrayCamera}draw(e){const{object:t,pipeline:s,material:i,context:r,hardwareClippingPlanes:n}=e,{programGPU:o}=this.get(s),{gl:a,state:l}=this,h=this.get(r),u=e.getDrawParameters();if(null===u)return;this._bindUniforms(e.getBindings());const c=t.isMesh&&t.matrixWorld.determinant()<0;l.setMaterial(i,c,n),null!==r.textures&&r.textures.length>1&&l.setMRTBlending(r.textures),l.useProgram(o);const d=e.getAttributes(),p=this.get(d);let m=p.vaoGPU;if(void 0===m){const e=this._getVaoKey(d);m=this.vaoCache[e],void 0===m&&(m=this._createVao(d),this.vaoCache[e]=m,p.vaoGPU=m)}const f=e.getIndex(),g=null!==f?this.get(f).bufferGPU:null;l.setVertexState(m,g);const y=h.lastOcclusionObject;if(y!==t&&void 0!==y){if(null!==y&&!0===y.occlusionTest&&(a.endQuery(a.ANY_SAMPLES_PASSED),h.occlusionQueryIndex++),!0===t.occlusionTest){const e=a.createQuery();a.beginQuery(a.ANY_SAMPLES_PASSED,e),h.occlusionQueries[h.occlusionQueryIndex]=e,h.occlusionQueryObjects[h.occlusionQueryIndex]=t}h.lastOcclusionObject=t}const x=this.bufferRenderer;t.isPoints?x.mode=a.POINTS:t.isLineSegments?x.mode=a.LINES:t.isLine?x.mode=a.LINE_STRIP:t.isLineLoop?x.mode=a.LINE_LOOP:!0===i.wireframe?(l.setLineWidth(i.wireframeLinewidth*this.renderer.getPixelRatio()),x.mode=a.LINES):x.mode=a.TRIANGLES;const{vertexCount:b,instanceCount:_}=u;let{firstVertex:w}=u;if(x.object=t,null!==f){w*=f.array.BYTES_PER_ELEMENT;const e=this.get(f);x.index=f.count,x.type=e.type}else x.index=0;const v=()=>{t.isBatchedMesh?null!==t._multiDrawInstances?(Qo("WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),x.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?x.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):Qo("WebGLBackend: WEBGL_multi_draw not supported."):_>1?x.renderInstances(w,b,_):x.render(w,b)};if(!0===e.camera.isArrayCamera&&e.camera.cameras.length>0&&!1===e.camera.isMultiViewCamera){const s=this.get(e.camera),i=e.camera.cameras,r=e.getBindingGroup("cameraIndex").bindings[0];if(void 0===s.indexesGPU||s.indexesGPU.length!==i.length){const e=new Uint32Array([0,0,0,0]),t=[];for(let s=0,r=i.length;s<r;s++){const i=a.createBuffer();e[0]=s,a.bindBuffer(a.UNIFORM_BUFFER,i),a.bufferData(a.UNIFORM_BUFFER,e,a.STATIC_DRAW),t.push(i)}s.indexesGPU=t}const n=this.get(r),o=this.renderer.getPixelRatio(),h=this._currentContext.renderTarget,u=this._isRenderCameraDepthArray(this._currentContext),c=this._currentContext.activeCubeFace;if(u){const e=this.get(h.depthTexture);if(e.clearedRenderId!==this.renderer._nodes.nodeFrame.renderId){e.clearedRenderId=this.renderer._nodes.nodeFrame.renderId;const{stencilBuffer:t}=h;for(let e=0,s=i.length;e<s;e++)this.renderer._activeCubeFace=e,this._currentContext.activeCubeFace=e,this._setFramebuffer(this._currentContext),this.clear(!1,!0,t,this._currentContext,!1,!1);this.renderer._activeCubeFace=c,this._currentContext.activeCubeFace=c}}for(let r=0,h=i.length;r<h;r++){const h=i[r];if(t.layers.test(h.layers)){u&&(this.renderer._activeCubeFace=r,this._currentContext.activeCubeFace=r,this._setFramebuffer(this._currentContext));const t=h.viewport;if(void 0!==t){const s=t.x*o,i=t.y*o,r=t.width*o,n=t.height*o;l.viewport(Math.floor(s),Math.floor(e.context.height-n-i),Math.floor(r),Math.floor(n))}l.bindBufferBase(a.UNIFORM_BUFFER,n.index,s.indexesGPU[r]),v()}this._currentContext.activeCubeFace=c,this.renderer._activeCubeFace=c}}else v()}needsRenderUpdate(){return!1}getRenderCacheKey(){return""}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}updateSampler(){return""}createNodeBuilder(e,t){return new KP(e,t)}createProgram(e){const t=this.gl,{stage:s,code:i}=e,r="fragment"===s?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(r,i),t.compileShader(r),this.set(e,{shaderGPU:r})}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){const s=this.gl,i=e.pipeline,{fragmentProgram:r,vertexProgram:n}=i,o=s.createProgram(),a=this.get(r).shaderGPU,l=this.get(n).shaderGPU;if(s.attachShader(o,a),s.attachShader(o,l),s.linkProgram(o),this.set(i,{programGPU:o,fragmentShader:a,vertexShader:l}),null!==t&&this.parallel){const r=new Promise(t=>{const r=this.parallel,n=()=>{s.getProgramParameter(o,r.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),t()):requestAnimationFrame(n)};n()});return void t.push(r)}this._completeCompile(e,i)}_handleSource(e,t){const s=e.split("\n"),i=[],r=Math.max(t-6,0),n=Math.min(t+6,s.length);for(let e=r;e<n;e++){const r=e+1;i.push(`${r===t?">":" "} ${r}: ${s[e]}`)}return i.join("\n")}_getShaderErrors(e,t,s){const i=e.getShaderParameter(t,e.COMPILE_STATUS),r=(e.getShaderInfoLog(t)||"").trim();if(i&&""===r)return"";const n=/ERROR: 0:(\d+)/.exec(r);if(n){const i=parseInt(n[1]);return s.toUpperCase()+"\n\n"+r+"\n\n"+this._handleSource(e.getShaderSource(t),i)}return r}_logProgramError(e,t,s){if(this.renderer.debug.checkShaderErrors){const i=this.gl,r=(i.getProgramInfoLog(e)||"").trim();if(!1===i.getProgramParameter(e,i.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(i,e,s,t);else{const n=this._getShaderErrors(i,s,"vertex"),o=this._getShaderErrors(i,t,"fragment");Zo("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(e,i.VALIDATE_STATUS)+"\n\nProgram Info Log: "+r+"\n"+n+"\n"+o)}else""!==r&&Yo("WebGLProgram: Program Info Log:",r)}}_completeCompile(e,t){const{state:s,gl:i}=this,r=this.get(t),{programGPU:n,fragmentShader:o,vertexShader:a}=r;!1===i.getProgramParameter(n,i.LINK_STATUS)&&this._logProgramError(n,o,a),s.useProgram(n);const l=e.getBindings();this._setupBindings(l,n),this.set(t,{programGPU:n})}createComputePipeline(e,t){const{state:s,gl:i}=this,r={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(r);const{computeProgram:n}=e,o=i.createProgram(),a=this.get(r).shaderGPU,l=this.get(n).shaderGPU,h=n.transforms,u=[],c=[];for(let e=0;e<h.length;e++){const t=h[e];u.push(t.varyingName),c.push(t.attributeNode)}i.attachShader(o,a),i.attachShader(o,l),i.transformFeedbackVaryings(o,u,i.SEPARATE_ATTRIBS),i.linkProgram(o),!1===i.getProgramParameter(o,i.LINK_STATUS)&&this._logProgramError(o,a,l),s.useProgram(o),this._setupBindings(t,o);const d=n.attributes,p=[],m=[];for(let e=0;e<d.length;e++){const t=d[e].node.attribute;p.push(t),this.has(t)||this.attributeUtils.createAttribute(t,i.ARRAY_BUFFER)}for(let e=0;e<c.length;e++){const t=c[e].attribute;this.has(t)||this.attributeUtils.createAttribute(t,i.ARRAY_BUFFER);const s=this.get(t);m.push(s)}this.set(e,{programGPU:o,transformBuffers:m,attributes:p})}createBindings(e,t){if(!1===this._knownBindings.has(t)){this._knownBindings.add(t);let e=0,s=0;for(const i of t){this.set(i,{textures:s,uniformBuffers:e});for(const t of i.bindings)t.isUniformBuffer&&e++,t.isSampledTexture&&s++}}this.updateBindings(e,t)}updateBindings(e){const{gl:t}=this,s=this.get(e);let i=s.uniformBuffers,r=s.textures;for(const s of e.bindings){const e=this.get(s);if(s.isUniformsGroup||s.isUniformBuffer){const r=s.buffer;let{bufferGPU:n}=this.get(r);void 0===n?(n=t.createBuffer(),t.bindBuffer(t.UNIFORM_BUFFER,n),t.bufferData(t.UNIFORM_BUFFER,r.byteLength,t.DYNAMIC_DRAW),this.set(r,{bufferGPU:n})):t.bindBuffer(t.UNIFORM_BUFFER,n);const o=s.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,n),0===o.length)t.bufferData(t.UNIFORM_BUFFER,r,t.DYNAMIC_DRAW);else{const e=Wo(r),s=e?1:r.BYTES_PER_ELEMENT;for(let i=0,n=o.length;i<n;i++){const n=o[i],a=n.start*s,l=n.count*s,h=a*(e?r.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,h,r,a,l)}}e.index=i++,e.bufferGPU=n,this.set(s,e)}else if(s.isSampledTexture){const{textureGPU:t,glTextureType:i}=this.get(s.texture);e.index=r++,e.textureGPU=t,e.glTextureType=i,this.set(s,e)}}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const s=this.get(e).bufferGPU,i=e.buffer,r=e.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,s),0===r.length)t.bufferData(t.UNIFORM_BUFFER,i,t.DYNAMIC_DRAW);else{const e=Wo(i),s=e?1:i.BYTES_PER_ELEMENT;for(let n=0,o=r.length;n<o;n++){const o=r[n],a=o.start*s,l=o.count*s,h=a*(e?i.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,h,i,a,l)}}}}createIndexAttribute(e){const t=this.gl;this.attributeUtils.createAttribute(e,t.ELEMENT_ARRAY_BUFFER)}createAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}createStorageAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}hasFeature(e){const t=Object.keys(yB).filter(t=>yB[t]===e),s=this.extensions;for(let e=0;e<t.length;e++)if(s.has(t[e]))return!0;return!1}getMaxAnisotropy(){return this.capabilities.getMaxAnisotropy()}copyTextureToTexture(e,t,s=null,i=null,r=0,n=0){this.textureUtils.copyTextureToTexture(e,t,s,i,r,n)}copyFramebufferToTexture(e,t,s){this.textureUtils.copyFramebufferToTexture(e,t,s)}_setFramebuffer(e){const{gl:t,state:s}=this;let i=null;if(null!==e.textures){const r=e.renderTarget,n=this.get(r),{samples:o,depthBuffer:a,stencilBuffer:l}=r,h=!0===r.isWebGLCubeRenderTarget,u=!0===r.isRenderTarget3D,c=r.depth>1,d=!0===r.isXRRenderTarget,p=!0===d&&!0===r._hasExternalTextures;let m=n.msaaFrameBuffer,f=n.depthRenderbuffer;const g=this.extensions.get("WEBGL_multisampled_render_to_texture"),y=this.extensions.get("OVR_multiview2"),x=this._useMultisampledExtension(r),b=VS(e);let _;if(h?(n.cubeFramebuffers||(n.cubeFramebuffers={}),_=n.cubeFramebuffers[b]):d&&!1===p?_=this._xrFramebuffer:(n.framebuffers||(n.framebuffers={}),_=n.framebuffers[b]),void 0===_){_=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,_);const i=e.textures,a=[];if(h){n.cubeFramebuffers[b]=_;const{textureGPU:e}=this.get(i[0]),s=this.renderer._activeCubeFace,r=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+s,e,r)}else{n.framebuffers[b]=_;for(let s=0;s<i.length;s++){const n=i[s],a=this.get(n);a.renderTarget=e.renderTarget,a.cacheKey=b;const l=t.COLOR_ATTACHMENT0+s;if(r.multiview)y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,l,a.textureGPU,0,o,0,2);else if(u||c){const e=this.renderer._activeCubeFace,s=this.renderer._activeMipmapLevel;t.framebufferTextureLayer(t.FRAMEBUFFER,l,a.textureGPU,s,e)}else if(x)g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,l,t.TEXTURE_2D,a.textureGPU,0,o);else{const e=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,l,t.TEXTURE_2D,a.textureGPU,e)}}}const d=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===r._autoAllocateDepthBuffer){const s=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(s,e,0,x),n.xrDepthRenderbuffer=s,a.push(l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),t.bindRenderbuffer(t.RENDERBUFFER,s),t.framebufferRenderbuffer(t.FRAMEBUFFER,d,t.RENDERBUFFER,s)}else if(null!==e.depthTexture){a.push(l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);const s=this.get(e.depthTexture);if(s.renderTarget=e.renderTarget,s.cacheKey=b,r.multiview)y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,d,s.textureGPU,0,o,0,2);else if(p&&x)g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,d,t.TEXTURE_2D,s.textureGPU,0,o);else if(e.depthTexture.isArrayTexture){const e=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,d,s.textureGPU,0,e)}else if(e.depthTexture.isCubeTexture){const e=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,d,t.TEXTURE_CUBE_MAP_POSITIVE_X+e,s.textureGPU,0)}else t.framebufferTexture2D(t.FRAMEBUFFER,d,t.TEXTURE_2D,s.textureGPU,0)}n.depthInvalidationArray=a}else{if(this._isRenderCameraDepthArray(e)){s.bindFramebuffer(t.FRAMEBUFFER,_);const i=this.renderer._activeCubeFace,r=this.get(e.depthTexture),n=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,n,r.textureGPU,0,i)}if((d||x||r.multiview)&&!0!==r._isOpaqueFramebuffer){s.bindFramebuffer(t.FRAMEBUFFER,_);const i=this.get(e.textures[0]);r.multiview?y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,i.textureGPU,0,o,0,2):x?g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i.textureGPU,0,o):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i.textureGPU,0);const a=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===r._autoAllocateDepthBuffer){const e=n.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,e),t.framebufferRenderbuffer(t.FRAMEBUFFER,a,t.RENDERBUFFER,e)}else{const s=this.get(e.depthTexture);r.multiview?y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,a,s.textureGPU,0,o,0,2):x?g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,a,t.TEXTURE_2D,s.textureGPU,0,o):t.framebufferTexture2D(t.FRAMEBUFFER,a,t.TEXTURE_2D,s.textureGPU,0)}}}if(o>0&&!1===x&&!r.multiview){if(void 0===m){const i=[];m=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,m);const r=[],h=e.textures;for(let s=0;s<h.length;s++){r[s]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,r[s]),i.push(t.COLOR_ATTACHMENT0+s);const n=e.textures[s],a=this.get(n);t.renderbufferStorageMultisample(t.RENDERBUFFER,o,a.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+s,t.RENDERBUFFER,r[s])}if(t.bindRenderbuffer(t.RENDERBUFFER,null),n.msaaFrameBuffer=m,n.msaaRenderbuffers=r,a&&void 0===f){f=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(f,e,o),n.depthRenderbuffer=f;const s=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;i.push(s)}n.invalidationArray=i}i=n.msaaFrameBuffer}else i=_;s.drawBuffers(e,_)}s.bindFramebuffer(t.FRAMEBUFFER,i)}_getVaoKey(e){let t="";for(let s=0;s<e.length;s++){t+=":"+this.get(e[s]).id}return t}_createVao(e){const{gl:t}=this,s=t.createVertexArray();t.bindVertexArray(s);for(let s=0;s<e.length;s++){const i=e[s],r=this.get(i);let n,o;t.bindBuffer(t.ARRAY_BUFFER,r.bufferGPU),t.enableVertexAttribArray(s),!0===i.isInterleavedBufferAttribute?(n=i.data.stride*r.bytesPerElement,o=i.offset*r.bytesPerElement):(n=0,o=0),r.isInteger?t.vertexAttribIPointer(s,i.itemSize,r.type,n,o):t.vertexAttribPointer(s,i.itemSize,r.type,i.normalized,n,o),i.isInstancedBufferAttribute&&!i.isInterleavedBufferAttribute?t.vertexAttribDivisor(s,i.meshPerAttribute):i.isInterleavedBufferAttribute&&i.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(s,i.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),s}_getTransformFeedback(e){let t="";for(let s=0;s<e.length;s++)t+=":"+e[s].id;let s=this.transformFeedbackCache[t];if(void 0!==s)return s;const{gl:i}=this;s=i.createTransformFeedback(),i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,s);for(let t=0;t<e.length;t++){const s=e[t];i.bindBufferBase(i.TRANSFORM_FEEDBACK_BUFFER,t,s.transformBuffer)}return i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,null),this.transformFeedbackCache[t]=s,s}_setupBindings(e,t){const s=this.gl;for(const i of e)for(const e of i.bindings){const i=this.get(e).index;if(e.isUniformsGroup||e.isUniformBuffer){const r=s.getUniformBlockIndex(t,e.name);s.uniformBlockBinding(t,r,i)}else if(e.isSampledTexture){const r=s.getUniformLocation(t,e.name);s.uniform1i(r,i)}}}_bindUniforms(e){const{gl:t,state:s}=this;for(const i of e)for(const e of i.bindings){const i=this.get(e),r=i.index;e.isUniformsGroup||e.isUniformBuffer?s.bindBufferBase(t.UNIFORM_BUFFER,r,i.bufferGPU):e.isSampledTexture&&s.bindTexture(i.glTextureType,i.textureGPU,t.TEXTURE0+r)}}_resolveRenderTarget(e){const{gl:t,state:s}=this,i=e.renderTarget;if(null!==e.textures&&i){const r=this.get(i);if(i.samples>0&&!1===this._useMultisampledExtension(i)){const n=r.framebuffers[e.getCacheKey()];let o=t.COLOR_BUFFER_BIT;i.resolveDepthBuffer&&(i.depthBuffer&&(o|=t.DEPTH_BUFFER_BIT),i.stencilBuffer&&i.resolveStencilBuffer&&(o|=t.STENCIL_BUFFER_BIT));const a=r.msaaFrameBuffer,l=r.msaaRenderbuffers,h=e.textures,u=h.length>1;if(s.bindFramebuffer(t.READ_FRAMEBUFFER,a),s.bindFramebuffer(t.DRAW_FRAMEBUFFER,n),u)for(let e=0;e<h.length;e++)t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,null),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,null,0);for(let s=0;s<h.length;s++){if(u){const{textureGPU:e}=this.get(h[s]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,l[s]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0)}if(e.scissor){const{x:s,y:i,width:r,height:n}=e.scissorValue,a=e.height-n-i;t.blitFramebuffer(s,a,s+r,a+n,s,a,s+r,a+n,o,t.NEAREST)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,o,t.NEAREST)}if(u)for(let e=0;e<h.length;e++){const{textureGPU:s}=this.get(h[e]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,l[e]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,s,0)}!0===this._supportsInvalidateFramebuffer&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,r.invalidationArray)}else if(!1===i.resolveDepthBuffer&&r.framebuffers){const i=r.framebuffers[e.getCacheKey()];s.bindFramebuffer(t.DRAW_FRAMEBUFFER,i),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,r.depthInvalidationArray)}}}_useMultisampledExtension(e){return!0===e.multiview||e.samples>0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}dispose(){null!==this.textureUtils&&this.textureUtils.dispose();const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const vB="point-list",TB="line-list",SB="line-strip",MB="triangle-list",AB="triangle-strip",NB="undefined"!=typeof self?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},EB="never",CB="less",RB="equal",PB="less-equal",BB="greater",IB="not-equal",DB="greater-equal",LB="always",FB="store",OB="load",VB="clear",zB="ccw",kB="cw",UB="none",GB="back",jB="uint16",$B="uint32",WB="r8unorm",HB="r8snorm",qB="r8uint",XB="r8sint",YB="r16uint",ZB="r16sint",QB="r16float",KB="rg8unorm",JB="rg8snorm",eI="rg8uint",tI="rg8sint",sI="r32uint",iI="r32sint",rI="r32float",nI="rg16uint",oI="rg16sint",aI="rg16float",lI="rgba8unorm",hI="rgba8unorm-srgb",uI="rgba8snorm",cI="rgba8uint",dI="rgba8sint",pI="bgra8unorm",mI="bgra8unorm-srgb",fI="rgb9e5ufloat",gI="rgb10a2unorm",yI="rg11b10ufloat",xI="rg32uint",bI="rg32sint",_I="rg32float",wI="rgba16uint",vI="rgba16sint",TI="rgba16float",SI="rgba32uint",MI="rgba32sint",AI="rgba32float",NI="depth16unorm",EI="depth24plus",CI="depth24plus-stencil8",RI="depth32float",PI="depth32float-stencil8",BI="bc1-rgba-unorm",II="bc1-rgba-unorm-srgb",DI="bc2-rgba-unorm",LI="bc2-rgba-unorm-srgb",FI="bc3-rgba-unorm",OI="bc3-rgba-unorm-srgb",VI="bc4-r-unorm",zI="bc4-r-snorm",kI="bc5-rg-unorm",UI="bc5-rg-snorm",GI="bc6h-rgb-ufloat",jI="bc6h-rgb-float",$I="bc7-rgba-unorm",WI="bc7-rgba-unorm-srgb",HI="etc2-rgb8unorm",qI="etc2-rgb8unorm-srgb",XI="etc2-rgb8a1unorm",YI="etc2-rgb8a1unorm-srgb",ZI="etc2-rgba8unorm",QI="etc2-rgba8unorm-srgb",KI="eac-r11unorm",JI="eac-r11snorm",eD="eac-rg11unorm",tD="eac-rg11snorm",sD="astc-4x4-unorm",iD="astc-4x4-unorm-srgb",rD="astc-5x4-unorm",nD="astc-5x4-unorm-srgb",oD="astc-5x5-unorm",aD="astc-5x5-unorm-srgb",lD="astc-6x5-unorm",hD="astc-6x5-unorm-srgb",uD="astc-6x6-unorm",cD="astc-6x6-unorm-srgb",dD="astc-8x5-unorm",pD="astc-8x5-unorm-srgb",mD="astc-8x6-unorm",fD="astc-8x6-unorm-srgb",gD="astc-8x8-unorm",yD="astc-8x8-unorm-srgb",xD="astc-10x5-unorm",bD="astc-10x5-unorm-srgb",_D="astc-10x6-unorm",wD="astc-10x6-unorm-srgb",vD="astc-10x8-unorm",TD="astc-10x8-unorm-srgb",SD="astc-10x10-unorm",MD="astc-10x10-unorm-srgb",AD="astc-12x10-unorm",ND="astc-12x10-unorm-srgb",ED="astc-12x12-unorm",CD="astc-12x12-unorm-srgb",RD="clamp-to-edge",PD="repeat",BD="mirror-repeat",ID="linear",DD="nearest",LD="zero",FD="one",OD="src",VD="one-minus-src",zD="src-alpha",kD="one-minus-src-alpha",UD="dst",GD="one-minus-dst",jD="dst-alpha",$D="one-minus-dst-alpha",WD="src-alpha-saturated",HD="constant",qD="one-minus-constant",XD="add",YD="subtract",ZD="reverse-subtract",QD="min",KD="max",JD=0,eL=15,tL="keep",sL="zero",iL="replace",rL="invert",nL="increment-clamp",oL="decrement-clamp",aL="increment-wrap",lL="decrement-wrap",hL="storage",uL="read-only-storage",cL="write-only",dL="read-only",pL="read-write",mL="non-filtering",fL="comparison",gL="float",yL="unfilterable-float",xL="depth",bL="sint",_L="uint",wL="2d",vL="3d",TL="2d",SL="2d-array",ML="cube",AL="3d",NL="all",EL="vertex",CL="instance",RL={CoreFeaturesAndLimits:"core-features-and-limits",DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionBCSliced3D:"texture-compression-bc-sliced-3d",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TextureCompressionASTCSliced3D:"texture-compression-astc-sliced-3d",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",Float32Blendable:"float32-blendable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups",TextureFormatsTier1:"texture-formats-tier1",TextureFormatsTier2:"texture-formats-tier2"},PL={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class BL extends zP{constructor(e,t,s){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class IL extends BP{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let DL=0;class LL extends IL{constructor(e,t){super("StorageBuffer_"+DL++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:vc.READ_WRITE,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class FL extends dS{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:ID}),this.flipYSampler=e.createSampler({minFilter:DD}),this.transferPipelines={},this.flipYPipelines={},this.mipmapVertexShaderModule=e.createShaderModule({label:"mipmapVertex",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4<f32>,\n\t@location( 0 ) vTex : vec2<f32>\n};\n\n@vertex\nfn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array< vec2<f32>, 4 >(\n\t\tvec2<f32>( -1.0, 1.0 ),\n\t\tvec2<f32>( 1.0, 1.0 ),\n\t\tvec2<f32>( -1.0, -1.0 ),\n\t\tvec2<f32>( 1.0, -1.0 )\n\t);\n\n\tvar tex = array< vec2<f32>, 4 >(\n\t\tvec2<f32>( 0.0, 0.0 ),\n\t\tvec2<f32>( 1.0, 0.0 ),\n\t\tvec2<f32>( 0.0, 1.0 ),\n\t\tvec2<f32>( 1.0, 1.0 )\n\t);\n\n\tVarys.vTex = tex[ vertexIndex ];\n\tVarys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );\n\n\treturn Varys;\n\n}\n"}),this.mipmapFragmentShaderModule=e.createShaderModule({label:"mipmapFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d<f32>;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img, imgSampler, vTex );\n\n}\n"}),this.flipYFragmentShaderModule=e.createShaderModule({label:"flipYFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d<f32>;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );\n\n}\n"})}getTransferPipeline(e){let t=this.transferPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`mipmap-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:AB,stripIndexFormat:$B},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`flipY-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:AB,stripIndexFormat:$B},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,s=0){const i=t.format,{width:r,height:n}=t.size,o=this.getTransferPipeline(i),a=this.getFlipYPipeline(i),l=this.device.createTexture({size:{width:r,height:n,depthOrArrayLayers:1},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),h=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:TL,baseArrayLayer:s}),u=l.createView({baseMipLevel:0,mipLevelCount:1,dimension:TL,baseArrayLayer:0}),c=this.device.createCommandEncoder({}),d=(e,t,s)=>{const i=e.getBindGroupLayout(0),r=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),n=c.beginRenderPass({colorAttachments:[{view:s,loadOp:VB,storeOp:FB,clearValue:[0,0,0,0]}]});n.setPipeline(e),n.setBindGroup(0,r),n.draw(4,1,0,0),n.end()};d(o,h,u),d(a,u,h),this.device.queue.submit([c.finish()]),l.destroy()}generateMipmaps(e,t,s=0,i=null){const r=this.get(e);void 0===r.layers&&(r.layers=[]);const n=r.layers[s]||this._mipmapCreateBundles(e,t,s),o=i||this.device.createCommandEncoder({label:"mipmapEncoder"});this._mipmapRunBundles(o,n),null===i&&this.device.queue.submit([o.finish()]),r.layers[s]=n}_mipmapCreateBundles(e,t,s){const i=this.getTransferPipeline(t.format),r=i.getBindGroupLayout(0);let n=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:TL,baseArrayLayer:s});const o=[];for(let a=1;a<t.mipLevelCount;a++){const l=this.device.createBindGroup({layout:r,entries:[{binding:0,resource:this.mipmapSampler},{binding:1,resource:n}]}),h=e.createView({baseMipLevel:a,mipLevelCount:1,dimension:TL,baseArrayLayer:s}),u={colorAttachments:[{view:h,loadOp:VB,storeOp:FB,clearValue:[0,0,0,0]}]},c=this.device.createRenderBundleEncoder({colorFormats:[t.format]});c.setPipeline(i),c.setBindGroup(0,l),c.draw(4,1,0,0),o.push({renderBundles:[c.finish()],passDescriptor:u}),n=h}return o}_mipmapRunBundles(e,t){const s=t.length;for(let i=0;i<s;i++){const s=t[i],r=e.beginRenderPass(s.passDescriptor);r.executeBundles(s.renderBundles),r.end()}}}const OL={[Ro]:"never",[Po]:"less",[Bo]:"equal",[Io]:"less-equal",[Do]:"greater",[Fo]:"greater-equal",[Oo]:"always",[Lo]:"not-equal"},VL=[0,1,3,2,4,5];class zL{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this._samplerCache=new Map}updateSampler(e){const t=this.backend,s=e.minFilter+"-"+e.magFilter+"-"+e.wrapS+"-"+e.wrapT+"-"+(e.wrapR||"0")+"-"+e.anisotropy+"-"+(e.compareFunction||0);let i=this._samplerCache.get(s);if(void 0===i){const r={addressModeU:this._convertAddressMode(e.wrapS),addressModeV:this._convertAddressMode(e.wrapT),addressModeW:this._convertAddressMode(e.wrapR),magFilter:this._convertFilterMode(e.magFilter),minFilter:this._convertFilterMode(e.minFilter),mipmapFilter:this._convertFilterMode(e.minFilter),maxAnisotropy:1};r.magFilter===ID&&r.minFilter===ID&&r.mipmapFilter===ID&&(r.maxAnisotropy=e.anisotropy),e.isDepthTexture&&null!==e.compareFunction&&(r.compare=OL[e.compareFunction]);i={sampler:t.device.createSampler(r),usedTimes:0},this._samplerCache.set(s,i)}const r=t.get(e);if(r.sampler!==i.sampler){if(void 0!==r.sampler){const e=this._samplerCache.get(r.samplerKey);e.usedTimes--,0===e.usedTimes&&this._samplerCache.delete(r.samplerKey)}r.samplerKey=s,r.sampler=i.sampler,i.usedTimes++}return s}createDefaultTexture(e){let t;const s=kL(e);t=e.isCubeTexture?this._getDefaultCubeTextureGPU(s):this._getDefaultTextureGPU(s),this.backend.get(e).texture=t}createTexture(e,t={}){const s=this.backend,i=s.get(e);if(i.initialized)throw new Error("WebGPUTextureUtils: Texture already initialized.");if(e.isExternalTexture)return i.texture=e.sourceTexture,void(i.initialized=!0);void 0===t.needsMipmaps&&(t.needsMipmaps=!1),void 0===t.levels&&(t.levels=1),void 0===t.depth&&(t.depth=1);const{width:r,height:n,depth:o,levels:a}=t;e.isFramebufferTexture&&(t.renderTarget?t.format=this.backend.utils.getCurrentColorFormat(t.renderTarget):t.format=this.backend.utils.getPreferredCanvasFormat());const l=this._getDimension(e),h=e.internalFormat||t.format||kL(e,s.device);i.format=h;const{samples:u,primarySamples:c,isMSAA:d}=s.utils.getTextureSampleData(e);let p=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;!0===e.isStorageTexture&&(p|=GPUTextureUsage.STORAGE_BINDING),!0!==e.isCompressedTexture&&!0!==e.isCompressedArrayTexture&&h!==fI&&(p|=GPUTextureUsage.RENDER_ATTACHMENT);const m={label:e.name,size:{width:r,height:n,depthOrArrayLayers:o},mipLevelCount:a,sampleCount:c,dimension:l,format:h,usage:p};if(void 0===h)return Yo("WebGPURenderer: Texture format not supported."),void this.createDefaultTexture(e);if(e.isCubeTexture&&(m.textureBindingViewDimension=ML),i.texture=s.device.createTexture(m),d){const e=Object.assign({},m);e.label=e.label+"-msaa",e.sampleCount=u,e.mipLevelCount=1,i.msaaTexture=s.device.createTexture(e)}i.initialized=!0,i.textureDescriptorGPU=m}destroyTexture(e,t=!1){const s=this.backend,i=s.get(e);void 0!==i.texture&&!1===t&&i.texture.destroy(),void 0!==i.msaaTexture&&i.msaaTexture.destroy(),s.delete(e)}generateMipmaps(e,t=null){const s=this.backend.get(e);if(e.isCubeTexture)for(let e=0;e<6;e++)this._generateMipmaps(s.texture,s.textureDescriptorGPU,e,t);else{const i=e.image.depth||1;for(let e=0;e<i;e++)this._generateMipmaps(s.texture,s.textureDescriptorGPU,e,t)}}getColorBuffer(){const e=this.backend,t=e.renderer.getCanvasTarget(),{width:s,height:i}=e.getDrawingBufferSize(),r=e.renderer.currentSamples,n=t.colorTexture,o=e.get(n);if(n.width===s&&n.height===i&&n.samples===r)return o.texture;let a=o.texture;return a&&a.destroy(),a=e.device.createTexture({label:"colorBuffer",size:{width:s,height:i,depthOrArrayLayers:1},sampleCount:e.utils.getSampleCount(e.renderer.currentSamples),format:e.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),n.source.width=s,n.source.height=i,n.samples=r,o.texture=a,a}getDepthBuffer(e=!0,t=!1){const s=this.backend,i=s.renderer.getCanvasTarget(),{width:r,height:n}=s.getDrawingBufferSize(),o=s.renderer.currentSamples,a=i.depthTexture;if(a.width===r&&a.height===n&&a.samples===o&&a.depth===e&&a.stencil===t)return s.get(a).texture;const l=s.get(a).texture;let h,u;if(t?(h=On,u=Pn):e&&(h=Fn,u=An),void 0!==l){if(a.image.width===r&&a.image.height===n&&a.format===h&&a.type===u&&a.samples===o)return l;this.destroyTexture(a)}return a.name="depthBuffer",a.format=h,a.type=u,a.image.width=r,a.image.height=n,a.samples=o,this.createTexture(a,{width:r,height:n}),s.get(a).texture}updateTexture(e,t){const s=this.backend.get(e),i=e.mipmaps,{textureDescriptorGPU:r}=s;if(!e.isRenderTargetTexture&&void 0!==r){if(e.isDataTexture)if(i.length>0)for(let t=0,n=i.length;t<n;t++){const n=i[t];this._copyBufferToTexture(n,s.texture,r,0,e.flipY,0,t)}else this._copyBufferToTexture(t.image,s.texture,r,0,e.flipY);else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)for(let i=0;i<t.image.depth;i++)this._copyBufferToTexture(t.image,s.texture,r,i,e.flipY,i);else if(e.isCompressedTexture||e.isCompressedArrayTexture)this._copyCompressedBufferToTexture(e.mipmaps,s.texture,r);else if(e.isCubeTexture)this._copyCubeMapToTexture(e,s.texture,r);else if(i.length>0)for(let t=0,n=i.length;t<n;t++){const n=i[t];this._copyImageToTexture(n,s.texture,r,0,e.flipY,e.premultiplyAlpha,t)}else this._copyImageToTexture(t.image,s.texture,r,0,e.flipY,e.premultiplyAlpha);s.version=e.version}}async copyTextureToBuffer(e,t,s,i,r,n){const o=this.backend.device,a=this.backend.get(e),l=a.texture,h=a.textureDescriptorGPU.format,u=this._getBytesPerTexel(h);let c=i*u;c=256*Math.ceil(c/256);const d=o.createBuffer({size:(r-1)*c+i*u,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),p=o.createCommandEncoder();p.copyTextureToBuffer({texture:l,origin:{x:t,y:s,z:n}},{buffer:d,bytesPerRow:c},{width:i,height:r});const m=this._getTypedArrayType(h);o.queue.submit([p.finish()]),await d.mapAsync(GPUMapMode.READ);return new m(d.getMappedRange())}dispose(){this._samplerCache.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const s=new Ra;s.minFilter=fn,s.magFilter=fn,this.createTexture(s,{width:1,height:1,format:e}),this.defaultTexture[e]=t=s}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultCubeTexture[e];if(void 0===t){const s=new Xh;s.minFilter=fn,s.magFilter=fn,this.createTexture(s,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=s}return this.backend.get(t).texture}_copyCubeMapToTexture(e,t,s){const i=e.images,r=e.mipmaps;for(let n=0;n<6;n++){const o=i[n],a=!0===e.flipY?VL[n]:n;o.isDataTexture?this._copyBufferToTexture(o.image,t,s,a,e.flipY):this._copyImageToTexture(o,t,s,a,e.flipY,e.premultiplyAlpha);for(let i=0;i<r.length;i++){const o=r[i].images[n];o.isDataTexture?this._copyBufferToTexture(o.image,t,s,a,e.flipY,0,i+1):this._copyImageToTexture(o,t,s,a,e.flipY,e.premultiplyAlpha,i+1)}}}_copyImageToTexture(e,t,s,i,r,n,o=0){const a=this.backend.device,l=o>0?e.width:s.size.width,h=o>0?e.height:s.size.height;try{a.queue.copyExternalImageToTexture({source:e,flipY:r},{texture:t,mipLevel:o,origin:{x:0,y:0,z:i},premultipliedAlpha:n},{width:l,height:h,depthOrArrayLayers:1})}catch(e){}}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new FL(this.backend.device)),e}_generateMipmaps(e,t,s=0,i=null){this._getPassUtils().generateMipmaps(e,t,s,i)}_flipY(e,t,s=0){this._getPassUtils().flipY(e,t,s)}_copyBufferToTexture(e,t,s,i,r,n=0,o=0){const a=this.backend.device,l=e.data,h=this._getBytesPerTexel(s.format),u=e.width*h;a.queue.writeTexture({texture:t,mipLevel:o,origin:{x:0,y:0,z:i}},l,{offset:e.width*e.height*h*n,bytesPerRow:u},{width:e.width,height:e.height,depthOrArrayLayers:1}),!0===r&&this._flipY(t,s,i)}_copyCompressedBufferToTexture(e,t,s){const i=this.backend.device,r=this._getBlockData(s.format),n=s.size.depthOrArrayLayers>1;for(let o=0;o<e.length;o++){const a=e[o],l=a.width,h=a.height,u=n?s.size.depthOrArrayLayers:1,c=Math.ceil(l/r.width)*r.byteLength,d=c*Math.ceil(h/r.height);for(let e=0;e<u;e++)i.queue.writeTexture({texture:t,mipLevel:o,origin:{x:0,y:0,z:e}},a.data,{offset:e*d,bytesPerRow:c,rowsPerImage:Math.ceil(h/r.height)},{width:Math.ceil(l/r.width)*r.width,height:Math.ceil(h/r.height)*r.height,depthOrArrayLayers:1})}}_getBlockData(e){return e===BI||e===II?{byteLength:8,width:4,height:4}:e===DI||e===LI||e===FI||e===OI?{byteLength:16,width:4,height:4}:e===VI||e===zI?{byteLength:8,width:4,height:4}:e===kI||e===UI||e===GI||e===jI||e===$I||e===WI?{byteLength:16,width:4,height:4}:e===HI||e===qI||e===XI||e===YI?{byteLength:8,width:4,height:4}:e===ZI||e===QI?{byteLength:16,width:4,height:4}:e===KI||e===JI?{byteLength:8,width:4,height:4}:e===eD||e===tD||e===sD||e===iD?{byteLength:16,width:4,height:4}:e===rD||e===nD?{byteLength:16,width:5,height:4}:e===oD||e===aD?{byteLength:16,width:5,height:5}:e===lD||e===hD?{byteLength:16,width:6,height:5}:e===uD||e===cD?{byteLength:16,width:6,height:6}:e===dD||e===pD?{byteLength:16,width:8,height:5}:e===mD||e===fD?{byteLength:16,width:8,height:6}:e===gD||e===yD?{byteLength:16,width:8,height:8}:e===xD||e===bD?{byteLength:16,width:10,height:5}:e===_D||e===wD?{byteLength:16,width:10,height:6}:e===vD||e===TD?{byteLength:16,width:10,height:8}:e===SD||e===MD?{byteLength:16,width:10,height:10}:e===AD||e===ND?{byteLength:16,width:12,height:10}:e===ED||e===CD?{byteLength:16,width:12,height:12}:void 0}_convertAddressMode(e){let t=RD;return e===dn?t=PD:e===mn&&(t=BD),t}_convertFilterMode(e){let t=ID;return e!==fn&&1004!==e&&e!==yn||(t=DD),t}_getBytesPerTexel(e){return e===WB||e===HB||e===qB||e===XB?1:e===YB||e===ZB||e===QB||e===KB||e===JB||e===eI||e===tI?2:e===sI||e===iI||e===rI||e===nI||e===oI||e===aI||e===lI||e===hI||e===uI||e===cI||e===dI||e===pI||e===mI||e===fI||e===gI||e===yI||e===RI||e===EI||e===CI||e===PI?4:e===xI||e===bI||e===_I||e===wI||e===vI||e===TI?8:e===SI||e===MI||e===AI?16:void 0}_getTypedArrayType(e){return e===qB?Uint8Array:e===XB?Int8Array:e===WB?Uint8Array:e===HB?Int8Array:e===eI?Uint8Array:e===tI?Int8Array:e===KB?Uint8Array:e===JB?Int8Array:e===cI?Uint8Array:e===dI?Int8Array:e===lI||e===hI?Uint8Array:e===uI?Int8Array:e===YB?Uint16Array:e===ZB?Int16Array:e===nI?Uint16Array:e===oI?Int16Array:e===wI?Uint16Array:e===vI?Int16Array:e===QB||e===aI||e===TI?Uint16Array:e===sI?Uint32Array:e===iI?Int32Array:e===rI?Float32Array:e===xI?Uint32Array:e===bI?Int32Array:e===_I?Float32Array:e===SI?Uint32Array:e===MI?Int32Array:e===AI?Float32Array:e===pI||e===mI?Uint8Array:e===gI||e===fI||e===yI?Uint32Array:e===RI?Float32Array:e===EI||e===CI?Uint32Array:e===PI?Float32Array:void 0}_getDimension(e){let t;return t=e.is3DTexture||e.isData3DTexture?vL:wL,t}}function kL(e,t=null){const s=e.format,i=e.type,r=e.colorSpace,n=_a.getTransfer(r);let o;if(!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture)switch(s){case jn:case $n:o=n===Eo?II:BI;break;case Wn:o=n===Eo?LI:DI;break;case Hn:o=n===Eo?OI:FI;break;case _o:o=VI;break;case wo:o=zI;break;case vo:o=kI;break;case To:o=UI;break;case bo:o=n===Eo?WI:$I;break;case Kn:case Qn:o=n===Eo?qI:HI;break;case Jn:o=n===Eo?QI:ZI;break;case eo:o=KI;break;case to:o=JI;break;case so:o=eD;break;case io:o=tD;break;case ro:o=n===Eo?iD:sD;break;case no:o=n===Eo?nD:rD;break;case oo:o=n===Eo?aD:oD;break;case ao:o=n===Eo?hD:lD;break;case lo:o=n===Eo?cD:uD;break;case ho:o=n===Eo?pD:dD;break;case uo:o=n===Eo?fD:mD;break;case co:o=n===Eo?yD:gD;break;case po:o=n===Eo?bD:xD;break;case mo:o=n===Eo?wD:_D;break;case fo:o=n===Eo?TD:vD;break;case go:o=n===Eo?MD:SD;break;case yo:o=n===Eo?ND:AD;break;case xo:o=n===Eo?CD:ED;break;case Ln:o=n===Eo?hI:lI;break;default:Zo("WebGPURenderer: Unsupported texture format.",s)}else switch(s){case Ln:switch(i){case vn:o=uI;break;case Tn:o=vI;break;case Sn:o=wI;break;case An:o=SI;break;case Mn:o=MI;break;case wn:o=n===Eo?hI:lI;break;case En:o=TI;break;case Nn:o=AI;break;default:Zo("WebGPURenderer: Unsupported texture type with RGBAFormat.",i)}break;case Dn:switch(i){case Bn:o=fI;break;case In:o=yI;break;default:Zo("WebGPURenderer: Unsupported texture type with RGBFormat.",i)}break;case Vn:switch(i){case vn:o=HB;break;case Tn:o=ZB;break;case Sn:o=YB;break;case An:o=sI;break;case Mn:o=iI;break;case wn:o=WB;break;case En:o=QB;break;case Nn:o=rI;break;default:Zo("WebGPURenderer: Unsupported texture type with RedFormat.",i)}break;case kn:switch(i){case vn:o=JB;break;case Tn:o=oI;break;case Sn:o=nI;break;case An:o=xI;break;case Mn:o=bI;break;case wn:o=KB;break;case En:o=aI;break;case Nn:o=_I;break;default:Zo("WebGPURenderer: Unsupported texture type with RGFormat.",i)}break;case Fn:switch(i){case Sn:o=NI;break;case An:o=EI;break;case Nn:o=RI;break;default:Zo("WebGPURenderer: Unsupported texture type with DepthFormat.",i)}break;case On:switch(i){case Pn:o=CI;break;case Nn:t&&!1===t.features.has(RL.Depth32FloatStencil8)&&Zo('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),o=PI;break;default:Zo("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",i)}break;case zn:switch(i){case Mn:o=iI;break;case An:o=sI;break;default:Zo("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",i)}break;case Un:switch(i){case Mn:o=bI;break;case An:o=xI;break;default:Zo("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",i)}break;case Gn:switch(i){case Mn:o=MI;break;case An:o=SI;break;default:Zo("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",i)}break;default:Zo("WebGPURenderer: Unsupported texture format.",s)}return o}const UL=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,GL=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,jL={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2<f32>":"vec2","vec2<i32>":"ivec2","vec2<u32>":"uvec2","vec2<bool>":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3<f32>":"vec3","vec3<i32>":"ivec3","vec3<u32>":"uvec3","vec3<bool>":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4<f32>":"vec4","vec4<i32>":"ivec4","vec4<u32>":"uvec4","vec4<bool>":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2<f32>":"mat2",mat2x2f:"mat2","mat3x3<f32>":"mat3",mat3x3f:"mat3","mat4x4<f32>":"mat4",mat4x4f:"mat4",sampler:"sampler",texture_1d:"texture",texture_2d:"texture",texture_2d_array:"texture",texture_multisampled_2d:"cubeTexture",texture_depth_2d:"depthTexture",texture_depth_2d_array:"depthTexture",texture_depth_multisampled_2d:"depthTexture",texture_depth_cube:"depthTexture",texture_depth_cube_array:"depthTexture",texture_3d:"texture3D",texture_cube:"cubeTexture",texture_cube_array:"cubeTexture",texture_storage_1d:"storageTexture",texture_storage_2d:"storageTexture",texture_storage_2d_array:"storageTexture",texture_storage_3d:"storageTexture"};class $L extends qR{constructor(e){const{type:t,inputs:s,name:i,inputsCode:r,blockCode:n,outputType:o}=(e=>{const t=(e=e.trim()).match(UL);if(null!==t&&4===t.length){const s=t[2],i=[];let r=null;for(;null!==(r=GL.exec(s));)i.push({name:r[1],type:r[2]});const n=[];for(let e=0;e<i.length;e++){const{name:t,type:s}=i[e];let r=s;r.startsWith("ptr")?r="pointer":(r.startsWith("texture")&&(r=s.split("<")[0]),r=jL[r]),n.push(new IR(r,t))}const o=e.substring(t[0].length),a=t[3]||"void",l=void 0!==t[1]?t[1]:"";return{type:jL[a]||a,inputs:n,name:l,inputsCode:s,blockCode:o,outputType:a}}throw new Error("FunctionNode: Function is not a WGSL code.")})(e);super(t,s,i),this.inputsCode=r,this.blockCode=n,this.outputType=o}getCode(e=this.name){const t="void"!==this.outputType?"-> "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class WL extends HR{parseFunction(e){return new $L(e)}}const HL={[vc.READ_ONLY]:"read",[vc.WRITE_ONLY]:"write",[vc.READ_WRITE]:"read_write"},qL={[dn]:"repeat",[pn]:"clamp",[mn]:"mirror"},XL={vertex:NB.VERTEX,fragment:NB.FRAGMENT,compute:NB.COMPUTE},YL={instance:!0,swizzleAssign:!1,storageBuffer:!0},ZL={"^^":"tsl_xor"},QL={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3<f32>",vec2:"vec2<f32>",ivec2:"vec2<i32>",uvec2:"vec2<u32>",bvec2:"vec2<bool>",vec3:"vec3<f32>",ivec3:"vec3<i32>",uvec3:"vec3<u32>",bvec3:"vec3<bool>",vec4:"vec4<f32>",ivec4:"vec4<i32>",uvec4:"vec4<u32>",bvec4:"vec4<bool>",mat2:"mat2x2<f32>",mat3:"mat3x3<f32>",mat4:"mat4x4<f32>"},KL={},JL={tsl_xor:new iN("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new iN("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new iN("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new iN("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new iN("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new iN("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new iN("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new iN("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new iN("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new iN("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new iN("fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }"),clampWrapping_float:new iN("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new iN("\nfn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n")},eF={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inversesqrt:"inverseSqrt",bitcast:"bitcast<f32>",floatpack_snorm_2x16:"pack2x16snorm",floatpack_unorm_2x16:"pack2x16unorm",floatpack_float16_2x16:"pack2x16float",floatunpack_snorm_2x16:"unpack2x16snorm",floatunpack_unorm_2x16:"unpack2x16unorm",floatunpack_float16_2x16:"unpack2x16float"};let tF="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(tF+="diagnostic( off, derivative_uniformity );\n");class sF extends PR{constructor(e,t){super(e,t,new WL),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}_generateTextureSample(e,t,s,i,r,n=this.shaderStage){return"fragment"===n?i?r?`textureSample( ${t}, ${t}_sampler, ${s}, ${i}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${s}, ${i} )`:r?`textureSample( ${t}, ${t}_sampler, ${s}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${s} )`:this.generateTextureSampleLevel(e,t,s,"0",i)}generateTextureSampleLevel(e,t,s,i,r,n){return!1===this.isUnfilterable(e)?n?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,n,i):this.generateTextureLod(e,t,s,r,n,i)}generateWrapFunction(e){const t=`tsl_coord_${qL[e.wrapS]}S_${qL[e.wrapT]}_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}T`;let s=KL[t];if(void 0===s){const i=[],r=e.is3DTexture||e.isData3DTexture?"vec3f":"vec2f";let n=`fn ${t}( coord : ${r} ) -> ${r} {\n\n\treturn ${r}(\n`;const o=(e,t)=>{e===dn?(i.push(JL.repeatWrapping_float),n+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===pn?(i.push(JL.clampWrapping_float),n+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===mn?(i.push(JL.mirrorWrapping_float),n+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(n+=`\t\tcoord.${t}`,Yo(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};o(e.wrapS,"x"),n+=",\n",o(e.wrapT,"y"),(e.is3DTexture||e.isData3DTexture)&&(n+=",\n",o(e.wrapR,"z")),n+="\n\t);\n\n}\n",KL[t]=s=new iN(n,i)}return s.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,s){const i=this.getDataFromNode(e,this.shaderStage,this.globalCache);void 0===i.dimensionsSnippet&&(i.dimensionsSnippet={});let r=i.dimensionsSnippet[s];if(void 0===i.dimensionsSnippet[s]){let n,o;const{primarySamples:a}=this.renderer.backend.utils.getTextureSampleData(e),l=a>1;o=e.is3DTexture||e.isData3DTexture?"vec3<u32>":"vec2<u32>",n=l||e.isStorageTexture?t:`${t}${s?`, u32( ${s} )`:""}`,r=new Xf(new Lg(`textureDimensions( ${n} )`,o)),i.dimensionsSnippet[s]=r,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(i.arrayLayerCount=new Xf(new Lg(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(i.cubeFaceCount=new Xf(new Lg("6u","u32")))}return r.build(this)}generateFilteredTexture(e,t,s,i,r="0u"){this._include("biquadraticTexture");const n=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,r);return i&&(s=`${s} + vec2<f32>(${i}) / ${o}`),`tsl_biquadraticTexture( ${t}, ${n}( ${s} ), ${o}, u32( ${r} ) )`}generateTextureLod(e,t,s,i,r,n="0u"){const o=this.generateWrapFunction(e),a=this.generateTextureDimension(e,t,n),l=e.is3DTexture||e.isData3DTexture?"vec3":"vec2";r&&(s=`${s} + ${l}<f32>(${r}) / ${l}<f32>( ${a} )`);const h=`${l}<u32>( ${o}( ${s} ) * ${l}<f32>( ${a} ) )`;return this.generateTextureLoad(e,t,h,n,i,null)}generateTextureLoad(e,t,s,i,r,n){let o;return null===i&&(i="0u"),n&&(s=`${s} + ${n}`),r?o=`textureLoad( ${t}, ${s}, ${r}, u32( ${i} ) )`:(o=`textureLoad( ${t}, ${s}, u32( ${i} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(o+=".x")),o}generateTextureStore(e,t,s,i,r){let n;return n=i?`textureStore( ${t}, ${s}, ${i}, ${r} )`:`textureStore( ${t}, ${s}, ${r} )`,n}isSampleCompare(e){return!0===e.isDepthTexture&&null!==e.compareFunction}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&!0===e.isDataTexture&&e.type===Nn||!1===this.isSampleCompare(e)&&e.minFilter===fn&&e.magFilter===fn||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,s,i,r,n=this.shaderStage){let o=null;return o=this.isUnfilterable(e)?this.generateTextureLod(e,t,s,i,r,"0",n):this._generateTextureSample(e,t,s,i,r,n),o}generateTextureGrad(e,t,s,i,r,n,o=this.shaderStage){if("fragment"===o)return n?`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]}, ${n} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]} )`;Zo(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${o} shader.`)}generateTextureCompare(e,t,s,i,r,n,o=this.shaderStage){if("fragment"===o)return!0===e.isDepthTexture&&!0===e.isArrayTexture?n?`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${r}, ${i}, ${n} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${r}, ${i} )`:n?`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${i} )`;Zo(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${o} shader.`)}generateTextureLevel(e,t,s,i,r,n){return!1===this.isUnfilterable(e)?n?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,n,i):this.generateTextureLod(e,t,s,r,n,i)}generateTextureBias(e,t,s,i,r,n,o=this.shaderStage){if("fragment"===o)return n?`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i} )`;Zo(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${o} shader.`)}getPropertyName(e,t=this.shaderStage){if(!0===e.isNodeVarying&&!0===e.needsInterpolation){if("vertex"===t)return`varyings.${e.name}`}else if(!0===e.isNodeUniform){const t=e.name,s=e.type;return"texture"===s||"cubeTexture"===s||"cubeDepthTexture"===s||"storageTexture"===s||"texture3D"===s?t:"buffer"===s||"storageBuffer"===s||"indirectStorageBuffer"===s?this.isCustomStruct(e)?t:t+".value":e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=ZL[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?!0===e.isAtomic?(Yo("WebGPURenderer: Atomic operations are only supported in compute shaders."),vc.READ_WRITE):vc.READ_ONLY:e.access}getStorageAccess(e,t){return HL[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,s,i=null){const r=super.getUniformFromNode(e,t,s,i),n=this.getDataFromNode(e,s,this.globalCache);if(void 0===n.uniformGPU){let o;const a=e.groupNode,l=a.name,h=this.getBindGroupArray(l,s);if("texture"===t||"cubeTexture"===t||"cubeDepthTexture"===t||"storageTexture"===t||"texture3D"===t){let i=null;const n=this.getNodeAccess(e,s);if("texture"===t||"storageTexture"===t?i=!0===e.value.is3DTexture?new $P(r.name,r.node,a,n):new GP(r.name,r.node,a,n):"cubeTexture"===t||"cubeDepthTexture"===t?i=new jP(r.name,r.node,a,n):"texture3D"===t&&(i=new $P(r.name,r.node,a,n)),i.store=!0===e.isStorageTextureNode,i.mipLevel=i.store?e.mipLevel:0,i.setVisibility(XL[s]),!1===this.isUnfilterable(e.value)&&!1===i.store){const e=new BL(`${r.name}_sampler`,r.node,a);e.setVisibility(XL[s]),h.push(e,i),o=[e,i]}else h.push(i),o=[i]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const n=this.getSharedDataFromNode(e);let l=n.buffer;if(void 0===l){l=new("buffer"===t?LP:LL)(e,a),n.buffer=l}l.setVisibility(l.getVisibility()|XL[s]),h.push(l),o=l,r.name=i||"NodeBuffer_"+r.id}else{const e=this.uniformGroups[s]||(this.uniformGroups[s]={});let i=e[l];void 0===i&&(i=new VP(l,a),i.setVisibility(XL[s]),e[l]=i,h.push(i)),o=this.getNodeUniform(r,t),i.addUniform(o)}n.uniformGPU=o}return r}getBuiltin(e,t,s,i=this.shaderStage){const r=this.builtins[i]||(this.builtins[i]=new Map);return!1===r.has(e)&&r.set(e,{name:e,property:t,type:s}),t}hasBuiltin(e,t=this.shaderStage){return void 0!==this.builtins[t]&&this.builtins[t].has(e)}getVertexIndex(){return"vertex"===this.shaderStage?this.getBuiltin("vertex_index","vertexIndex","u32","attribute"):"vertexIndex"}buildFunctionCode(e){const t=e.layout,s=this.flowShaderNode(e),i=[];for(const e of t.inputs)i.push(e.name+" : "+this.getType(e.type));let r=`fn ${t.name}( ${i.join(", ")} ) -> ${this.getType(t.type)} {\n${s.vars}\n${s.code}\n`;return s.result&&(r+=`\treturn ${s.result};\n`),r+="\n}\n",r}getInstanceIndex(){return"vertex"===this.shaderStage?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}getInvocationLocalIndex(){return this.getBuiltin("local_invocation_index","invocationLocalIndex","u32","attribute")}getSubgroupSize(){return this.enableSubGroups(),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute")}getInvocationSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_invocation_id","invocationSubgroupIndex","u32","attribute")}getSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_id","subgroupIndex","u32","attribute")}getDrawIndex(){return null}getFrontFacing(){return this.getBuiltin("front_facing","isFront","bool")}getFragCoord(){return this.getBuiltin("position","fragCoord","vec4<f32>")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],s=this.directives[e];if(void 0!==s)for(const e of s)t.push(`enable ${e};`);return t.join("\n")}enableSubGroups(){this.enableDirective("subgroups")}enableSubgroupsF16(){this.enableDirective("subgroups-f16")}enableClipDistances(){this.enableDirective("clip_distances")}enableShaderF16(){this.enableDirective("f16")}enableDualSourceBlending(){this.enableDirective("dual_source_blending")}enableHardwareClipping(e){this.enableClipDistances(),this.getBuiltin("clip_distances","hw_clip_distances",`array<f32, ${e} >`,"vertex")}getBuiltins(e){const t=[],s=this.builtins[e];if(void 0!==s)for(const{name:e,property:i,type:r}of s.values())t.push(`@builtin( ${e} ) ${i} : ${r}`);return t.join(",\n\t")}getScopedArray(e,t,s,i){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:s,bufferCount:i}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:s,bufferType:i,bufferCount:r}of this.scopedArrays.values()){const n=this.getType(i);t.push(`var<${s}> ${e}: array< ${n}, ${r} >;`)}return t.join("\n")}getAttributes(e){const t=[];if("compute"===e&&(this.getBuiltin("global_invocation_id","globalId","vec3<u32>","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3<u32>","attribute"),this.getBuiltin("local_invocation_id","localId","vec3<u32>","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3<u32>","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",e),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),"vertex"===e||"compute"===e){const e=this.getBuiltins("attribute");e&&t.push(e);const s=this.getAttributesArray();for(let e=0,i=s.length;e<i;e++){const i=s[e],r=i.name,n=this.getType(i.type);t.push(`@location( ${e} ) ${r} : ${n}`)}}return t.join(",\n\t")}getStructMembers(e){const t=[];for(const s of e.members){const i=e.output?"@location( "+s.index+" ) ":"";let r=this.getType(s.type);s.atomic&&(r="atomic< "+r+" >"),t.push(`\t${i+s.name} : ${r}`)}return e.output&&t.push(`\t${this.getBuiltins("output")}`),t.join(",\n")}getStructs(e){let t="";const s=this.structs[e];if(s.length>0){const e=[];for(const t of s){let s=`struct ${t.name} {\n`;s+=this.getStructMembers(t),s+="\n};",e.push(s)}t="\n"+e.join("\n\n")+"\n"}return t}getVar(e,t,s=null){let i=`var ${t} : `;return i+=null!==s?this.generateArrayDeclaration(e,s):this.getType(e),i}getVars(e){const t=[],s=this.vars[e];if(void 0!==s)for(const e of s)t.push(`\t${this.getVar(e.type,e.name,e.count)};`);return`\n${t.join("\n")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","Vertex","vec4<f32>","vertex"),"vertex"===e||"fragment"===e){const s=this.varyings,i=this.vars[e];for(let r=0;r<s.length;r++){const n=s[r];if(n.needsInterpolation){let e=`@location( ${r} )`;if(n.interpolationType){const t=null!==n.interpolationSampling?`, ${n.interpolationSampling} )`:" )";e+=` @interpolate( ${n.interpolationType}${t}`}else/^(int|uint|ivec|uvec)/.test(n.type)&&(e+=` @interpolate( ${this.renderer.backend.compatibilityMode?"flat, either":"flat"} )`);t.push(`${e} ${n.name} : ${this.getType(n.type)}`)}else"vertex"===e&&!1===i.includes(n)&&i.push(n)}}const s=this.getBuiltins(e);s&&t.push(s);const i=t.join(",\n\t");return"vertex"===e?this._getWGSLStruct("VaryingsStruct","\t"+i):i}isCustomStruct(e){const t=e.value,s=e.node,i=(t.isBufferAttribute||t.isInstancedBufferAttribute)&&null!==s.structTypeNode,r=s.value&&s.value.array&&"number"==typeof s.value.itemSize&&s.value.array.length>s.value.itemSize;return i&&!r}getUniforms(e){const t=this.uniforms[e],s=[],i=[],r=[],n={};for(const r of t){const t=r.groupNode.name,o=this.bindingsIndexes[t];if("texture"===r.type||"cubeTexture"===r.type||"cubeDepthTexture"===r.type||"storageTexture"===r.type||"texture3D"===r.type){const t=r.node.value;let i;!1===this.isUnfilterable(t)&&!0!==r.node.isStorageTextureNode&&(this.isSampleCompare(t)?s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${r.name}_sampler : sampler_comparison;`):s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${r.name}_sampler : sampler;`));let n="";const{primarySamples:a}=this.renderer.backend.utils.getTextureSampleData(t);if(a>1&&(n="_multisampled"),!0===t.isCubeTexture&&!0===t.isDepthTexture)i="texture_depth_cube";else if(!0===t.isCubeTexture)i="texture_cube<f32>";else if(!0===t.isDepthTexture)i=this.renderer.backend.compatibilityMode&&null===t.compareFunction?`texture${n}_2d<f32>`:`texture_depth${n}_2d${!0===t.isArrayTexture?"_array":""}`;else if(!0===r.node.isStorageTextureNode){const s=kL(t),n=this.getStorageAccess(r.node,e),o=r.node.value.is3DTexture,a=r.node.value.isArrayTexture;i=`texture_storage_${o?"3d":"2d"+(a?"_array":"")}<${s}, ${n}>`}else if(!0===t.isArrayTexture||!0===t.isDataArrayTexture||!0===t.isCompressedArrayTexture)i="texture_2d_array<f32>";else if(!0===t.is3DTexture||!0===t.isData3DTexture)i="texture_3d<f32>";else{i=`texture${n}_2d<${this.getComponentTypeFromTexture(t).charAt(0)}32>`}s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${r.name} : ${i};`)}else if("buffer"===r.type||"storageBuffer"===r.type||"indirectStorageBuffer"===r.type){const t=r.node,s=this.getType(t.getNodeType(this)),n=t.bufferCount,a=n>0&&"buffer"===r.type?", "+n:"",l=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(r))i.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var<${l}> ${r.name} : ${s};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${s}>`:`${s}`}${a} >`;i.push(this._getWGSLStructBinding(r.name,e,l,o.binding++,o.group))}}else{const e=this.getType(this.getVectorType(r.type)),t=r.groupNode.name;(n[t]||(n[t]={index:o.binding++,id:o.group,snippets:[]})).snippets.push(`\t${r.name} : ${e}`)}}for(const e in n){const t=n[e];r.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}return[...s,...i,...r].join("\n")}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const s=e[t];s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.structs=this.getStructs(t),s.vars=this.getVars(t),s.codes=this.getCodes(t),s.directives=this.getDirectives(t),s.scopedArrays=this.getScopedArrays(t);let i="// code\n\n";i+=this.flowCode[t];const r=this.flowNodes[t],n=r[r.length-1],o=n.outputNode,a=void 0!==o&&!0===o.isOutputStructNode;for(const e of r){const r=this.getFlowData(e),l=e.name;if(l&&(i.length>0&&(i+="\n"),i+=`\t// flow -> ${l}\n`),i+=`${r.code}\n\t`,e===n&&"compute"!==t)if(i+="// result\n\n\t","vertex"===t)i+=`varyings.Vertex = ${r.result};`;else if("fragment"===t)if(a)s.returnType=o.getNodeType(this),s.structs+="var<private> output : "+s.returnType+";",i+=`return ${r.result};`;else{let e="\t@location(0) color: vec4<f32>";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),s.returnType="OutputStruct",s.structs+=this._getWGSLStruct("OutputStruct",e),s.structs+="\nvar<private> output : OutputStruct;",i+=`output.color = ${r.result};\n\n\treturn output;`}}s.flow=i}if(this.shaderStage=null,null!==this.material)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{const t=this.object.workgroupSize;this.computeShader=this._getWGSLComputeCode(e.compute,t)}}getMethod(e,t=null){let s;return null!==t&&(s=this._getWGSLMethod(e+"_"+t)),void 0===s&&(s=this._getWGSLMethod(e)),s||e}getBitcastMethod(e){return`bitcast<${this.getType(e)}>`}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,s){return`select( ${s}, ${t}, ${e} )`}getType(e){return QL[e]||e}isAvailable(e){let t=YL[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),YL[e]=t),t}_getWGSLMethod(e){return void 0!==JL[e]&&this._include(e),eF[e]}_include(e){const t=JL[e];return t.build(this),this.addInclude(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar<private> varyings : VaryingsStruct;\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${tF}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){const[s,i,r]=t;return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar<private> instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${s}, ${i}, ${r} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = globalId.x\n\t\t+ globalId.y * ( ${s} * numWorkgroups.x )\n\t\t+ globalId.z * ( ${s} * numWorkgroups.x ) * ( ${i} * numWorkgroups.y );\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,s,i=0,r=0){const n=e+"Struct";return`${this._getWGSLStruct(n,t)}\n@binding( ${i} ) @group( ${r} )\nvar<${s}> ${e} : ${n};`}}class iF{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=CI:e.depth&&(t=EI),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){const e=this.backend.renderer,s=e.getRenderTarget();t=s?s.samples:e.currentSamples}else e.renderTarget&&(t=e.renderTarget.samples);t=t||1;const s=t>1&&null!==e.renderTarget&&!0!==e.isDepthTexture&&!0!==e.isFramebufferTexture;return{samples:t,primarySamples:s?1:t,isMSAA:s}}getCurrentColorFormat(e){let t;return t=null!==e.textures?this.getTextureFormatGPU(e.textures[0]):this.getPreferredCanvasFormat(),t}getCurrentColorFormats(e){return null!==e.textures?e.textures.map(e=>this.getTextureFormatGPU(e)):[this.getPreferredCanvasFormat()]}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?vB:e.isLineSegments||e.isMesh&&!0===t.wireframe?TB:e.isLine?SB:e.isMesh?MB:void 0}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.currentSamples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===wn)return pI;if(e===En)return TI;throw new Error("Unsupported output buffer type.")}}const rF=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]);"undefined"!=typeof Float16Array&&rF.set(Float16Array,["float16"]);const nF=new Map([[fh,["float16"]]]),oF=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class aF{constructor(e){this.backend=e}createAttribute(e,t){const s=this._getBufferAttribute(e),i=this.backend,r=i.get(s);let n=r.buffer;if(void 0===n){const o=i.device;let a=s.array;if(!1===e.normalized)if(a.constructor===Int16Array||a.constructor===Int8Array)a=new Int32Array(a);else if((a.constructor===Uint16Array||a.constructor===Uint8Array)&&(a=new Uint32Array(a),t&GPUBufferUsage.INDEX))for(let e=0;e<a.length;e++)65535===a[e]&&(a[e]=4294967295);if(s.array=a,(s.isStorageBufferAttribute||s.isStorageInstancedBufferAttribute)&&3===s.itemSize){a=new a.constructor(4*s.count);for(let e=0;e<s.count;e++)a.set(s.array.subarray(3*e,3*e+3),4*e);s.itemSize=4,s.array=a,r._force3to4BytesAlignment=!0}const l=a.byteLength,h=l+(4-l%4)%4;n=o.createBuffer({label:s.name,size:h,usage:t,mappedAtCreation:!0}),new a.constructor(n.getMappedRange()).set(a),n.unmap(),r.buffer=n}}updateAttribute(e){const t=this._getBufferAttribute(e),s=this.backend,i=s.device,r=s.get(t),n=s.get(t).buffer;let o=t.array;if(!0===r._force3to4BytesAlignment){o=new o.constructor(4*t.count);for(let e=0;e<t.count;e++)o.set(t.array.subarray(3*e,3*e+3),4*e);t.array=o}const a=t.updateRanges;if(0===a.length)i.queue.writeBuffer(n,0,o,0);else{const e=Wo(o),s=e?1:o.BYTES_PER_ELEMENT;for(let t=0,l=a.length;t<l;t++){const l=a[t];let h,u;if(!0===r._force3to4BytesAlignment){h=4*Math.floor(l.start/3)*s,u=4*Math.ceil(l.count/3)*s}else h=l.start*s,u=l.count*s;const c=h*(e?o.BYTES_PER_ELEMENT:1);i.queue.writeBuffer(n,c,o,h,u)}t.clearUpdateRanges()}}createShaderVertexBuffers(e){const t=e.getAttributes(),s=new Map;for(let e=0;e<t.length;e++){const i=t[e],r=i.array.BYTES_PER_ELEMENT,n=this._getBufferAttribute(i);let o=s.get(n);if(void 0===o){let e,t;!0===i.isInterleavedBufferAttribute?(e=i.data.stride*r,t=i.data.isInstancedInterleavedBuffer?CL:EL):(e=i.itemSize*r,t=i.isInstancedBufferAttribute?CL:EL),!1!==i.normalized||i.array.constructor!==Int16Array&&i.array.constructor!==Uint16Array||(e=4),o={arrayStride:e,attributes:[],stepMode:t},s.set(n,o)}const a=this._getVertexFormat(i),l=!0===i.isInterleavedBufferAttribute?i.offset*r:0;o.attributes.push({shaderLocation:e,offset:l,format:a})}return Array.from(s.values())}destroyAttribute(e){const t=this.backend;t.get(this._getBufferAttribute(e)).buffer.destroy(),t.delete(e)}async getArrayBufferAsync(e){const t=this.backend,s=t.device,i=t.get(this._getBufferAttribute(e)).buffer,r=i.size,n=s.createBuffer({label:`${e.name}_readback`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),o=s.createCommandEncoder({label:`readback_encoder_${e.name}`});o.copyBufferToBuffer(i,0,n,0,r);const a=o.finish();s.queue.submit([a]),await n.mapAsync(GPUMapMode.READ);const l=n.getMappedRange(),h=new e.array.constructor(l.slice(0));return n.unmap(),h.buffer}_getVertexFormat(e){const{itemSize:t,normalized:s}=e,i=e.array.constructor,r=e.constructor;let n;if(1===t)n=oF.get(i);else{const e=(nF.get(r)||rF.get(i))[s?1:0];if(e){const s=i.BYTES_PER_ELEMENT*t,r=4*Math.floor((s+3)/4)/i.BYTES_PER_ELEMENT;if(r%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");n=`${e}x${r}`}}return n||Zo("WebGPUAttributeUtils: Vertex format not supported yet."),n}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class lF{constructor(e){this.layoutGPU=e,this.usedTimes=0}}class hF{constructor(e){this.backend=e,this._bindGroupLayoutCache=new Map}createBindingsLayout(e){const t=this.backend,s=t.device,i=t.get(e);if(i.layout)return i.layout.layoutGPU;const r=this._createLayoutEntries(e),n=JSON.stringify(r);let o=this._bindGroupLayoutCache.get(n);return void 0===o&&(o=new lF(s.createBindGroupLayout({entries:r})),this._bindGroupLayoutCache.set(n,o)),o.usedTimes++,i.layout=o,i.layoutKey=n,o.layoutGPU}createBindings(e,t,s,i=0){const{backend:r}=this,n=r.get(e),o=this.createBindingsLayout(e);let a;s>0&&(void 0===n.groups&&(n.groups=[],n.versions=[]),n.versions[s]===i&&(a=n.groups[s])),void 0===a&&(a=this.createBindGroup(e,o),s>0&&(n.groups[s]=a,n.versions[s]=i)),n.group=a}updateBinding(e){const t=this.backend,s=t.device,i=e.buffer,r=t.get(e).buffer,n=e.updateRanges;if(0===n.length)s.queue.writeBuffer(r,0,i,0);else{const t=Wo(i),o=t?1:i.BYTES_PER_ELEMENT;for(let e=0,a=n.length;e<a;e++){const a=n[e],l=a.start*o,h=a.count*o,u=l*(t?i.BYTES_PER_ELEMENT:1);s.queue.writeBuffer(r,u,i,l,h)}e.clearUpdateRanges()}}createBindGroupIndex(e,t){const s=this.backend.device,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,r=e[0],n=s.createBuffer({label:"bindingCameraIndex_"+r,size:16,usage:i});s.queue.writeBuffer(n,0,e,0);const o=[{binding:0,resource:{buffer:n}}];return s.createBindGroup({label:"bindGroupCameraIndex_"+r,layout:t,entries:o})}createBindGroup(e,t){const s=this.backend,i=s.device;let r=0;const n=[];for(const t of e.bindings){if(t.isUniformBuffer){const e=s.get(t);if(void 0===e.buffer){const s=t.byteLength,r=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,n=[];t.visibility&NB.VERTEX&&n.push("vertex"),t.visibility&NB.FRAGMENT&&n.push("fragment"),t.visibility&NB.COMPUTE&&n.push("compute");const o=`(${n.join(",")})`,a=i.createBuffer({label:`bindingBuffer${t.id}_${t.name}_${o}`,size:s,usage:r});e.buffer=a}n.push({binding:r,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=s.get(t);if(void 0===e.buffer){const i=t.attribute;e.buffer=s.get(i).buffer}n.push({binding:r,resource:{buffer:e.buffer}})}else if(t.isSampledTexture){const e=s.get(t.texture);let o;if(void 0!==e.externalTexture)o=i.importExternalTexture({source:e.externalTexture});else{const s=t.store?1:e.texture.mipLevelCount,i=t.store?t.mipLevel:0;let r=`view-${e.texture.width}-${e.texture.height}`;if(e.texture.depthOrArrayLayers>1&&(r+=`-${e.texture.depthOrArrayLayers}`),r+=`-${s}-${i}`,o=e[r],void 0===o){const n=NL;let a;a=t.isSampledCubeTexture?ML:t.isSampledTexture3D?AL:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?SL:TL,o=e[r]=e.texture.createView({aspect:n,dimension:a,mipLevelCount:s,baseMipLevel:i})}}n.push({binding:r,resource:o})}else if(t.isSampler){const e=s.get(t.texture);n.push({binding:r,resource:e.sampler})}r++}return i.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:n})}_createLayoutEntries(e){const t=[];let s=0;for(const i of e.bindings){const e=this.backend,r={binding:s,visibility:i.visibility};if(i.isUniformBuffer||i.isStorageBuffer){const e={};i.isStorageBuffer&&(i.visibility&NB.COMPUTE&&(i.access===vc.READ_WRITE||i.access===vc.WRITE_ONLY)?e.type=hL:e.type=uL),r.buffer=e}else if(i.isSampledTexture&&i.store){const e={};e.format=this.backend.get(i.texture).texture.format;const t=i.access;e.access=t===vc.READ_WRITE?pL:t===vc.WRITE_ONLY?cL:dL,i.texture.isArrayTexture?e.viewDimension=SL:i.texture.is3DTexture&&(e.viewDimension=AL),r.storageTexture=e}else if(i.isSampledTexture){const t={},{primarySamples:s}=e.utils.getTextureSampleData(i.texture);if(s>1&&(t.multisampled=!0,i.texture.isDepthTexture||(t.sampleType=yL)),i.texture.isDepthTexture)e.compatibilityMode&&null===i.texture.compareFunction?t.sampleType=yL:t.sampleType=xL;else if(i.texture.isDataTexture||i.texture.isDataArrayTexture||i.texture.isData3DTexture){const e=i.texture.type;e===Mn?t.sampleType=bL:e===An?t.sampleType=_L:e===Nn&&(this.backend.hasFeature("float32-filterable")?t.sampleType=gL:t.sampleType=yL)}i.isSampledCubeTexture?t.viewDimension=ML:i.texture.isArrayTexture||i.texture.isDataArrayTexture||i.texture.isCompressedArrayTexture?t.viewDimension=SL:i.isSampledTexture3D&&(t.viewDimension=AL),r.texture=t}else if(i.isSampler){const t={};i.texture.isDepthTexture&&(null!==i.texture.compareFunction?t.type=fL:e.compatibilityMode&&(t.type=mL)),r.sampler=t}else Zo(`WebGPUBindingUtils: Unsupported binding "${i}".`);t.push(r),s++}return t}deleteBindGroupData(e){const{backend:t}=this,s=t.get(e);s.layout&&(s.layout.usedTimes--,0===s.layout.usedTimes&&this._bindGroupLayoutCache.delete(s.layoutKey),s.layout=void 0,s.layoutKey=void 0)}dispose(){this._bindGroupLayoutCache.clear()}}class uF{constructor(e){this.backend=e,this._activePipelines=new WeakMap}setPipeline(e,t){this._activePipelines.get(e)!==t&&(e.setPipeline(t),this._activePipelines.set(e,t))}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:s,material:i,geometry:r,pipeline:n}=e,{vertexProgram:o,fragmentProgram:a}=n,l=this.backend,h=l.device,u=l.utils,c=l.get(n),d=[];for(const t of e.getBindings()){const e=l.get(t),{layoutGPU:s}=e.layout;d.push(s)}const p=l.attributeUtils.createShaderVertexBuffers(e);let m;0===i.blending||1===i.blending&&!1===i.transparent||(m=this._getBlending(i));let f={};!0===i.stencilWrite&&(f={compare:this._getStencilCompare(i),failOp:this._getStencilOperation(i.stencilFail),depthFailOp:this._getStencilOperation(i.stencilZFail),passOp:this._getStencilOperation(i.stencilZPass)});const g=this._getColorWriteMask(i),y=[];if(null!==e.context.textures){const t=e.context.textures;for(let e=0;e<t.length;e++){const s=u.getTextureFormatGPU(t[e]);0===e?y.push({format:s,blend:m,writeMask:g}):y.push({format:s,writeMask:g})}}else{const t=u.getCurrentColorFormat(e.context);y.push({format:t,blend:m,writeMask:g})}const x=l.get(o).module,b=l.get(a).module,_=this._getPrimitiveState(s,r,i),w=this._getDepthCompare(i),v=u.getCurrentDepthStencilFormat(e.context),T=this._getSampleCount(e.context),S={label:`renderPipeline_${i.name||i.type}_${i.id}`,vertex:Object.assign({},x,{buffers:p}),fragment:Object.assign({},b,{targets:y}),primitive:_,multisample:{count:T,alphaToCoverageEnabled:i.alphaToCoverage&&T>1},layout:h.createPipelineLayout({bindGroupLayouts:d})},M={},A=e.context.depth,N=e.context.stencil;if(!0!==A&&!0!==N||(!0===A&&(M.format=v,M.depthWriteEnabled=i.depthWrite,M.depthCompare=w),!0===N&&(M.stencilFront=f,M.stencilBack={},M.stencilReadMask=i.stencilFuncMask,M.stencilWriteMask=i.stencilWriteMask),!0===i.polygonOffset&&(M.depthBias=i.polygonOffsetUnits,M.depthBiasSlopeScale=i.polygonOffsetFactor,M.depthBiasClamp=0),S.depthStencil=M),h.pushErrorScope("validation"),null===t)c.pipeline=h.createRenderPipeline(S),h.popErrorScope().then(e=>{null!==e&&(c.error=!0,Zo(e.message))});else{const e=new Promise(async e=>{try{c.pipeline=await h.createRenderPipelineAsync(S)}catch(e){}const t=await h.popErrorScope();null!==t&&(c.error=!0,Zo(t.message)),e()});t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const s=this.backend,{utils:i,device:r}=s,n=i.getCurrentDepthStencilFormat(e),o={label:t,colorFormats:i.getCurrentColorFormats(e),depthStencilFormat:n,sampleCount:this._getSampleCount(e)};return r.createRenderBundleEncoder(o)}createComputePipeline(e,t){const s=this.backend,i=s.device,r=s.get(e.computeProgram).module,n=s.get(e),o=[];for(const e of t){const t=s.get(e),{layoutGPU:i}=t.layout;o.push(i)}n.pipeline=i.createComputePipeline({compute:r,layout:i.createPipelineLayout({bindGroupLayouts:o})})}_getBlending(e){let t,s;const i=e.blending,r=e.blendSrc,n=e.blendDst,o=e.blendEquation;if(5===i){const i=null!==e.blendSrcAlpha?e.blendSrcAlpha:r,a=null!==e.blendDstAlpha?e.blendDstAlpha:n,l=null!==e.blendEquationAlpha?e.blendEquationAlpha:o;t={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(n),operation:this._getBlendOperation(o)},s={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(a),operation:this._getBlendOperation(l)}}else{const r=(e,i,r,n)=>{t={srcFactor:e,dstFactor:i,operation:XD},s={srcFactor:r,dstFactor:n,operation:XD}};if(e.premultipliedAlpha)switch(i){case 1:r(FD,kD,FD,kD);break;case 2:r(FD,FD,FD,FD);break;case 3:r(LD,VD,LD,FD);break;case 4:r(UD,kD,LD,FD)}else switch(i){case 1:r(zD,kD,FD,kD);break;case 2:r(zD,FD,FD,FD);break;case 3:Zo("WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:Zo("WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true")}}if(void 0!==t&&void 0!==s)return{color:t,alpha:s};Zo("WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case Kr:t=LD;break;case 201:t=FD;break;case 202:t=OD;break;case 203:t=VD;break;case sn:t=zD;break;case rn:t=kD;break;case 208:t=UD;break;case 209:t=GD;break;case 206:t=jD;break;case 207:t=$D;break;case 210:t=WD;break;case 211:t=HD;break;case 212:t=qD;break;default:Zo("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const s=e.stencilFunc;switch(s){case 512:t=EB;break;case 519:t=LB;break;case 513:t=CB;break;case 515:t=PB;break;case 514:t=RB;break;case 518:t=DB;break;case 516:t=BB;break;case 517:t=IB;break;default:Zo("WebGPURenderer: Invalid stencil function.",s)}return t}_getStencilOperation(e){let t;switch(e){case Co:t=tL;break;case 0:t=sL;break;case 7681:t=iL;break;case 5386:t=rL;break;case 7682:t=nL;break;case 7683:t=oL;break;case 34055:t=aL;break;case 34056:t=lL;break;default:Zo("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case Yr:t=XD;break;case 101:t=YD;break;case 102:t=ZD;break;case 103:t=QD;break;case 104:t=KD;break;default:Zo("WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,s){const i={},r=this.backend.utils;i.topology=r.getPrimitiveTopology(e,s),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?jB:$B);let n=1===s.side;return e.isMesh&&e.matrixWorld.determinant()<0&&(n=!n),i.frontFace=!0===n?kB:zB,i.cullMode=2===s.side?UB:GB,i}_getColorWriteMask(e){return!0===e.colorWrite?eL:JD}_getDepthCompare(e){let t;if(!1===e.depthTest)t=LB;else{const s=e.depthFunc;switch(s){case 0:t=EB;break;case 1:t=LB;break;case 2:t=CB;break;case 3:t=PB;break;case 4:t=RB;break;case 5:t=DB;break;case 6:t=BB;break;case 7:t=IB;break;default:Zo("WebGPUPipelineUtils: Invalid depth function.",s)}}return t}}class cF extends bB{constructor(e,t,s=2048){super(s),this.device=e,this.type=t,this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxQueries,label:`queryset_global_timestamp_${t}`});const i=8*this.maxQueries;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return Qo(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||0===this.currentQueryIndex||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if("unmapped"!==this.resultBuffer.mapState)return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,s=8*t;this.currentQueryIndex=0,this.queryOffsets.clear();const i=this.device.createCommandEncoder();i.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),i.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,s);const r=i.finish();if(this.device.queue.submit([r]),"unmapped"!==this.resultBuffer.mapState)return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,s),this.isDisposed)return"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue;const n=new BigUint64Array(this.resultBuffer.getMappedRange(0,s)),o={},a=[];for(const[t,s]of e){const e=t.match(/^(.*):f(\d+)$/),i=parseInt(e[2]);!1===a.includes(i)&&a.push(i),void 0===o[i]&&(o[i]=0);const r=n[s],l=n[s+1],h=Number(l-r)/1e6;this.timestamps.set(t,h),o[i]+=h}const l=o[a[a.length-1]];return this.resultBuffer.unmap(),this.lastValue=l,this.frames=a,l}catch(e){return Zo("Error resolving queries:",e),"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){Zo("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){Zo("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}class dF extends tB{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.compatibilityMode=void 0!==e.compatibilityMode&&e.compatibilityMode,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.compatibilityMode=this.parameters.compatibilityMode,this.device=null,this.defaultRenderPassdescriptor=null,this.utils=new iF(this),this.attributeUtils=new aF(this),this.bindingUtils=new hF(this),this.pipelineUtils=new uF(this),this.textureUtils=new zL(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let s;if(void 0===t.device){const e={powerPreference:t.powerPreference,featureLevel:t.compatibilityMode?"compatibility":void 0},i="undefined"!=typeof navigator?await navigator.gpu.requestAdapter(e):null;if(null===i)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const r=Object.values(RL),n=[];for(const e of r)i.features.has(e)&&n.push(e);const o={requiredFeatures:n,requiredLimits:t.requiredLimits};s=await i.requestDevice(o)}else s=t.device;s.lost.then(t=>{if("destroyed"===t.reason)return;const s={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(s)}),this.device=s,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(RL.TimestampQuery),this.updateSize()}get context(){const e=this.renderer.getCanvasTarget(),t=this.get(e);let s=t.context;if(void 0===s){const i=this.parameters;s=!0===e.isDefaultCanvasTarget&&void 0!==i.context?i.context:e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${Xr} webgpu`);const r=i.alpha?"premultiplied":"opaque",n=i.outputType===En?"extended":"standard";s.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:r,toneMapping:{mode:n}}),t.context=s}return s}get coordinateSystem(){return Uo}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){const e=this.renderer,t=e.getCanvasTarget(),s=this.get(t),i=e.currentSamples;let r=s.descriptor;if(void 0===r||s.samples!==i){r={colorAttachments:[{view:null}]},!0!==e.depth&&!0!==e.stencil||(r.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView()});const t=r.colorAttachments[0];i>0?t.view=this.textureUtils.getColorBuffer().createView():t.resolveTarget=void 0,s.descriptor=r,s.samples=i}const n=r.colorAttachments[0];return i>0?n.resolveTarget=this.context.getCurrentTexture().createView():n.view=this.context.getCurrentTexture().createView(),r}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const s=e.renderTarget,i=this.get(s);let r=i.descriptors;void 0!==r&&i.width===s.width&&i.height===s.height&&i.samples===s.samples||(r={},i.descriptors=r);const n=e.getCacheKey();let o=r[n];if(void 0===o){const t=e.textures,a=[];let l;const h=this._isRenderCameraDepthArray(e);for(let i=0;i<t.length;i++){const r=this.get(t[i]),n={label:`colorAttachment_${i}`,baseMipLevel:e.activeMipmapLevel,mipLevelCount:1,baseArrayLayer:e.activeCubeFace,arrayLayerCount:1,dimension:TL};if(s.isRenderTarget3D)l=e.activeCubeFace,n.baseArrayLayer=0,n.dimension=AL,n.depthOrArrayLayers=t[i].image.depth;else if(s.isRenderTarget&&t[i].image.depth>1)if(!0===h){const t=e.camera.cameras;for(let e=0;e<t.length;e++){const t={...n,baseArrayLayer:e,arrayLayerCount:1,dimension:TL},s=r.texture.createView(t);a.push({view:s,resolveTarget:void 0,depthSlice:void 0})}}else n.dimension=SL,n.depthOrArrayLayers=t[i].image.depth;if(!0!==h){const e=r.texture.createView(n);let t,s;void 0!==r.msaaTexture?(t=r.msaaTexture.createView(),s=e):(t=e,s=void 0),a.push({view:t,resolveTarget:s,depthSlice:l})}}if(o={textureViews:a},e.depth){const t=this.get(e.depthTexture),s={};(e.depthTexture.isArrayTexture||e.depthTexture.isCubeTexture)&&(s.dimension=TL,s.arrayLayerCount=1,s.baseArrayLayer=e.activeCubeFace),o.depthStencilView=t.texture.createView(s)}r[n]=o,i.width=s.width,i.height=s.height,i.samples=s.samples,i.activeMipmapLevel=e.activeMipmapLevel,i.activeCubeFace=e.activeCubeFace}const a={colorAttachments:[]};for(let e=0;e<o.textureViews.length;e++){const s=o.textureViews[e];let i={r:0,g:0,b:0,a:1};0===e&&t.clearValue&&(i=t.clearValue),a.colorAttachments.push({view:s.view,depthSlice:s.depthSlice,resolveTarget:s.resolveTarget,loadOp:t.loadOp||OB,storeOp:t.storeOp||FB,clearValue:i})}return o.depthStencilView&&(a.depthStencilAttachment={view:o.depthStencilView}),a}beginRender(e){const t=this.get(e),s=this.device,i=e.occlusionQueryCount;let r,n;i>0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,r=s.createQuerySet({type:"occlusion",count:i,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=r,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null),n=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:OB}),this.initTimestampQuery(jo,this.getTimestampUID(e),n),n.occlusionQuerySet=r;const o=n.depthStencilAttachment;if(null!==e.textures){const t=n.colorAttachments;for(let s=0;s<t.length;s++){const i=t[s];e.clearColor?(i.clearValue=0===s?e.clearColorValue:{r:0,g:0,b:0,a:1},i.loadOp=VB):i.loadOp=OB,i.storeOp=FB}}else{const t=n.colorAttachments[0];e.clearColor?(t.clearValue=e.clearColorValue,t.loadOp=VB):t.loadOp=OB,t.storeOp=FB}e.depth&&(e.clearDepth?(o.depthClearValue=e.clearDepthValue,o.depthLoadOp=VB):o.depthLoadOp=OB,o.depthStoreOp=FB),e.stencil&&(e.clearStencil?(o.stencilClearValue=e.clearStencilValue,o.stencilLoadOp=VB):o.stencilLoadOp=OB,o.stencilStoreOp=FB);const a=s.createCommandEncoder({label:"renderContext_"+e.id});if(!0===this._isRenderCameraDepthArray(e)){const s=e.camera.cameras;t.layerDescriptors&&t.layerDescriptors.length===s.length?this._updateDepthLayerDescriptors(e,t,s):this._createDepthLayerDescriptors(e,t,n,s),t.bundleEncoders=[],t.bundleSets=[];for(let i=0;i<s.length;i++){const s=this.pipelineUtils.createBundleEncoder(e,"renderBundleArrayCamera_"+i),r={attributes:{},bindingGroups:[],pipeline:null,index:null};t.bundleEncoders.push(s),t.bundleSets.push(r)}t.currentPass=null}else{const s=a.beginRenderPass(n);t.currentPass=s,e.viewport&&this.updateViewport(e),e.scissor&&this.updateScissor(e)}t.descriptor=n,t.encoder=a,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.renderBundles=[]}_createDepthLayerDescriptors(e,t,s,i){const r=s.depthStencilAttachment;t.layerDescriptors=[];const n=this.get(e.depthTexture);n.viewCache||(n.viewCache=[]);for(let o=0;o<i.length;o++){const i={...s,colorAttachments:[{...s.colorAttachments[0],view:s.colorAttachments[o].view}]};if(s.depthStencilAttachment){const t=o;n.viewCache[t]||(n.viewCache[t]=n.texture.createView({dimension:TL,baseArrayLayer:o,arrayLayerCount:1})),i.depthStencilAttachment={view:n.viewCache[t],depthLoadOp:r.depthLoadOp||VB,depthStoreOp:r.depthStoreOp||FB,depthClearValue:r.depthClearValue||1},e.stencil&&(i.depthStencilAttachment.stencilLoadOp=r.stencilLoadOp,i.depthStencilAttachment.stencilStoreOp=r.stencilStoreOp,i.depthStencilAttachment.stencilClearValue=r.stencilClearValue)}else i.depthStencilAttachment={...r};t.layerDescriptors.push(i)}}_updateDepthLayerDescriptors(e,t,s){for(let i=0;i<s.length;i++){const s=t.layerDescriptors[i];if(s.depthStencilAttachment){const t=s.depthStencilAttachment;e.depth&&(e.clearDepth?(t.depthClearValue=e.clearDepthValue,t.depthLoadOp=VB):t.depthLoadOp=OB),e.stencil&&(e.clearStencil?(t.stencilClearValue=e.clearStencilValue,t.stencilLoadOp=VB):t.stencilLoadOp=OB)}}}finishRender(e){const t=this.get(e),s=e.occlusionQueryCount;t.renderBundles.length>0&&t.currentPass.executeBundles(t.renderBundles),s>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();const i=t.encoder;if(!0===this._isRenderCameraDepthArray(e)){const s=[];for(let e=0;e<t.bundleEncoders.length;e++){const i=t.bundleEncoders[e];s.push(i.finish())}for(let r=0;r<t.layerDescriptors.length;r++)if(r<s.length){const n=t.layerDescriptors[r],o=i.beginRenderPass(n);if(e.viewport){const{x:t,y:s,width:i,height:r,minDepth:n,maxDepth:a}=e.viewportValue;o.setViewport(t,s,i,r,n,a)}if(e.scissor){const{x:t,y:s,width:i,height:r}=e.scissorValue;o.setScissorRect(t,s,i,r)}o.executeBundles([s[r]]),o.end()}}else t.currentPass&&t.currentPass.end();if(s>0){const i=8*s;let r=this.occludedResolveCache.get(i);void 0===r&&(r=this.device.createBuffer({size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(i,r));const n=this.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,s,r,0),t.encoder.copyBufferToBuffer(r,0,n,0,i),t.occlusionQueryBuffer=n,this.resolveOccludedAsync(e)}if(this.device.queue.submit([t.encoder.finish()]),null!==e.textures){const t=e.textures;for(let e=0;e<t.length;e++){const s=t[e];!0===s.generateMipmaps&&this.textureUtils.generateMipmaps(s)}}}isOccluded(e,t){const s=this.get(e);return s.occluded&&s.occluded.has(t)}async resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueryBuffer:s,currentOcclusionQueryObjects:i}=t;if(s&&i){const e=new WeakSet;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueryBuffer=null,await s.mapAsync(GPUMapMode.READ);const r=s.getMappedRange(),n=new BigUint64Array(r);for(let t=0;t<i.length;t++)n[t]===BigInt(0)&&e.add(i[t]);s.destroy(),t.occluded=e}}updateViewport(e){const{currentPass:t}=this.get(e),{x:s,y:i,width:r,height:n,minDepth:o,maxDepth:a}=e.viewportValue;t.setViewport(s,i,r,n,o,a)}updateScissor(e){const{currentPass:t}=this.get(e),{x:s,y:i,width:r,height:n}=e.scissorValue;t.setScissorRect(s,i,r,n)}getClearColor(){const e=super.getClearColor();return!0===this.renderer.alpha&&(e.r*=e.a,e.g*=e.a,e.b*=e.a),e}clear(e,t,s,i=null){const r=this.device,n=this.renderer;let o,a,l,h,u=[];if(e){const e=this.getClearColor();a={r:e.r,g:e.g,b:e.b,a:e.a}}if(null===i){l=n.depth,h=n.stencil;const t=this._getDefaultRenderPassDescriptor();if(e){u=t.colorAttachments;const e=u[0];e.clearValue=a,e.loadOp=VB,e.storeOp=FB}(l||h)&&(o=t.depthStencilAttachment)}else{l=i.depth,h=i.stencil;const r={loadOp:e?VB:OB,clearValue:e?a:void 0};l&&(r.depthLoadOp=t?VB:OB,r.depthClearValue=t?n.getClearDepth():void 0,r.depthStoreOp=FB),h&&(r.stencilLoadOp=s?VB:OB,r.stencilClearValue=s?n.getClearStencil():void 0,r.stencilStoreOp=FB);const c=this._getRenderPassDescriptor(i,r);u=c.colorAttachments,o=c.depthStencilAttachment}l&&o&&(t?(o.depthLoadOp=VB,o.depthClearValue=n.getClearDepth(),o.depthStoreOp=FB):(o.depthLoadOp=OB,o.depthStoreOp=FB)),h&&o&&(s?(o.stencilLoadOp=VB,o.stencilClearValue=n.getClearStencil(),o.stencilStoreOp=FB):(o.stencilLoadOp=OB,o.stencilStoreOp=FB));const c=r.createCommandEncoder({label:"clear"});c.beginRenderPass({colorAttachments:u,depthStencilAttachment:o}).end(),r.queue.submit([c.finish()])}beginCompute(e){const t=this.get(e),s={label:"computeGroup_"+e.id};this.initTimestampQuery(Go,this.getTimestampUID(e),s),t.cmdEncoderGPU=this.device.createCommandEncoder({label:"computeGroup_"+e.id}),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(s)}compute(e,t,s,i,r=null){const n=this.get(t),{passEncoderGPU:o}=this.get(e),a=this.get(i).pipeline;this.pipelineUtils.setPipeline(o,a);for(let e=0,t=s.length;e<t;e++){const t=s[e],i=this.get(t);o.setBindGroup(e,i.group)}if(null===r&&(r=t.count),r&&"object"==typeof r&&r.isIndirectStorageBufferAttribute){const e=this.get(r).buffer;return void o.dispatchWorkgroupsIndirect(e,0)}if("number"==typeof r){const e=r;if(void 0===n.dispatchSize||n.count!==e){n.dispatchSize=[0,1,1],n.count=e;const s=t.workgroupSize;let i=s[0];for(let e=1;e<s.length;e++)i*=s[e];const o=Math.ceil(e/i),a=this.device.limits.maxComputeWorkgroupsPerDimension;r=[o,1,1],o>a&&(r[0]=Math.min(o,a),r[1]=Math.ceil(o/a)),n.dispatchSize=r}r=n.dispatchSize}o.dispatchWorkgroups(r[0],r[1]||1,r[2]||1)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}draw(e,t){const{object:s,material:i,context:r,pipeline:n}=e,o=e.getBindings(),a=this.get(r),l=this.get(n),h=l.pipeline;if(!0===l.error)return;const u=e.getIndex(),c=null!==u,d=e.getDrawParameters();if(null===d)return;const p=(t,s)=>{this.pipelineUtils.setPipeline(t,h),s.pipeline=h;const n=s.bindingGroups;for(let e=0,s=o.length;e<s;e++){const s=o[e],i=this.get(s);n[s.index]!==s.id&&(t.setBindGroup(s.index,i.group),n[s.index]=s.id)}if(!0===c&&s.index!==u){const e=this.get(u).buffer,i=u.array instanceof Uint16Array?jB:$B;t.setIndexBuffer(e,i),s.index=u}const l=e.getVertexBuffers();for(let e=0,i=l.length;e<i;e++){const i=l[e];if(s.attributes[e]!==i){const r=this.get(i).buffer;t.setVertexBuffer(e,r),s.attributes[e]=i}}!0===r.stencil&&!0===i.stencilWrite&&a.currentStencilRef!==i.stencilRef&&(t.setStencilReference(i.stencilRef),a.currentStencilRef=i.stencilRef)},m=(i,r)=>{if(p(i,r),!0===s.isBatchedMesh){const e=s._multiDrawStarts,r=s._multiDrawCounts,n=s._multiDrawCount,o=s._multiDrawInstances;null!==o&&Qo("WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");for(let a=0;a<n;a++){const n=o?o[a]:1,l=n>1?0:a;!0===c?i.drawIndexed(r[a],n,e[a]/u.array.BYTES_PER_ELEMENT,0,l):i.draw(r[a],n,e[a],l),t.update(s,r[a],n)}}else if(!0===c){const{vertexCount:r,instanceCount:n,firstVertex:o}=d,a=e.getIndirect();if(null!==a){const t=this.get(a).buffer,s=e.getIndirectOffset(),r=Array.isArray(s)?s:[s];for(let e=0;e<r.length;e++)i.drawIndexedIndirect(t,r[e])}else i.drawIndexed(r,n,o,0,0);t.update(s,r,n)}else{const{vertexCount:r,instanceCount:n,firstVertex:o}=d,a=e.getIndirect();if(null!==a){const t=this.get(a).buffer,s=e.getIndirectOffset(),r=Array.isArray(s)?s:[s];for(let e=0;e<r.length;e++)i.drawIndirect(t,r[e])}else i.draw(r,n,o,0);t.update(s,r,n)}};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const t=this.get(e.camera),i=e.camera.cameras,n=e.getBindingGroup("cameraIndex");if(void 0===t.indexesGPU||t.indexesGPU.length!==i.length){const e=this.get(n),s=[],r=new Uint32Array([0,0,0,0]);for(let t=0,n=i.length;t<n;t++){r[0]=t;const{layoutGPU:i}=e.layout,n=this.bindingUtils.createBindGroupIndex(r,i);s.push(n)}t.indexesGPU=s}const o=this.renderer.getPixelRatio();for(let e=0,l=i.length;e<l;e++){const l=i[e];if(s.layers.test(l.layers)){const s=l.viewport;let i=a.currentPass,h=a.currentSets;if(a.bundleEncoders){i=a.bundleEncoders[e],h=a.bundleSets[e]}s&&i.setViewport(Math.floor(s.x*o),Math.floor(s.y*o),Math.floor(s.width*o),Math.floor(s.height*o),r.viewportValue.minDepth,r.viewportValue.maxDepth),n&&t.indexesGPU&&(i.setBindGroup(n.index,t.indexesGPU[e]),h.bindingGroups[n.index]=n.id),m(i,h)}}}else if(a.currentPass){if(void 0!==a.occlusionQuerySet){const e=a.lastOcclusionObject;e!==s&&(null!==e&&!0===e.occlusionTest&&(a.currentPass.endOcclusionQuery(),a.occlusionQueryIndex++),!0===s.occlusionTest&&(a.currentPass.beginOcclusionQuery(a.occlusionQueryIndex),a.occlusionQueryObjects[a.occlusionQueryIndex]=s),a.lastOcclusionObject=s)}m(a.currentPass,a.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:s,material:i}=e,r=this.utils,n=r.getSampleCountRenderContext(e.context),o=r.getCurrentColorSpace(e.context),a=r.getCurrentColorFormat(e.context),l=r.getCurrentDepthStencilFormat(e.context),h=r.getPrimitiveTopology(s,i);let u=!1;return t.material===i&&t.materialVersion===i.version&&t.transparent===i.transparent&&t.blending===i.blending&&t.premultipliedAlpha===i.premultipliedAlpha&&t.blendSrc===i.blendSrc&&t.blendDst===i.blendDst&&t.blendEquation===i.blendEquation&&t.blendSrcAlpha===i.blendSrcAlpha&&t.blendDstAlpha===i.blendDstAlpha&&t.blendEquationAlpha===i.blendEquationAlpha&&t.colorWrite===i.colorWrite&&t.depthWrite===i.depthWrite&&t.depthTest===i.depthTest&&t.depthFunc===i.depthFunc&&t.stencilWrite===i.stencilWrite&&t.stencilFunc===i.stencilFunc&&t.stencilFail===i.stencilFail&&t.stencilZFail===i.stencilZFail&&t.stencilZPass===i.stencilZPass&&t.stencilFuncMask===i.stencilFuncMask&&t.stencilWriteMask===i.stencilWriteMask&&t.side===i.side&&t.alphaToCoverage===i.alphaToCoverage&&t.sampleCount===n&&t.colorSpace===o&&t.colorFormat===a&&t.depthStencilFormat===l&&t.primitiveTopology===h&&t.clippingContextCacheKey===e.clippingContextCacheKey||(t.material=i,t.materialVersion=i.version,t.transparent=i.transparent,t.blending=i.blending,t.premultipliedAlpha=i.premultipliedAlpha,t.blendSrc=i.blendSrc,t.blendDst=i.blendDst,t.blendEquation=i.blendEquation,t.blendSrcAlpha=i.blendSrcAlpha,t.blendDstAlpha=i.blendDstAlpha,t.blendEquationAlpha=i.blendEquationAlpha,t.colorWrite=i.colorWrite,t.depthWrite=i.depthWrite,t.depthTest=i.depthTest,t.depthFunc=i.depthFunc,t.stencilWrite=i.stencilWrite,t.stencilFunc=i.stencilFunc,t.stencilFail=i.stencilFail,t.stencilZFail=i.stencilZFail,t.stencilZPass=i.stencilZPass,t.stencilFuncMask=i.stencilFuncMask,t.stencilWriteMask=i.stencilWriteMask,t.side=i.side,t.alphaToCoverage=i.alphaToCoverage,t.sampleCount=n,t.colorSpace=o,t.colorFormat=a,t.depthStencilFormat=l,t.primitiveTopology=h,t.clippingContextCacheKey=e.clippingContextCacheKey,u=!0),u}getRenderCacheKey(e){const{object:t,material:s}=e,i=this.utils,r=e.context,n=t.isMesh&&t.matrixWorld.determinant()<0;return[s.transparent,s.blending,s.premultipliedAlpha,s.blendSrc,s.blendDst,s.blendEquation,s.blendSrcAlpha,s.blendDstAlpha,s.blendEquationAlpha,s.colorWrite,s.depthWrite,s.depthTest,s.depthFunc,s.stencilWrite,s.stencilFunc,s.stencilFail,s.stencilZFail,s.stencilZPass,s.stencilFuncMask,s.stencilWriteMask,s.side,n,i.getSampleCountRenderContext(r),i.getCurrentColorSpace(r),i.getCurrentColorFormat(r),i.getCurrentDepthStencilFormat(r),i.getPrimitiveTopology(t,s),e.getGeometryCacheKey(),e.clippingContextCacheKey].join()}updateSampler(e){return this.textureUtils.updateSampler(e)}createDefaultTexture(e){return this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}initTimestampQuery(e,t,s){if(!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new cF(this.device,e,2048));const i=this.timestampQueryPool[e],r=i.allocateQueriesForContext(t);s.timestampWrites={querySet:i.querySet,beginningOfPassWriteIndex:r,endOfPassWriteIndex:r+1}}createNodeBuilder(e,t){return new sF(e,t)}createProgram(e){this.get(e).module={module:this.device.createShaderModule({code:e.code,label:e.stage+(""!==e.name?`_${e.name}`:"")}),entryPoint:"main"}}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t){this.pipelineUtils.createComputePipeline(e,t)}beginBundle(e){const t=this.get(e);t._currentPass=t.currentPass,t._currentSets=t.currentSets,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.currentPass=this.pipelineUtils.createBundleEncoder(e)}finishBundle(e,t){const s=this.get(e),i=s.currentPass.finish();this.get(t).bundleGPU=i,s.currentSets=s._currentSets,s.currentPass=s._currentPass}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createBindings(e,t,s,i){this.bindingUtils.createBindings(e,t,s,i)}updateBindings(e,t,s,i){this.bindingUtils.createBindings(e,t,s,i)}updateBinding(e){this.bindingUtils.updateBinding(e)}deleteBindGroupData(e){this.bindingUtils.deleteBindGroupData(e)}createIndexAttribute(e){let t=GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST;(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(t|=GPUBufferUsage.STORAGE),this.attributeUtils.createAttribute(e,t)}createAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createIndirectStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}updateSize(){this.delete(this.renderer.getCanvasTarget())}getMaxAnisotropy(){return 16}hasFeature(e){return void 0!==PL[e]&&(e=PL[e]),this.device.features.has(e)}copyTextureToTexture(e,t,s=null,i=null,r=0,n=0){let o=0,a=0,l=0,h=0,u=0,c=0,d=e.image.width,p=e.image.height,m=1;null!==s&&(!0===s.isBox3?(h=s.min.x,u=s.min.y,c=s.min.z,d=s.max.x-s.min.x,p=s.max.y-s.min.y,m=s.max.z-s.min.z):(h=s.min.x,u=s.min.y,d=s.max.x-s.min.x,p=s.max.y-s.min.y,m=1)),null!==i&&(o=i.x,a=i.y,l=i.z||0);const f=this.device.createCommandEncoder({label:"copyTextureToTexture_"+e.id+"_"+t.id}),g=this.get(e).texture,y=this.get(t).texture;f.copyTextureToTexture({texture:g,mipLevel:r,origin:{x:h,y:u,z:c}},{texture:y,mipLevel:n,origin:{x:o,y:a,z:l}},[d,p,m]),this.device.queue.submit([f.finish()]),0===n&&t.generateMipmaps&&this.textureUtils.generateMipmaps(t)}copyFramebufferToTexture(e,t,s){const i=this.get(t);let r=null;r=t.renderTarget?e.isDepthTexture?this.get(t.depthTexture).texture:this.get(t.textures[0]).texture:e.isDepthTexture?this.textureUtils.getDepthBuffer(t.depth,t.stencil):this.context.getCurrentTexture();const n=this.get(e).texture;if(r.format!==n.format)return void Zo("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",r.format,n.format);let o;if(i.currentPass?(i.currentPass.end(),o=i.encoder):o=this.device.createCommandEncoder({label:"copyFramebufferToTexture_"+e.id}),o.copyTextureToTexture({texture:r,origin:[s.x,s.y,0]},{texture:n},[s.z,s.w]),e.generateMipmaps&&this.textureUtils.generateMipmaps(e,o),i.currentPass){const{descriptor:e}=i;for(let t=0;t<e.colorAttachments.length;t++)e.colorAttachments[t].loadOp=OB;t.depth&&(e.depthStencilAttachment.depthLoadOp=OB),t.stencil&&(e.depthStencilAttachment.stencilLoadOp=OB),i.currentPass=o.beginRenderPass(e),i.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.viewport&&this.updateViewport(t),t.scissor&&this.updateScissor(t)}else this.device.queue.submit([o.finish()])}dispose(){if(this.bindingUtils.dispose(),this.textureUtils.dispose(),this.occludedResolveCache){for(const e of this.occludedResolveCache.values())e.destroy();this.occludedResolveCache.clear()}if(this.timestampQueryPool)for(const e of Object.values(this.timestampQueryPool))null!==e&&e.dispose();void 0===this.parameters.device&&null!==this.device&&this.device.destroy()}}class pF extends Uu{constructor(e,t,s,i,r,n){super(e,t,s,i,r,n),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}}class mF extends Uu{constructor(e,t,s,i,r,n){super(e,t,s,i,r,n),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}}class fF extends lP{constructor(){super(),this.addMaterial(qw,"MeshPhongMaterial"),this.addMaterial(zT,"MeshStandardMaterial"),this.addMaterial(UT,"MeshPhysicalMaterial"),this.addMaterial(WT,"MeshToonMaterial"),this.addMaterial(Vw,"MeshBasicMaterial"),this.addMaterial(Ww,"MeshLambertMaterial"),this.addMaterial(Mw,"MeshNormalMaterial"),this.addMaterial(XT,"MeshMatcapMaterial"),this.addMaterial(xw,"LineBasicMaterial"),this.addMaterial(_w,"LineDashedMaterial"),this.addMaterial(tS,"PointsMaterial"),this.addMaterial(KT,"SpriteMaterial"),this.addMaterial(nS,"ShadowMaterial"),this.addLight(sC,ju),this.addLight(DR,Hu),this.addLight(VR,Xu),this.addLight(zR,Uu),this.addLight(jR,qu),this.addLight($R,Lu),this.addLight(WR,Zu),this.addLight(kR,pF),this.addLight(GR,mF),this.addToneMapping(qA,1),this.addToneMapping(XA,2),this.addToneMapping(YA,3),this.addToneMapping(QA,4),this.addToneMapping(tN,6),this.addToneMapping(sN,7)}}class gF extends RP{constructor(e={}){let t;e.forceWebGL?t=wB:(t=dF,e.getFallback=()=>(Yo("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new wB(e)));super(new t(e),e),this.library=new fF,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}
12
+ /**
13
+ * @license
14
+ * Copyright 2010-2025 Three.js Authors
15
+ * SPDX-License-Identifier: MIT
16
+ */YC.BRDF_GGX,YC.BRDF_Lambert,YC.BasicPointShadowFilter,YC.BasicShadowFilter,YC.Break,YC.Const;const yF=YC.Continue;YC.DFGLUT,YC.D_GGX,YC.Discard,YC.EPSILON,YC.F_Schlick;const xF=YC.Fn;YC.INFINITY;const bF=YC.If,_F=YC.Loop;YC.NodeAccess,YC.NodeShaderStage,YC.NodeType,YC.NodeUpdateType,YC.PCFShadowFilter,YC.PCFSoftShadowFilter,YC.PI,YC.PI2,YC.TWO_PI,YC.HALF_PI,YC.PointShadowFilter,YC.Return,YC.Schlick_to_F0,YC.ScriptableNodeResources,YC.ShaderNode,YC.Stack,YC.Switch,YC.TBNViewMatrix,YC.VSMShadowFilter,YC.V_GGX_SmithCorrelated,YC.Var,YC.VarIntent;const wF=YC.abs;YC.acesFilmicToneMapping,YC.acos,YC.add,YC.addMethodChaining,YC.addNodeElement,YC.agxToneMapping,YC.all,YC.alphaT,YC.and,YC.anisotropy,YC.anisotropyB,YC.anisotropyT,YC.any,YC.append,YC.array,YC.arrayBuffer,YC.asin,YC.assign,YC.atan,YC.atan2;const vF=YC.atomicAdd;YC.atomicAnd,YC.atomicFunc,YC.atomicLoad,YC.atomicMax,YC.atomicMin,YC.atomicOr,YC.atomicStore,YC.atomicSub,YC.atomicXor,YC.attenuationColor,YC.attenuationDistance,YC.attribute,YC.attributeArray,YC.backgroundBlurriness,YC.backgroundIntensity,YC.backgroundRotation,YC.batch,YC.bentNormalView,YC.billboarding,YC.bitAnd,YC.bitNot,YC.bitOr,YC.bitXor,YC.bitangentGeometry,YC.bitangentLocal,YC.bitangentView,YC.bitangentWorld,YC.bitcast,YC.blendBurn,YC.blendColor,YC.blendDodge,YC.blendOverlay,YC.blendScreen,YC.blur,YC.bool,YC.buffer,YC.bufferAttribute,YC.bumpMap,YC.burn,YC.builtin,YC.builtinAOContext,YC.builtinShadowContext,YC.bvec2,YC.bvec3,YC.bvec4,YC.bypass,YC.cache,YC.call,YC.cameraFar,YC.cameraIndex,YC.cameraNear,YC.cameraNormalMatrix,YC.cameraPosition,YC.cameraProjectionMatrix,YC.cameraProjectionMatrixInverse,YC.cameraViewMatrix,YC.cameraViewport,YC.cameraWorldMatrix,YC.cbrt,YC.cdl,YC.ceil,YC.checker,YC.cineonToneMapping,YC.clamp,YC.clearcoat,YC.clearcoatNormalView,YC.clearcoatRoughness,YC.code,YC.color,YC.colorSpaceToWorking,YC.colorToDirection,YC.compute,YC.computeKernel,YC.computeSkinning,YC.context,YC.convert,YC.convertColorSpace,YC.convertToTexture,YC.countLeadingZeros,YC.countOneBits,YC.countTrailingZeros,YC.cos;const TF=YC.cross;YC.cubeTexture,YC.cubeTextureBase,YC.dFdx,YC.dFdy,YC.dashSize,YC.debug,YC.decrement,YC.decrementBefore,YC.defaultBuildStages,YC.defaultShaderStages,YC.defined,YC.degrees,YC.deltaTime,YC.densityFog,YC.densityFogFactor,YC.depth,YC.depthPass,YC.determinant,YC.difference,YC.diffuseColor,YC.directPointLight,YC.directionToColor,YC.directionToFaceDirection,YC.dispersion,YC.distance,YC.div,YC.dodge,YC.dot,YC.drawIndex,YC.dynamicBufferAttribute,YC.element,YC.emissive,YC.equal,YC.equals,YC.equirectUV,YC.exp,YC.exp2,YC.expression,YC.faceDirection,YC.faceForward,YC.faceforward;const SF=YC.float;YC.floatBitsToInt,YC.floatBitsToUint,YC.floor,YC.fog,YC.fract,YC.frameGroup,YC.frameId,YC.frontFacing,YC.fwidth,YC.gain,YC.gapSize,YC.getConstNodeType,YC.getCurrentStack,YC.getDirection,YC.getDistanceAttenuation,YC.getGeometryRoughness,YC.getNormalFromDepth,YC.interleavedGradientNoise,YC.vogelDiskSample,YC.getParallaxCorrectNormal,YC.getRoughness,YC.getScreenPosition,YC.getShIrradianceAt,YC.getShadowMaterial,YC.getShadowRenderObjectFunction,YC.getTextureIndex,YC.getViewPosition,YC.globalId,YC.glsl,YC.glslFn,YC.grayscale,YC.greaterThan,YC.greaterThanEqual,YC.hash,YC.highpModelNormalViewMatrix,YC.highpModelViewMatrix,YC.hue,YC.increment,YC.incrementBefore,YC.instance;const MF=YC.instanceIndex,AF=YC.instancedArray;YC.instancedBufferAttribute,YC.instancedDynamicBufferAttribute,YC.instancedMesh;const NF=YC.int;YC.intBitsToFloat,YC.inverse,YC.inverseSqrt,YC.inversesqrt,YC.invocationLocalIndex,YC.invocationSubgroupIndex,YC.ior,YC.iridescence,YC.iridescenceIOR,YC.iridescenceThickness,YC.ivec2,YC.ivec3,YC.ivec4,YC.js,YC.label,YC.length,YC.lengthSq,YC.lessThan,YC.lessThanEqual,YC.lightPosition,YC.lightProjectionUV,YC.lightShadowMatrix,YC.lightTargetDirection,YC.lightTargetPosition,YC.lightViewPosition,YC.lightingContext,YC.lights,YC.linearDepth,YC.linearToneMapping,YC.localId,YC.log,YC.log2,YC.logarithmicDepthToViewZ,YC.luminance,YC.mat2,YC.mat3;const EF=YC.mat4;YC.matcapUV,YC.materialAO,YC.materialAlphaTest,YC.materialAnisotropy,YC.materialAnisotropyVector,YC.materialAttenuationColor,YC.materialAttenuationDistance,YC.materialClearcoat,YC.materialClearcoatNormal,YC.materialClearcoatRoughness,YC.materialColor,YC.materialDispersion,YC.materialEmissive,YC.materialEnvIntensity,YC.materialEnvRotation,YC.materialIOR,YC.materialIridescence,YC.materialIridescenceIOR,YC.materialIridescenceThickness,YC.materialLightMap,YC.materialLineDashOffset,YC.materialLineDashSize,YC.materialLineGapSize,YC.materialLineScale,YC.materialLineWidth,YC.materialMetalness,YC.materialNormal,YC.materialOpacity,YC.materialPointSize,YC.materialReference,YC.materialReflectivity,YC.materialRefractionRatio,YC.materialRotation,YC.materialRoughness,YC.materialSheen,YC.materialSheenRoughness,YC.materialShininess,YC.materialSpecular,YC.materialSpecularColor,YC.materialSpecularIntensity,YC.materialSpecularStrength,YC.materialThickness,YC.materialTransmission;const CF=YC.max;YC.maxMipLevel,YC.mediumpModelViewMatrix,YC.metalness;const RF=YC.min,PF=YC.mix;YC.mixElement,YC.mod,YC.modInt,YC.modelDirection,YC.modelNormalMatrix,YC.modelPosition,YC.modelRadius,YC.modelScale,YC.modelViewMatrix,YC.modelViewPosition,YC.modelViewProjection,YC.modelWorldMatrix,YC.modelWorldMatrixInverse,YC.morphReference,YC.mrt,YC.mul,YC.mx_aastep,YC.mx_add,YC.mx_atan2,YC.mx_cell_noise_float,YC.mx_contrast,YC.mx_divide,YC.mx_fractal_noise_float,YC.mx_fractal_noise_vec2,YC.mx_fractal_noise_vec3,YC.mx_fractal_noise_vec4,YC.mx_frame,YC.mx_heighttonormal,YC.mx_hsvtorgb,YC.mx_ifequal,YC.mx_ifgreater,YC.mx_ifgreatereq,YC.mx_invert,YC.mx_modulo,YC.mx_multiply,YC.mx_noise_float,YC.mx_noise_vec3,YC.mx_noise_vec4,YC.mx_place2d,YC.mx_power,YC.mx_ramp4,YC.mx_ramplr,YC.mx_ramptb,YC.mx_rgbtohsv,YC.mx_rotate2d,YC.mx_rotate3d,YC.mx_safepower,YC.mx_separate,YC.mx_splitlr,YC.mx_splittb,YC.mx_srgb_texture_to_lin_rec709,YC.mx_subtract,YC.mx_timer,YC.mx_transform_uv,YC.mx_unifiednoise2d,YC.mx_unifiednoise3d,YC.mx_worley_noise_float,YC.mx_worley_noise_vec2,YC.mx_worley_noise_vec3,YC.negate,YC.neutralToneMapping,YC.nodeArray,YC.nodeImmutable,YC.nodeObject,YC.nodeObjectIntent,YC.nodeObjects,YC.nodeProxy,YC.nodeProxyIntent,YC.normalFlat,YC.normalGeometry,YC.normalLocal,YC.normalMap,YC.normalView,YC.normalViewGeometry,YC.normalWorld,YC.normalWorldGeometry;const BF=YC.normalize;YC.not,YC.notEqual,YC.numWorkgroups,YC.objectDirection,YC.objectGroup,YC.objectPosition,YC.objectRadius,YC.objectScale,YC.objectViewPosition,YC.objectWorldMatrix,YC.OnBeforeObjectUpdate,YC.OnBeforeMaterialUpdate,YC.OnObjectUpdate,YC.OnMaterialUpdate,YC.oneMinus,YC.or,YC.orthographicDepthToViewZ,YC.oscSawtooth,YC.oscSine,YC.oscSquare,YC.oscTriangle,YC.output,YC.outputStruct,YC.overlay,YC.overloadingFn,YC.packHalf2x16,YC.packSnorm2x16,YC.packUnorm2x16,YC.parabola,YC.parallaxDirection,YC.parallaxUV,YC.parameter,YC.pass,YC.passTexture,YC.pcurve,YC.perspectiveDepthToViewZ,YC.pmremTexture,YC.pointShadow,YC.pointUV,YC.pointWidth,YC.positionGeometry,YC.positionLocal,YC.positionPrevious,YC.positionView,YC.positionViewDirection,YC.positionWorld,YC.positionWorldDirection,YC.posterize,YC.pow,YC.pow2,YC.pow3,YC.pow4,YC.premultiplyAlpha,YC.property,YC.radians,YC.rand,YC.range,YC.rangeFog,YC.rangeFogFactor,YC.reciprocal,YC.reference,YC.referenceBuffer,YC.reflect,YC.reflectVector,YC.reflectView,YC.reflector,YC.refract,YC.refractVector,YC.refractView,YC.reinhardToneMapping,YC.remap,YC.remapClamp,YC.renderGroup,YC.renderOutput,YC.rendererReference,YC.replaceDefaultUV,YC.rotate,YC.rotateUV,YC.roughness,YC.round,YC.rtt,YC.sRGBTransferEOTF,YC.sRGBTransferOETF,YC.sample,YC.sampler,YC.samplerComparison,YC.saturate,YC.saturation,YC.screen,YC.screenCoordinate,YC.screenDPR,YC.screenSize,YC.screenUV,YC.scriptable,YC.scriptableValue;const IF=YC.select;YC.setCurrentStack,YC.setName,YC.shaderStages,YC.shadow,YC.shadowPositionWorld,YC.shapeCircle,YC.sharedUniformGroup,YC.sheen,YC.sheenRoughness,YC.shiftLeft,YC.shiftRight,YC.shininess,YC.sign,YC.sin,YC.sinc,YC.skinning,YC.smoothstep,YC.smoothstepElement,YC.specularColor,YC.specularF90,YC.spherizeUV,YC.split,YC.spritesheetUV,YC.sqrt,YC.stack,YC.step,YC.stepElement,YC.storage,YC.storageBarrier,YC.storageObject,YC.storageTexture,YC.string,YC.struct,YC.sub,YC.subgroupAdd,YC.subgroupAll,YC.subgroupAnd,YC.subgroupAny,YC.subgroupBallot,YC.subgroupBroadcast,YC.subgroupBroadcastFirst,YC.subBuild,YC.subgroupElect,YC.subgroupExclusiveAdd,YC.subgroupExclusiveMul,YC.subgroupInclusiveAdd,YC.subgroupInclusiveMul,YC.subgroupIndex,YC.subgroupMax,YC.subgroupMin,YC.subgroupMul,YC.subgroupOr,YC.subgroupShuffle,YC.subgroupShuffleDown,YC.subgroupShuffleUp,YC.subgroupShuffleXor,YC.subgroupSize,YC.subgroupXor,YC.tan,YC.tangentGeometry,YC.tangentLocal,YC.tangentView,YC.tangentWorld,YC.texture,YC.texture3D,YC.textureBarrier,YC.textureBicubic,YC.textureBicubicLevel,YC.textureCubeUV,YC.textureLoad,YC.textureSize,YC.textureLevel,YC.textureStore,YC.thickness,YC.time,YC.toneMapping,YC.toneMappingExposure,YC.toonOutlinePass,YC.transformDirection,YC.transformNormal,YC.transformNormalToView,YC.transformedClearcoatNormalView,YC.transformedNormalView,YC.transformedNormalWorld,YC.transmission,YC.transpose,YC.triNoise3D,YC.triplanarTexture,YC.triplanarTextures,YC.trunc;const DF=YC.uint;YC.uintBitsToFloat,YC.uniform,YC.uniformArray,YC.uniformCubeTexture,YC.uniformGroup,YC.uniformFlow,YC.uniformTexture,YC.unpackHalf2x16,YC.unpackSnorm2x16,YC.unpackUnorm2x16,YC.unpremultiplyAlpha,YC.userData,YC.uv,YC.uvec2,YC.uvec3,YC.uvec4,YC.varying,YC.varyingProperty,YC.vec2;const LF=YC.vec3,FF=YC.vec4;YC.vectorComponents,YC.velocity,YC.vertexColor,YC.vertexIndex,YC.vertexStage,YC.vibrance,YC.viewZToLogarithmicDepth,YC.viewZToOrthographicDepth,YC.viewZToPerspectiveDepth,YC.viewport,YC.viewportCoordinate,YC.viewportDepthTexture,YC.viewportLinearDepth,YC.viewportMipTexture,YC.viewportResolution,YC.viewportSafeUV,YC.viewportSharedTexture,YC.viewportSize,YC.viewportTexture,YC.viewportUV,YC.wgsl,YC.wgslFn,YC.workgroupArray,YC.workgroupBarrier,YC.workgroupId,YC.workingToColorSpace,YC.xor;const OF=1e-5,VF=1e-16,zF=1e-16;function kF(e,t,s,i,r){e.bvhcast(t,s.matrixWorld,{intersectsRanges:(e,t,s,n)=>{i._edgeOffsets.push(e),i._edgeCounts.push(t),i._meshOffsets.push(s),i._meshCounts.push(n),i._meshIndex.push(r),i.groupCount++}})}let UF=null;async function GF(e,t,s,i,r=null){const n=await async function(){return null===UF&&(UF=new gF,await UF.init()),UF}();e._edgeOffsets&&(e.edgeOffsets=new Uint32Array(e._edgeOffsets),e.edgeCounts=new Uint32Array(e._edgeCounts),e.meshOffsets=new Uint32Array(e._meshOffsets),e.meshCounts=new Uint32Array(e._meshCounts),e.meshIndex=new Uint32Array(e._meshIndex),e._edgeOffsets=null,e._edgeCounts=null,e._meshOffsets=null,e._meshCounts=null,e._meshIndex=null);const o=AF(function(e){const t=new Float32Array(6*e.length);for(let s=0;s<e.length;s++){const i=e[s];t[6*s+0]=i.start.x,t[6*s+1]=i.start.y,t[6*s+2]=i.start.z,t[6*s+3]=i.end.x,t[6*s+4]=i.end.y,t[6*s+5]=i.end.z}return t}(s.lines),"float");qr.enabled&&console.log("Number of meshes:",t.length),qr.enabled&&console.log("Group count:",e.groupCount);const a=[];{let e=0;for(;e<t.length;){let s=e,i=0;for(;s<t.length;){const r=t[s].geometry,n=r.index?r.index.count/3:r.attributes.position.count/3;if(s>e&&(s-e>=1e3||i+n>1e5))break;i+=n,s++}a.push({start:e,end:s}),e=s}}qr.enabled&&console.log(`Split ${t.length} meshes into ${a.length} batches`);let l=0,h=0,u=0,c=0,d=0;for(let s=0;s<a.length;s++){const{start:p,end:m}=a[s],f=m-p;qr.enabled&&console.log(`Processing batch ${s+1}/${a.length} (meshes ${p}-${m-1})`);let g=0,y=0;const x=[];for(let e=p;e<m;e++){const s=t[e].geometry;x.push(y/3),g+=s.attributes.position.array.length,y+=s.index.array.length}const b=new Float32Array(g),_=new Uint32Array(y);let w=0,v=0,T=0;for(let e=p;e<m;e++){const s=t[e].geometry,i=s.attributes.position.array,r=s.index.array;b.set(i,w),w+=i.length;for(let e=0;e<r.length;e++)_[v+e]=r[e]+T;v+=r.length,T+=s.attributes.position.count}const S=new Float32Array(16*f);for(let e=p;e<m;e++){const s=e-p;S.set(t[e].matrixWorld.elements,16*s)}const M=[];for(let t=0;t<e.groupCount;t++){const s=e.meshIndex[t];if(s>=p&&s<m){const i=s-p,r=x[i]+e.meshOffsets[t];M.push({edgeOffset:e.edgeOffsets[t],edgeCount:e.edgeCounts[t],triOffset:r,triCount:e.meshCounts[t],meshIdx:i})}}if(0===M.length){qr.enabled&&console.log(` Batch ${s+1}: no groups, skipping`);continue}const A=new Uint32Array(5*M.length);for(let e=0;e<M.length;e++){const t=M[e],s=5*e;A[s+0]=t.edgeOffset,A[s+1]=t.edgeCount,A[s+2]=t.triOffset,A[s+3]=t.triCount,A[s+4]=t.meshIdx}let N=0;for(let e=0;e<M.length;e++)N+=M[e].edgeCount*M[e].triCount;r&&(r.candidates+=N);let E=Math.min(Math.ceil(.1*N),2e6),C=Math.max(E,1e4);qr.enabled&&console.log(` Batch ${s+1}: ${M.length} groups, ${g/3} vertices, ${y/3} triangles, ${N} pairs, buffer for ${C} overlaps`);const R=performance.now(),P=AF(b,"float"),B=AF(_,"uint"),I=AF(S,"float"),D=AF(A,"uint");let L=AF(new Uint32Array([0]),"uint").toAtomic(),F=AF(new Float32Array(3*C),"float");c+=performance.now()-R;const O=performance.now(),V=xF(()=>{const e=MF.mul(5),t=D.element(e),s=D.element(e.add(1)),i=D.element(e.add(2)),r=D.element(e.add(3)),n=D.element(e.add(4)).mul(16),a=EF(I.element(n),I.element(n.add(1)),I.element(n.add(2)),I.element(n.add(3)),I.element(n.add(4)),I.element(n.add(5)),I.element(n.add(6)),I.element(n.add(7)),I.element(n.add(8)),I.element(n.add(9)),I.element(n.add(10)),I.element(n.add(11)),I.element(n.add(12)),I.element(n.add(13)),I.element(n.add(14)),I.element(n.add(15)));_F({start:NF(0),end:r.toInt(),type:"int",condition:"<",name:"triIdx"},({triIdx:e})=>{const r=i.add(e.toUint()).mul(3),n=B.element(r),l=B.element(r.add(1)),h=B.element(r.add(2)),u=LF(P.element(n.mul(3)),P.element(n.mul(3).add(1)),P.element(n.mul(3).add(2))),c=LF(P.element(l.mul(3)),P.element(l.mul(3).add(1)),P.element(l.mul(3).add(2))),d=LF(P.element(h.mul(3)),P.element(h.mul(3).add(1)),P.element(h.mul(3).add(2))),p=a.mul(FF(u,SF(1))).xyz,m=a.mul(FF(c,SF(1))).xyz,f=a.mul(FF(d,SF(1))).xyz,g=m.sub(p),y=f.sub(p),x=TF(g,y),b=x.dot(x);bF(b.lessThan(SF(4e-16*VF)),()=>{yF()}),bF(x.y.lessThan(0),()=>{yF()});const _=CF(p.y,CF(m.y,f.y));_F({start:NF(0),end:s.toInt(),type:"int",condition:"<",name:"edgeIdx"},({edgeIdx:e})=>{const s=t.add(e.toUint()),i=s.mul(6),r=LF(o.element(i),o.element(i.add(1)),o.element(i.add(2))),n=LF(o.element(i.add(3)),o.element(i.add(4)),o.element(i.add(5))),a=RF(r.y,n.y);bF(_.lessThanEqual(a),()=>{yF()});const l=BF(x),h=l.dot(p).negate(),u=l.y.lessThan(0),c=IF(u,l.negate(),l),d=IF(u,h.negate(),h),g=c.dot(r).add(d),y=c.dot(n).add(d),b=g.lessThan(0),w=y.lessThan(0),v=wF(g).lessThan(SF(OF)),T=b.not().and(w.not()),S=y.sub(g),M=wF(S).lessThan(SF(OF)),A=M.and(v.or(b.not()));bF(A,()=>{yF()}),bF(T.and(M.not()),()=>{yF()});const N=g.negate().div(S),E=PF(r,n,N),R=LF(IF(M.or(b),r.x,E.x),IF(M.or(b),r.y,E.y),IF(M.or(b),r.z,E.z)),P=LF(IF(M.or(w),n.x,E.x),IF(M.or(w),n.y,E.y),IF(M.or(w),n.z,E.z)),B=P.sub(R),I=B.dot(B);bF(I.lessThan(SF(OF)),()=>{yF()});const D=r.sub(p),O=r.sub(m),V=r.sub(f),z=n.sub(p),k=n.sub(m),U=n.sub(f),G=D.dot(D).lessThanEqual(SF(OF)),j=O.dot(O).lessThanEqual(SF(OF)),$=V.dot(V).lessThanEqual(SF(OF)),W=z.dot(z).lessThanEqual(SF(OF)),H=k.dot(k).lessThanEqual(SF(OF)),q=U.dot(U).lessThanEqual(SF(OF)),X=G.or(j).or($),Y=W.or(H).or(q),Z=X.and(Y);bF(Z,()=>{yF()});const Q=LF(p.x,SF(0),p.z),K=LF(m.x,SF(0),m.z),J=LF(f.x,SF(0),f.z),ee=LF(R.x,SF(0),R.z),te=LF(P.x,SF(0),P.z),se=LF(r.x,SF(0),r.z),ie=LF(n.x,SF(0),n.z).sub(se),re=ie.dot(ie);bF(re.lessThan(SF(OF)),()=>{yF()});const ne=re.sqrt(),oe=K.sub(Q),ae=J.sub(Q),le=TF(oe,ae),he=le.dot(le);bF(he.lessThanEqual(SF(4e-16*VF)),()=>{yF()});const ue=te.sub(ee),ce=ue.dot(ue);bF(ce.lessThan(SF(OF)),()=>{yF()});const de=ce.sqrt(),pe=ue.div(de),me=ie.div(ne),fe=BF(le),ge=TF(pe,fe),ye=SF(0).toVar(),xe=SF(0).toVar(),be=SF(0).toVar(),_e=SF(0).toVar(),we=DF(0).toVar(),ve=ge.dot(Q.sub(ee)),Te=ge.dot(K.sub(ee)),Se=wF(ve).lessThan(SF(zF)),Me=wF(Te).lessThan(SF(zF)),Ae=Se.not().and(Me.not()).and(ve.mul(Te).lessThan(0));bF(Ae,()=>{const e=ve.div(ve.sub(Te)),t=PF(Q.x,K.x,e),s=PF(Q.z,K.z,e);bF(we.equal(0),()=>{ye.assign(t),xe.assign(s)}).Else(()=>{be.assign(t),_e.assign(s)}),we.addAssign(1)}).ElseIf(Se,()=>{bF(we.equal(0),()=>{ye.assign(Q.x),xe.assign(Q.z)}).Else(()=>{be.assign(Q.x),_e.assign(Q.z)}),we.addAssign(1)});const Ne=Te,Ee=ge.dot(J.sub(ee)),Ce=Me,Re=wF(Ee).lessThan(SF(zF)),Pe=Ce.not().and(Re.not()).and(Ne.mul(Ee).lessThan(0));bF(we.lessThan(2),()=>{bF(Pe,()=>{const e=Ne.div(Ne.sub(Ee)),t=PF(K.x,J.x,e),s=PF(K.z,J.z,e);bF(we.equal(0),()=>{ye.assign(t),xe.assign(s)}).Else(()=>{be.assign(t),_e.assign(s)}),we.addAssign(1)}).ElseIf(Ce.and(Ae.not()).and(Se.not()),()=>{bF(we.equal(0),()=>{ye.assign(K.x),xe.assign(K.z)}).Else(()=>{be.assign(K.x),_e.assign(K.z)}),we.addAssign(1)})});const Be=Ee,Ie=ve,De=Re,Le=Se,Fe=De.not().and(Le.not()).and(Be.mul(Ie).lessThan(0));bF(we.lessThan(2),()=>{bF(Fe,()=>{const e=Be.div(Be.sub(Ie)),t=PF(J.x,Q.x,e),s=PF(J.z,Q.z,e);bF(we.equal(0),()=>{ye.assign(t),xe.assign(s)}).Else(()=>{be.assign(t),_e.assign(s)}),we.addAssign(1)}).ElseIf(De.and(Pe.not()).and(Ce.not()),()=>{bF(we.equal(0),()=>{ye.assign(J.x),xe.assign(J.z)}).Else(()=>{be.assign(J.x),_e.assign(J.z)}),we.addAssign(1)})}),bF(we.notEqual(2),()=>{yF()});const Oe=LF(ye,SF(0),xe),Ve=LF(be,SF(0),_e).sub(Oe).dot(pe),ze=LF(ye,SF(0),xe).toVar(),ke=LF(be,SF(0),_e).toVar();bF(Ve.lessThan(0),()=>{const e=ye,t=xe;ze.x.assign(be),ze.z.assign(_e),ke.x.assign(e),ke.z.assign(t)});const Ue=SF(0),Ge=de,je=ze.sub(ee).dot(pe),$e=ke.sub(ee).dot(pe),We=Ge.lessThanEqual(je).or($e.lessThanEqual(Ue));bF(We,()=>{yF()});const He=CF(Ue,je),qe=RF(Ge,$e),Xe=ee.add(pe.mul(He)),Ye=ee.add(pe.mul(qe)),Ze=Xe.sub(se).dot(me).div(ne),Qe=Ye.sub(se).dot(me).div(ne),Ke=CF(SF(0),RF(SF(1),Ze)),Je=CF(SF(0),RF(SF(1),Qe)),et=wF(Je.sub(Ke));bF(et.lessThanEqual(SF(zF)),()=>{yF()});const tt=vF(L.element(0),1);bF(tt.lessThan(DF(C)),()=>{const e=tt.mul(3);F.element(e).assign(s.toFloat()),F.element(e.add(1)).assign(Ke),F.element(e.add(2)).assign(Je)})})})})().compute(M.length);d+=performance.now()-O;const z=performance.now();await n.computeAsync(V),l+=performance.now()-z;const k=performance.now(),U=await n.getArrayBufferAsync(L.value),G=new Uint32Array(U)[0];if(r&&(r.used+=Math.min(G,C)),qr.enabled&&console.log(` Batch ${s+1}: ${G} overlaps found (capacity: ${C})`),G>C&&qr.enabled&&console.warn(` WARNING: Overlap buffer overflow! ${G} > ${C}. Some occlusion data lost.`),G>0){const e=await n.getArrayBufferAsync(F.value),t=new Float32Array(e);h+=performance.now()-k;const s=performance.now(),r=Math.min(G,C);for(let e=0;e<r;e++){const s=3*e,r=Math.round(t[s]);Lr([t[s+1],t[s+2]],i[r])}u+=performance.now()-s,qr.enabled&&console.log(` Processed ${r} overlaps into hiddenOverlapMap`)}else h+=performance.now()-k}n.dispose(),UF=null;const p=c+d+l+h+u;qr.enabled&&(console.log(`WebGPU timing breakdown (total: ${p.toFixed(1)}ms):`),console.log(` Buffer creation: ${c.toFixed(1)}ms`),console.log(` Shader build: ${d.toFixed(1)}ms`),console.log(` GPU compute: ${l.toFixed(1)}ms`),console.log(` Readback: ${h.toFixed(1)}ms`),console.log(` CPU merge: ${u.toFixed(1)}ms`))}const jF=new i.Vector3(0,1,0);function $F(e,t=null){const s=new Float32Array(6*e.length);let r=0;for(let t=0,i=e.length;t<i;t++){const i=e[t];s[r++]=i[0],s[r++]=0,s[r++]=i[2],s[r++]=i[3],s[r++]=0,s[r++]=i[5]}const n=new i.BufferGeometry,o=new i.BufferAttribute(s,3,!0);if(n.setAttribute("position",o),t){const s=new Float32Array(2*e.length);for(let e=0,i=t.length;e<i;e++)s[2*e]=t[e],s[2*e+1]=t[e];n.setAttribute("group",new i.BufferAttribute(s,1))}return n}class WF{constructor(e,t=!0){this.meshes=hr(e),this.bvhs=new Map,this.visibleEdges=[],this.hiddenEdges=[],this.visibleGroupIndices=[],this.hiddenGroupIndices=[],this.groupKeyToIndex=null,this.hasGroups=!1,this.iterationTime=30,this.useWebGPU=t}reset(){this.visibleEdges.length=0,this.hiddenEdges.length=0,this.visibleGroupIndices.length=0,this.hiddenGroupIndices.length=0,this.groupKeyToIndex=null,this.hasGroups=!1}getVisibleLineGeometry(){return $F(this.visibleEdges,this.groupKeyToIndex?this.visibleGroupIndices:null)}getHiddenLineGeometry(){return $F(this.hiddenEdges,this.groupKeyToIndex?this.hiddenGroupIndices:null)}getGroupKeys(){return this.groupKeyToIndex?Object.fromEntries(this.groupKeyToIndex):{}}addEdges(...e){const t=this.iterationTime;this.iterationTime=1/0;const s=this.addEdgesGenerator(...e).next().value;return this.iterationTime=t,s}*addEdgesGenerator(e,t={}){const{meshes:s,bvhs:i,visibleEdges:r,hiddenEdges:n,iterationTime:o}=this;let a=performance.now();qr.startStep("Building mesh BVH");for(let e=0;e<s.length;e++){performance.now()-a>o&&(yield,a=performance.now());const t=s[e].geometry;if(!i.has(t)){const e=t.boundsTree||new Mi(t);i.set(t,e)}}let l=0;for(let e=0;e<s.length;e++){const t=s[e].geometry;l+=t.index?t.index.count/3:t.attributes.position.count/3}const h={};for(let t=0;t<e.length;t++)h[t]=[];qr.startStep("Building line BVH");const u=new fr(e,{maxLeafSize:2,strategy:2});qr.startStep("BVHcast overlaps"),a=performance.now();const c={candidates:0,backFaceCulled:0,yBoundsCulled:0,xzBoundsCulled:0,triangleEdgeCulled:0,planeTrimCulled:0,distThresholdCulled:0,noOverlapCulled:0,used:0,totalEdges:e.length,totalTriangles:l},d=this.useWebGPU,p={};d&&(p._edgeOffsets=[],p._edgeCounts=[],p._meshOffsets=[],p._meshCounts=[],p._meshIndex=[],p.groupCount=0);for(let e=0;e<s.length;e++){performance.now()-a>o&&(t.onProgress&&t.onProgress(e,s.length),yield,a=performance.now());const r=s[e];d?kF(u,i.get(r.geometry),r,p,e):kr(u,i.get(r.geometry),r,h,c)}if(d){let e=!1;for(GF(p,s,u,h,c).then(()=>{e=!0});!e;)yield}const m=c.totalEdges*c.totalTriangles;if(qr.setStat("Total edges",c.totalEdges.toLocaleString()),qr.setStat("Total triangles",c.totalTriangles.toLocaleString()),qr.setStat("Brute-force pairs (edges × triangles)",m.toLocaleString()),qr.setStat("BVH candidate pairs",c.candidates.toLocaleString()),m>0&&qr.setStat("BVH reduction",(c.candidates/m*100).toFixed(3)+"% of brute-force"),c.candidates>0){const e=c.candidates,t=t=>(t/e*100).toFixed(2)+"%";d||(qr.setStat("Rejected: back-face culling",c.backFaceCulled.toLocaleString()+" ("+t(c.backFaceCulled)+")"),qr.setStat("Rejected: Y-bounds (tri below edge)",c.yBoundsCulled.toLocaleString()+" ("+t(c.yBoundsCulled)+")"),qr.setStat("Rejected: XZ-bounds (no 2D overlap)",c.xzBoundsCulled.toLocaleString()+" ("+t(c.xzBoundsCulled)+")"),qr.setStat("Rejected: edge lies on triangle",c.triangleEdgeCulled.toLocaleString()+" ("+t(c.triangleEdgeCulled)+")"),qr.setStat("Rejected: line above tri plane",c.planeTrimCulled.toLocaleString()+" ("+t(c.planeTrimCulled)+")"),qr.setStat("Rejected: trimmed edge too small",c.distThresholdCulled.toLocaleString()+" ("+t(c.distThresholdCulled)+")"),qr.setStat("Rejected: no projected overlap",c.noOverlapCulled.toLocaleString()+" ("+t(c.noOverlapCulled)+")")),qr.setStat("Producing overlaps",c.used.toLocaleString()+" ("+t(c.used)+")")}qr.startStep("Converting overlaps to lines");const f=this.hasGroups;for(let t=0;t<e.length;t++){performance.now()-a>o&&(yield,a=performance.now());const s=e[t],i=h[t],l=r.length,u=n.length;if(Ji(s,i,!1,r),Ji(s,i,!0,n),f){const e=s.groupIndex;for(let t=l;t<r.length;t++)this.visibleGroupIndices.push(e);for(let t=u;t<n.length;t++)this.hiddenGroupIndices.push(e)}}}}class HF{constructor(){this.iterationTime=30,this.angleThreshold=50,this.includeIntersectionEdges=!0,this.useWebGPU=!0}generateAsync(e,t={}){return new Promise((s,i)=>{const{signal:r}=t,n=this.generate(e,t);!function e(){if(r&&r.aborted)return void i(new Error("ProjectionGenerator: Process aborted via AbortSignal."));const t=n.next();t.done?s(t.value):requestAnimationFrame(e)}()})}*generate(e,t){const{iterationTime:s,angleThreshold:r,includeIntersectionEdges:n}=this,{onProgress:o=()=>{},visibilityCuller:a=null,groupFn:l=null}=t;if(qr.reset(),qr.startTotal(),e.isBufferGeometry&&(e=new i.Mesh(e)),a){qr.startStep("Visibility culling");let t=!1;for(a.cull(e).then(s=>{(e=new i.Scene).children=s,t=!0});!t;)yield}const h=new pr;h.iterationTime=s,h.thresholdAngle=r,h.projectionDirection.copy(jF),qr.startStep("Generating candidate edges"),o("Generating candidate edges");let u=[],c=l?[]:null;if(yield*h.getEdgesGenerator(e,u,c),n&&(qr.startStep("Generating intersection edges"),o("Generating intersection edges"),yield*h.getIntersectionEdgesGenerator(e,u,c)),qr.startStep("Pre-filtering edges"),o("Pre-filtering edges"),c){const e=[],t=[];for(let s=0;s<u.length;s++)Zi(u[s])||(e.push(u[s]),t.push(c[s]));u=e,c=t}else u=u.filter(e=>!Zi(e));yield;const d=new WF(e,this.useWebGPU);if(d.iterationTime=s,l&&c){const e=new Map;for(let t=0;t<u.length;t++){const s=l(c[t]);e.has(s)||e.set(s,e.size),u[t].groupIndex=e.get(s)}d.groupKeyToIndex=e,d.hasGroups=!0}return o("Building BVH & computing overlaps"),yield*d.addEdgesGenerator(u,{onProgress:o?(e,t)=>{o("Building BVH & computing overlaps",e/t,d)}:null}),qr.printSummary(),d}}new i.Line3,new i.Line3,new i.Vector3;const qF=class e extends d{constructor(s){super(s),t(this,"enabled",!0),t(this,"onDisposed",new u),t(this,"generator",new HF),t(this,"cullerPixelsPerMeter",.05),t(this,"projectionDirection",new l.Vector3(0,-1,0)),t(this,"nearPlane",-1/0),t(this,"farPlane",1/0),this.components.add(e.uuid,this),this.generator.includeIntersectionEdges=!1}async get(e,t,s){const i=this.components.get(ji),r=new l.Group,n=new Map;for(const[t,s]of Object.entries(e)){const e=i.list.get(t);if(!e)continue;const o=(await e.getItemsIdsWithGeometry()).filter(e=>s.has(e));if(0===o.length)continue;const a=await e.getItemsGeometry(o);for(const s in a){const i=a[s];for(const s of i){if(!(s.positions&&s.indices&&s.transform&&s.representationId))continue;const i=s.representationId;if(!n.has(i)){const e=new l.BufferGeometry;e.setAttribute("position",new l.Float32BufferAttribute(s.positions,3)),s.normals&&e.setAttribute("normal",new l.Float32BufferAttribute(s.normals,3)),e.setIndex(Array.from(s.indices)),n.set(i,e)}const o=n.get(i),a=new l.Mesh(o);a.applyMatrix4(s.transform),a.applyMatrix4(e.object.matrixWorld),a.updateWorldMatrix(!0,!0),a.userData._edgeProjectorModelId=t,a.userData._edgeProjectorLocalId=s.localId,r.add(a)}}}const o=this.projectionDirection.clone().normalize(),a=new l.Vector3(0,-1,0),h=(new l.Quaternion).setFromUnitVectors(o,a),u=(new l.Matrix4).makeRotationFromQuaternion(h),c=u.clone().invert();for(const e of r.children)e.applyMatrix4(u),e.updateWorldMatrix(!1,!1);if(r.traverse(e=>{const t=e;if(t.geometry&&!t.geometry.boundsTree){const e=t.geometry.index?t.geometry.index.count:t.geometry.attributes.position.count;t.geometry.groups.forEach(t=>{t.count===1/0&&(t.count=e-t.start)}),t.geometry.boundsTree=new Mi(t.geometry,{maxLeafSize:1,strategy:2})}}),this.nearPlane!==-1/0||this.farPlane!==1/0){const e=new l.Box3,t=[];for(const s of r.children){const i=s;i.geometry&&(e.setFromObject(i),(e.max.y<this.nearPlane||e.min.y>this.farPlane)&&t.push(i))}for(const e of t)r.remove(e)}const d=t.renderer.three,p=new Wi(d,{pixelsPerMeter:this.cullerPixelsPerMeter}),m=await this.generator.generateAsync(r,{visibilityCuller:p,groupFn:e=>`${e.userData._edgeProjectorModelId??"unknown"}:${e.userData._edgeProjectorLocalId??0}`,onProgress:null==s?void 0:s.onProgress}),f=m.getVisibleLineGeometry(),g=m.getHiddenLineGeometry();f.applyMatrix4(c),g.applyMatrix4(c);const y=m.getGroupKeys(),x={};for(const[e,t]of Object.entries(y)){const s=e.lastIndexOf(":"),i=e.substring(0,s),r=Number(e.substring(s+1));x[t]={modelId:i,localId:r}}for(const e of n.values())e.dispose();return{visible:f,hidden:g,groups:x}}dispose(){this.onDisposed.trigger(e.uuid),this.onDisposed.reset()}};t(qF,"uuid","f2e76c3a-8b1d-4d5e-9a3f-7c6b2d4e8f1a");let XF=qF;class YF{constructor(){t(this,"wasm",{path:"",absolute:!1,logLevel:h.LogLevel.LOG_LEVEL_OFF}),t(this,"webIfc",{COORDINATE_TO_ORIGIN:!0}),t(this,"autoSetWasm",!0),t(this,"customLocateFileHandler",null)}}const ZF=class e extends d{constructor(s){super(s),t(this,"onDisposed",new u),t(this,"onIfcStartedLoading",new u),t(this,"onIfcImporterInitialized",new u),t(this,"onSetup",new u),t(this,"settings",new YF),t(this,"webIfc",new h.IfcAPI),t(this,"enabled",!0),this.components.add(e.uuid,this)}dispose(){this.webIfc=null,this.onDisposed.trigger(e.uuid),this.onDisposed.reset()}async setup(e){this.settings={...this.settings,...e},this.settings.autoSetWasm&&await this.autoSetWasm(),this.onSetup.trigger()}async load(e,t,s,i){const r=this.components.get(ji);if(!r.initialized)throw new Error("You need to initialize fragments first.");this.settings.autoSetWasm&&await this.autoSetWasm(),r.core.settings.autoCoordinate=t;const n=new a.IfcImporter;n.wasm.path=this.settings.wasm.path,n.wasm.absolute=this.settings.wasm.absolute,n.webIfcSettings=this.settings.webIfc,this.onIfcImporterInitialized.trigger(n),(null==i?void 0:i.instanceCallback)&&i.instanceCallback(n);const o=await n.process({...null==i?void 0:i.processData,bytes:e});return await r.core.load(o,{modelId:s,userData:null==i?void 0:i.userData})}async readIfcFile(e){const{path:t,absolute:s,logLevel:i}=this.settings.wasm;return this.webIfc.SetWasmPath(t,s),await this.webIfc.Init(this.settings.customLocateFileHandler||void 0),i&&this.webIfc.SetLogLevel(i),this.webIfc.OpenModel(e,this.settings.webIfc)}cleanUp(){try{this.webIfc.Dispose()}catch(e){console.log("Web-ifc wasn't disposed.")}this.webIfc=null,this.webIfc=new h.IfcAPI}async autoSetWasm(){const e=await fetch(`https://unpkg.com/@thatopen/components@${NO.release}/package.json`);if(!e.ok)return void console.warn("Couldn't get openbim-components package.json. Set wasm settings manually.");const t=await e.json();if("web-ifc"in t.peerDependencies){const e=t.peerDependencies["web-ifc"];this.settings.wasm.path=`https://unpkg.com/web-ifc@${e}/`,this.settings.wasm.absolute=!0}else console.warn("Couldn't get web-ifc from peer dependencies in openbim-components. Set wasm settings manually.")}};t(ZF,"uuid","a659add7-1418-4771-a0d6-7d4d438e4624");let QF=ZF;const KF=class e extends d{constructor(s){super(s),t(this,"enabled",!0),this.components.add(e.uuid,this)}async set(e,t){const s=this.components.get(ji),i=[];if(t)for(const[r,n]of Object.entries(t)){const t=s.list.get(r);t&&i.push(t.setVisible([...n],e))}else for(const t of s.list.values())i.push(t.setVisible(void 0,e));await Promise.all(i),await s.core.update(!0)}async isolate(e){await Promise.all([this.set(!1),this.set(!0,e)])}async toggle(e){const t=[],s=this.components.get(ji);for(const[i,r]of Object.entries(e)){const e=s.list.get(i);e&&t.push(e.toggleVisible([...r]))}await Promise.all(t),await s.core.update(!0)}async getVisibilityMap(e,t){const s=[],i=[],r=this.components.get(ji);if(t)for(const n of t){const t=r.list.get(n);t&&(s.push(t.modelId),i.push(t.getItemsByVisibility(e)))}else for(const t of r.list.values())s.push(t.modelId),i.push(t.getItemsByVisibility(e));const n=await Promise.all(i),o={};for(const[e,t]of s.entries())o[t]=n[e];return o}};t(KF,"uuid","dd9ccf2d-8a21-4821-b7f6-2949add16a29");let JF=KF;const eO=class e extends d{constructor(s){super(s),t(this,"enabled",!0),t(this,"onDisposed",new u),t(this,"list",new a.DataSet),this.components.add(e.uuid,this)}dispose(t=!0){this.list.clear(),this.onDisposed.trigger(e.uuid),t&&(this.onDisposed.reset(),this.list.eventsEnabled=!1,this.list.dispose())}get(){const e=new l.Box3;for(const t of this.list)e.union(t);return e}async addFromModelIdMap(e){const t=this.components.get(ji),s=new l.Box3;for(const[i,r]of Object.entries(e)){const e=t.list.get(i);if(!e)continue;const n=await e.getMergedBox([...r]);s.union(n)}this.list.add(s)}addFromModels(e){const t=this.components.get(ji);for(const[s,i]of t.list)e&&!e.some(e=>e.test(s))||this.list.add(i.box)}async getCenter(e){this.list.clear(),await this.addFromModelIdMap(e);const t=this.get();this.list.clear();const s=new l.Vector3;return t.getCenter(s),s}async getCameraOrientation(e,t=1){const s=this.components.get(ji);this.list.clear();for(const[e,t]of s.list)this.list.add(t.box);const i=this.get();this.list.clear();const r=new l.Vector3;i.getCenter(r);const n=new l.Vector3;i.getSize(n);const o=Math.max(n.x,n.y,n.z)*t,a=new l.Vector3;switch(e){case"front":default:a.set(r.x,r.y,r.z+o);break;case"back":a.set(r.x,r.y,r.z-o);break;case"left":a.set(r.x-o,r.y,r.z);break;case"right":a.set(r.x+o,r.y,r.z);break;case"top":a.set(r.x,r.y+o,r.z);break;case"bottom":a.set(r.x,r.y-o,r.z)}return{position:a,target:r}}};t(eO,"uuid","d1444724-dba6-4cdd-a0c7-68ee1450d166");let tO=eO;class sO{constructor(e,s){t(this,"name","Query"),t(this,"customData",{}),t(this,"_components"),t(this,"_queries",[]),t(this,"_aggregation","exclusive"),t(this,"result",null),t(this,"cache",!0),t(this,"serializeQueryParameters",e=>{var t;return{categories:null==(t=e.categories)?void 0:t.map(e=>e.source),attributes:e.attributes?{aggregation:e.attributes.aggregation,queries:e.attributes.queries.map(this.serializeAttributeQuery)}:void 0,relation:e.relation?{name:e.relation.name,query:e.relation.query?this.serializeQueryParameters(e.relation.query):void 0}:void 0}}),t(this,"deserializeQueryParameters",e=>{var t;return{categories:null==(t=e.categories)?void 0:t.map(e=>new RegExp(e)),attributes:e.attributes?{aggregation:e.attributes.aggregation,queries:e.attributes.queries.map(this.deserializeAttributeQuery)}:void 0,relation:e.relation?{name:e.relation.name,query:e.relation.query?this.deserializeQueryParameters(e.relation.query):void 0}:void 0}}),this._components=e,this.queries=s}set queries(e){this._queries=e,this.clearCache()}get queries(){return this._queries}set aggregation(e){e!==this._aggregation&&this.clearCache(),this._aggregation=e}get aggregation(){return this._aggregation}async test(e){const{modelIds:t,force:s}={force:!1,...e};if(this.result&&!s)return this.result;const i=this._components.get(rO),r=await i.getItems(this.queries,{modelIds:t,aggregation:this.aggregation});return this.cache&&(this.result=r),r}clearCache(){this.result=null}serializeAttributeQuery(e){let t;t=Array.isArray(e.value)?e.value.map(e=>e.source):e.value instanceof RegExp?e.value.source:e.value;return{name:e.name.source,value:t,type:e.type instanceof RegExp?e.type.source:e.type,negate:e.negate,itemIds:e.itemIds}}toJSON(){return{guid:this._components.get(rO).list.getKey(this)??w.create(),name:this.name,customData:this.customData,queries:this.queries.map(this.serializeQueryParameters),aggregation:this.aggregation,cache:this.cache}}deserializeAttributeQuery(e){let t;t=Array.isArray(e.value)?e.value.map(e=>new RegExp(e)):"string"==typeof e.value?new RegExp(e.value):e.value;return{name:new RegExp(e.name),value:t,type:e.type?new RegExp(e.type):void 0,negate:e.negate,itemIds:e.itemIds}}fromJSON(e){return this.name=e.name,this.customData=e.customData,this.aggregation=e.aggregation,this.cache=e.cache,this.queries=e.queries.map(this.deserializeQueryParameters),this}}const iO=class e extends d{constructor(s){super(s),t(this,"enabled",!0),t(this,"list",new a.DataMap),s.add(e.uuid,this)}async getItems(e,t){let s;if(t){const{modelIds:e,items:i}=t;if(i){const e=Object.keys(i);e.length>0&&(s=e.map(e=>new RegExp(`^${e}$`)))}else e&&(s=e)}const i=(null==t?void 0:t.aggregation)??"exclusive",r=this.components.get(ji),n=await Promise.all(e.map(async e=>{const i={};return await Promise.all(Array.from(r.list).map(async([r,n])=>{var o;if(s&&!s.some(e=>e.test(r)))return;const a=null==(o=null==t?void 0:t.items)?void 0:o[r],l=await n.getItemsByQuery(e,{localIds:a?[...a]:void 0});i[r]=new Set(l)})),i}));return"inclusive"===i?Oe.join(n):Oe.intersect(n)}create(e,t){const s=new sO(this.components,t);return this.list.set(e,s),s}async addFromCategories(e){const t=new Set,s=this.components.get(ji);for(const[i,r]of s.list){if(e&&!e.some(e=>e.test(i)))continue;const s=(await r.getItemsWithGeometryCategories()).filter(e=>null!==e),n=new Set(s);for(const e of n)this.list.has(e)||(this.create(e,[{categories:[new RegExp(`^${e}$`)]}]),t.add(e))}return[...t]}import(e){const{data:t}=e,s=[];if(!t)return s;for(const e of t){const t=this.create(e.guid,[]);t.fromJSON(e),s.push(t)}return s}export(){const e=[];for(const[t,s]of this.list.entries()){const i={...s.toJSON(),name:t};e.push(i)}return{data:e}}};t(iO,"uuid","0da7ad77-f734-42ca-942f-a074adfd1e3a");let rO=iO;const nO=class e extends d{constructor(s){super(s),t(this,"enabled",!0),t(this,"onDisposed",new u),t(this,"list",new a.DataMap),t(this,"defaultSaveFunction",e=>"value"in e.Name?e.Name.value:null),t(this,"onBeforeFragmentsDispose",async e=>{const{key:t,value:s}=e,i=await s.getLocalIds(),r={[t]:new Set(i)};this.removeItems(r)}),s.add(e.uuid,this),this.setupEvents();s.get(ji).list.onBeforeDelete.add(this.onBeforeFragmentsDispose)}setupEvents(){this.list.onBeforeDelete.add(({value:e})=>e.dispose())}getClassificationGroups(e){let t=this.list.get(e);return t||(t=new a.DataMap,this.list.set(e,t)),t}getModelItems(e,t,s){const{map:i}=this.getGroupData(e,t);let r=i[s];return r||(r=new Set,i[s]=r),r}getGroupData(e,t){const s=this.components.get(rO),i=this.getClassificationGroups(e);let r=i.get(t);return r||(r={map:{},get:()=>new Promise(e=>{if(r)if(r.query){const{name:t,config:i}=r.query,n=s.list.get(t);if(!n)throw new Error("Classifier: the query name associated with the group doesn't exist in the ItemsFinder component");n.test(i).then(t=>{if(!r)return void e({});const s=Oe.join([t,r.map]);e(s)})}else e(r.map);else e({})})},i.set(t,r)),r}async aggregateItems(e,t,s){const i=(null==s?void 0:s.data)??void 0,r=(null==s?void 0:s.aggregationCallback)??this.defaultSaveFunction,n=this.components.get(ji),o=this.components.get(rO),a=await o.getItems([t],{modelIds:null==s?void 0:s.modelIds});for(const[t,s]of Object.entries(a)){const o=n.list.get(t);if(!o)continue;const a=(s,...i)=>{const r=this.getModelItems(e,s,t);for(const e of i)r.add(e)},l=await o.getItemsData([...s],i);for(const e of l)r(e,a)}}addGroupItems(e,t,s){const{map:i}=this.getGroupData(e,t);Oe.add(i,s)}setGroupQuery(e,t,s){this.getGroupData(e,t).query=s}async find(e){const t=[];for(const[s,i]of Object.entries(e)){const e=[],r=this.list.get(s);if(!r)continue;for(const t of i){const s=r.get(t);if(!s)continue;const i=await s.get();e.push(i)}const n=Oe.join(e);t.push(n)}return Oe.intersect(t)}async aggregateItemRelations(e,t,s,i){const r=(null==i?void 0:i.attribute)??"Name",n={relations:{[s]:{attributes:!0,relations:!1}}};await this.aggregateItems(e,t,{modelIds:null==i?void 0:i.modelIds,data:n,aggregationCallback:(e,t)=>{if(!(null==e?void 0:e[r]))return;const i=e[r];if(!("value"in i))return;const n=e[s];if(Array.isArray(n))for(const e of n)"value"in e._localId&&t(i.value,e._localId.value)}})}async byIfcBuildingStorey(e){await this.aggregateItemRelations((null==e?void 0:e.classificationName)??"Storeys",{categories:[/BUILDINGSTOREY/]},"ContainsElements",{modelIds:null==e?void 0:e.modelIds})}async byCategory(e){const t=this.components.get(rO),s=await t.addFromCategories(null==e?void 0:e.modelIds);for(const t of s)this.setGroupQuery((null==e?void 0:e.classificationName)??"Categories",t,{name:t})}dispose(){this.list.clear();this.components.get(ji).list.onBeforeDelete.remove(this.onBeforeFragmentsDispose),this.onDisposed.trigger()}removeItems(e,t){if(t&&t.classificationName){const s=this.list.get(t.classificationName);if(!s)return;if(t.groupName){if(!s.get(t.groupName))return}for(const[,t]of s)Oe.remove(t.map,e);return}for(const[,t]of this.list.entries())for(const[,s]of t)Oe.remove(s.map,e)}async byModel(e){const t=this.components.get(ji),s=(null==e?void 0:e.classificationName)??"Models";for(const[i,r]of t.list){if(e&&e.modelIds&&!e.modelIds.some(e=>e.test(i)))continue;const t=await r.getItemsIdsWithGeometry(),n={[i]:new Set(t)};this.getGroupData(s,i),this.addGroupItems(s,i,n)}}};t(nO,"uuid","e25a7f3c-46c4-4a14-9d3d-5115f24ebeb7");let oO=nO;class aO{constructor(e,s){t(this,"enabled",!0),t(this,"components"),t(this,"onDisposed",new u),t(this,"mouse"),t(this,"world"),t(this,"debugMode",!1),t(this,"colorToModelId",new Map),t(this,"modelIdToColor",new Map),t(this,"renderTarget"),t(this,"renderTargetSize",new l.Vector2),t(this,"debugCanvas"),t(this,"debugContainer"),t(this,"colorMaterials",new Map),t(this,"originalMaterials",new Map),t(this,"originalLodColors",new Map),t(this,"colorsNeedUpdate",!0);const i=s.renderer;if(!i)throw new Error("A renderer is needed for the FastModelPicker to work!");this.world=s,this.mouse=new je(i.three.domElement),this.components=e,this.setupRenderTarget(),this.setupFragmentListeners()}setupFragmentListeners(){const e=this.components.get(ji);e.list.onItemSet.add(()=>{this.colorsNeedUpdate=!0}),e.list.onItemDeleted.add(()=>{this.colorsNeedUpdate=!0})}setupRenderTarget(){const e=this.world.renderer.three.getSize(new l.Vector2);this.renderTargetSize.copy(e),this.renderTarget=new l.WebGLRenderTarget(e.x,e.y),this.renderTarget.texture.format=l.RGBAFormat,this.renderTarget.texture.type=l.UnsignedByteType,this.debugMode&&this.setupDebugCanvas(),this.world.renderer.onResize.add(e=>{this.renderTargetSize.copy(e),this.renderTarget.setSize(e.x,e.y),this.debugCanvas&&(this.debugCanvas.width=e.x,this.debugCanvas.height=e.y)})}setupDebugCanvas(){if(this.debugCanvas)return;const e=this.world.renderer.three.getSize(new l.Vector2);this.debugContainer=document.createElement("div"),this.debugContainer.style.position="fixed",this.debugContainer.style.top="10px",this.debugContainer.style.right="10px",this.debugContainer.style.width="300px",this.debugContainer.style.height="300px",this.debugContainer.style.border="2px solid #fff",this.debugContainer.style.backgroundColor="#000",this.debugContainer.style.zIndex="10000",this.debugContainer.style.pointerEvents="none",this.debugCanvas=document.createElement("canvas"),this.debugCanvas.width=e.x,this.debugCanvas.height=e.y,this.debugCanvas.style.width="100%",this.debugCanvas.style.height="100%",this.debugCanvas.style.imageRendering="pixelated",this.debugContainer.appendChild(this.debugCanvas),document.body.appendChild(this.debugContainer)}generateColorForModel(e){let t=0;for(let s=0;s<e.length;s++)t=(t<<5)-t+e.charCodeAt(s),t&=t;let s=Math.abs(t)%16777215;0===s&&(s=1);const i=s>>16&255||1,r=s>>8&255||1,n=255&s||1;return new l.Color(i/255,r/255,n/255)}colorToId(e){return Math.round(255*e.r)<<16|Math.round(255*e.g)<<8|Math.round(255*e.b)}assignColors(){const e=this.components.get(ji);if(e.initialized){if(!this.colorsNeedUpdate){const t=new Set(e.list.keys()),s=new Set(this.modelIdToColor.keys());(t.size!==s.size||[...t].some(e=>!s.has(e)))&&(this.colorsNeedUpdate=!0)}if(this.colorsNeedUpdate){this.colorToModelId.clear(),this.modelIdToColor.clear();for(const e of this.colorMaterials.values())e.dispose();this.colorMaterials.clear();for(const[t]of e.list){const e=this.generateColorForModel(t),s=this.colorToId(e);this.colorToModelId.set(s,t),this.modelIdToColor.set(t,e);const i=new l.MeshBasicMaterial({color:e,depthTest:!0,depthWrite:!0});this.colorMaterials.set(t,i)}this.colorsNeedUpdate=!1}}}applyColorMaterials(){const e=this.components.get(ji);if(e.initialized)for(const[t,s]of e.list){const e=this.colorMaterials.get(t);e&&s.object.traverse(t=>{if(t instanceof l.Mesh){if("isLODGeometry"in t.geometry){const s=t.material[0].uniforms.lodColor;return this.originalLodColors.has(s)||this.originalLodColors.set(s,s.value),void(s.value=e.color)}this.originalMaterials.has(t)||this.originalMaterials.set(t,t.material),t.material=e}})}}restoreOriginalMaterials(){for(const[e,t]of this.originalMaterials)e.material=t;for(const[e,t]of this.originalLodColors)e.value=t;this.originalMaterials.clear()}renderColorCoded(){if(!this.renderTarget||!this.world.renderer)throw new Error("Render target not initialized!");const e=this.world.renderer.three,t=this.world.scene.three,s=this.world.camera.three,i=e.getRenderTarget(),r=e.autoClear,n=new l.Color,o=e.getClearAlpha();e.getClearColor(n),this.applyColorMaterials(),e.setRenderTarget(this.renderTarget),e.autoClear=!0,e.setClearColor(0,1),e.clear(!0,!0,!1),e.render(t,s),e.setRenderTarget(i),e.autoClear=r,e.setClearColor(n,o),this.restoreOriginalMaterials(),this.debugMode&&this.debugCanvas&&this.updateDebugCanvas()}updateDebugCanvas(){if(!this.debugCanvas||!this.renderTarget||!this.world.renderer)return;const e=this.world.renderer.three,t=this.renderTargetSize,s=new Uint8Array(t.x*t.y*4);e.readRenderTargetPixels(this.renderTarget,0,0,t.x,t.y,s);const i=this.debugCanvas.getContext("2d");if(!i)return;const r=i.createImageData(t.x,t.y),n=4*t.x;for(let e=0;e<t.y;e++){const i=e*n,o=(t.y-1-e)*n;r.data.set(s.subarray(i,i+n),o)}i.putImageData(r,0,0)}async getModelAt(e){if(!this.renderTarget||!this.world.renderer)throw new Error("Render target not initialized!");const t=this.components.get(ji);if(!t.initialized||0===t.list.size)return null;this.assignColors(),this.renderColorCoded();const s=e||this.mouse.position,i=this.renderTargetSize,r=Math.floor(.5*(s.x+1)*i.x),n=Math.floor(.5*(s.y+1)*(i.y-1)),o=Math.max(0,Math.min(i.x-1,r)),a=Math.max(0,Math.min(i.y-1,n)),l=this.world.renderer.three,h=new Uint8Array(4);l.readRenderTargetPixels(this.renderTarget,o,a,1,1,h);const u=h[0]<<16|h[1]<<8|h[2];return this.colorToModelId.get(u)||null}setDebugMode(e){this.debugMode=e,e?this.setupDebugCanvas():this.removeDebugCanvas()}removeDebugCanvas(){this.debugContainer&&(this.debugContainer.remove(),this.debugContainer=void 0,this.debugCanvas=void 0)}dispose(){this.mouse.dispose(),this.removeDebugCanvas();for(const e of this.colorMaterials.values())e.dispose();this.colorMaterials.clear(),this.renderTarget&&this.renderTarget.dispose(),this.colorToModelId.clear(),this.modelIdToColor.clear(),this.originalMaterials.clear(),this.originalLodColors.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}}const lO=class e extends d{constructor(s){super(s),t(this,"enabled",!0),t(this,"list",new Map),t(this,"onDisposed",new u),s.add(e.uuid,this)}get(e){if(this.list.has(e.uuid))return this.list.get(e.uuid);const t=new aO(this.components,e);return this.list.set(e.uuid,t),e.onDisposed.add(()=>{this.delete(e)}),t}delete(e){const t=this.list.get(e.uuid);t&&t.dispose(),this.list.delete(e.uuid)}dispose(){for(const[e,t]of this.list)t.dispose();this.list.clear(),this.onDisposed.trigger()}};t(lO,"uuid","4a82430c-7ff2-49ea-9401-60807502dad6");let hO=lO;class uO{constructor(e,s){t(this,"enabled",!0),t(this,"components"),t(this,"onDisposed",new u),t(this,"mouse"),t(this,"three",new l.Raycaster),t(this,"world"),t(this,"useFastModelPicking",!1);const i=s.renderer;if(!i)throw new Error("A renderer is needed for the raycaster to work!");this.world=s,this.mouse=new je(i.three.domElement),this.components=e}dispose(){this.mouse.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}castRayToObjects(e=Array.from(this.world.meshes),t=this.mouse.position){if(!this.world)throw new Error("A world is needed to cast rays!");const s=this.world.camera.three;return this.three.setFromCamera(t,s),this.intersect(e)}async castRay(e){const t=null==e?void 0:e.snappingClasses,s=(null==e?void 0:e.items)??Array.from(this.world.meshes),i=(null==e?void 0:e.position)??this.mouse.position;if(!this.world)throw new Error("A world is needed to cast rays!");const r=this.world.camera.three,n=this.components.get(ji),o=this.world.renderer.three.domElement,a=this.mouse.rawPosition;let l=null;if(n.initialized){if(this.useFastModelPicking){const e=this.components.get(hO).get(this.world),s=await e.getModelAt(i);if(s){const e=n.list.get(s);if(e)if(t&&t.length>0){const s=await e.raycastWithSnapping({camera:r,dom:o,mouse:a,snappingClasses:t});l=s&&s.length>0?s[0]:await e.raycast({camera:r,dom:o,mouse:a})}else l=await e.raycast({camera:r,dom:o,mouse:a})}}else l=await n.raycast({camera:r,dom:o,mouse:a,snappingClasses:t});if(0===s.length)return l}this.three.setFromCamera(i,r);const h=this.intersect(s);return l?h&&h.distance<l.distance?h:l:h}castRayFromVector(e,t,s=Array.from(this.world.meshes)){return this.three.set(e,t),this.intersect(s)}intersect(e=Array.from(this.world.meshes)){const t=this.three.intersectObjects(e),s=this.filterClippingPlanes(t);return s.length>0?s[0]:null}filterClippingPlanes(e){if(!this.world.renderer)throw new Error("Renderer not found!");const t=this.world.renderer.three;if(!t.clippingPlanes)return e;const s=t.clippingPlanes;return e.length<=0||!s||(null==s?void 0:s.length)<=0?e:e.filter(e=>s.every(t=>t.distanceToPoint(e.point)>0))}}const cO=class e extends d{constructor(s){super(s),t(this,"enabled",!0),t(this,"list",new Map),t(this,"onDisposed",new u),s.add(e.uuid,this)}get(e){if(this.list.has(e.uuid))return this.list.get(e.uuid);const t=new uO(this.components,e);return this.list.set(e.uuid,t),e.onDisposed.add(()=>{this.delete(e)}),t}delete(e){const t=this.list.get(e.uuid);t&&t.dispose(),this.list.delete(e.uuid)}dispose(){for(const[e,t]of this.list)t.dispose();this.list.clear(),this.onDisposed.trigger()}};t(cO,"uuid","d5d8bdf0-db25-4952-b951-b643af207ace");let dO=cO;class pO extends c{constructor(){super(...arguments),t(this,"onCameraChanged",new u),t(this,"meshes",new Set),t(this,"onAfterUpdate",new u),t(this,"onBeforeUpdate",new u),t(this,"onDisposed",new u),t(this,"isDisposing",!1),t(this,"enabled",!0),t(this,"_dynamicAnchor",!1),t(this,"uuid",w.create()),t(this,"name"),t(this,"_scene"),t(this,"_camera"),t(this,"_renderer",null),t(this,"onPointerDown",async e=>{if(!this.camera.hasCameraControls())throw new Error("World: can't set dynamic anchor if the camera doesn't have controls.");const t=this.components.get(dO).get(this),s=await t.castRay();s&&s.point&&0===e.button&&this.camera.controls.setOrbitPoint(s.point.x,s.point.y,s.point.z)}),t(this,"_defaultCamera")}set dynamicAnchor(e){var t;const s=null==(t=this.renderer)?void 0:t.three.domElement.parentElement;if(!s)throw new Error("World: the renderer must have a parentElement to set dynamic anchoring.");e?(this.camera.controls&&(this.camera.controls.minDistance=.01),s.addEventListener("pointerdown",this.onPointerDown)):s.removeEventListener("pointerdown",this.onPointerDown)}get dynamicAnchor(){return this._dynamicAnchor}get defaultCamera(){if(!this._defaultCamera)throw new Error("World: there is no default camera defined.");return this._defaultCamera}set defaultCamera(e){this._defaultCamera=e}get scene(){if(!this._scene)throw new Error("No scene initialized!");return this._scene}set scene(e){this._scene=e,e.worlds.set(this.uuid,this),e.currentWorld=this,e.onWorldChanged.trigger({world:this,action:"added"})}get camera(){if(!this._camera)throw new Error("No camera initialized!");return this._camera}set camera(e){this._camera||(this.defaultCamera=e),this._camera=e,e.currentWorld=this,this.onCameraChanged.trigger(e)}get renderer(){return this._renderer}set renderer(e){this._renderer=e,e&&(e.worlds.set(this.uuid,this),e.currentWorld=this,e.onWorldChanged.trigger({world:this,action:"added"}))}useDefaultCamera(){this.camera=this.defaultCamera}update(e){this.enabled&&this._scene&&this._camera&&(this.scene.currentWorld=this,this.camera.currentWorld=this,this.renderer&&(this.renderer.currentWorld=this),this.onBeforeUpdate.trigger(),this.scene.isUpdateable()&&this.scene.update(e),this.camera.isUpdateable()&&this.camera.update(e),this.renderer&&this.renderer.update(e),this.onAfterUpdate.trigger())}dispose(e=!0){if(this.enabled=!1,this.isDisposing=!0,this.scene.onWorldChanged.trigger({world:this,action:"removed"}),this.camera.onWorldChanged.trigger({world:this,action:"removed"}),this.renderer&&this.renderer.onWorldChanged.trigger({world:this,action:"removed"}),e){const e=this.components.get(y);this.scene.dispose(),this.camera.isDisposeable()&&this.camera.dispose(),this.renderer&&this.renderer.dispose();for(const t of this.meshes)e.destroy(t);this.meshes.clear()}this._scene=null,this._camera=null,this._renderer=null;this.components.get(wO).list.delete(this.uuid),this.onDisposed.trigger(),this.onDisposed.reset()}}class mO{constructor(e,s){t(this,"_list"),t(this,"_scene"),this._list=e,this._scene=s}get color(){return this._list.directionalLight.color.value}set color(e){this._list.directionalLight.color.value=e;for(const[,t]of this._scene.directionalLights)t.color.copy(e)}get intensity(){return this._list.directionalLight.intensity.value}set intensity(e){this._list.directionalLight.intensity.value=e;for(const[,t]of this._scene.directionalLights)t.intensity=e}get position(){return this._list.directionalLight.position.value.clone()}set position(e){this._list.directionalLight.position.value=e;for(const[,t]of this._scene.directionalLights)t.position.copy(e)}}class fO{constructor(e,s){t(this,"_list"),t(this,"_scene"),this._list=e,this._scene=s}get color(){return this._list.ambientLight.color.value}set color(e){this._list.ambientLight.color.value=e;for(const[,t]of this._scene.ambientLights)t.color.copy(e)}get intensity(){return this._list.ambientLight.intensity.value}set intensity(e){this._list.ambientLight.intensity.value=e;for(const[,t]of this._scene.ambientLights)t.intensity=e}}class gO extends ke{constructor(){super(...arguments),t(this,"_config",{backgroundColor:{value:new l.Color,type:"Color"},ambientLight:{color:{type:"Color",value:new l.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2}},directionalLight:{color:{type:"Color",value:new l.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2},position:{type:"Vector3",value:new l.Vector3}}}),t(this,"ambientLight",new fO(this._config,this._component)),t(this,"directionalLight",new mO(this._config,this._component))}get backgroundColor(){return this._config.backgroundColor.value}set backgroundColor(e){this._config.backgroundColor.value=e,this._component.three.background=e}}class yO extends x{constructor(e){super(e),t(this,"onSetup",new u),t(this,"isSetup",!1),t(this,"three"),t(this,"config",new gO(this,this.components,"Scene")),t(this,"_defaultConfig",{backgroundColor:new l.Color(2107698),directionalLight:{color:new l.Color("white"),intensity:1.5,position:new l.Vector3(5,10,3)},ambientLight:{color:new l.Color("white"),intensity:1}}),this.three=new l.Scene,this.three.background=new l.Color(2107698)}setup(e){const t={...this._defaultConfig,...e};this.config.backgroundColor=t.backgroundColor;const s=t.ambientLight;this.config.ambientLight.color=s.color,this.config.ambientLight.intensity=s.intensity;const i=t.directionalLight;this.config.directionalLight.color=i.color,this.config.directionalLight.intensity=i.intensity,this.config.directionalLight.position=i.position,this.deleteAllLights();const{color:r,intensity:n}=this.config.directionalLight,o=new l.DirectionalLight(r,n);o.position.copy(i.position);const{color:a,intensity:h}=this.config.directionalLight,u=new l.AmbientLight(a,h);this.three.add(o,u),this.directionalLights.set(o.uuid,o),this.ambientLights.set(u.uuid,u),this.isSetup=!0,this.onSetup.trigger()}dispose(){super.dispose();this.components.get(Ge).list.delete(this.config.uuid)}}var xO=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTO=1]="AUTO",e))(xO||{});class bO extends m{constructor(e){super(e),t(this,"onBeforeUpdate",new u),t(this,"onAfterUpdate",new u),t(this,"onAspectUpdated",new u),t(this,"onDisposed",new u),t(this,"three"),t(this,"_resizeObserver",null),t(this,"_allControls",new Map),t(this,"updateAspect",()=>{var e;if(this.currentWorld&&this.currentWorld.renderer)if(this.three instanceof l.OrthographicCamera)this.onAspectUpdated.trigger();else if(null==(e=this.currentWorld.renderer)?void 0:e.isResizeable()){const e=this.currentWorld.renderer.getSize();this.three.aspect=e.width/e.height,this.three.updateProjectionMatrix(),this.onAspectUpdated.trigger()}}),this.three=this.setupCamera(),this.worlds.onItemSet.add(({value:e})=>{const t=this.newCameraControls();this.setupEvents(!0),this._allControls.set(e.uuid,t)}),this.worlds.onBeforeDelete.add(({value:e})=>{var t;const s=this._allControls.get(e.uuid);s&&(s.dispose(),this._allControls.delete(e.uuid)),null==(t=this._resizeObserver)||t.disconnect()})}get controls(){if(!this.currentWorld)throw new Error("This camera needs a world to work!");const e=this._allControls.get(this.currentWorld.uuid);if(!e)throw new Error("Controls not found!");return e}get enabled(){return null!==this.currentWorld&&this.controls.enabled}set enabled(e){null!==this.currentWorld&&(this.controls.enabled=e)}set currentWorld(e){if(super.currentWorld=e,!e)return;this.worlds.get(e.uuid)||this.worlds.set(e.uuid,e)}get currentWorld(){return this._currentWorld}dispose(){this.setupEvents(!1),this.onAspectUpdated.reset(),this.onBeforeUpdate.reset(),this.onAfterUpdate.reset(),this.three.removeFromParent(),this.onDisposed.trigger(),this.onDisposed.reset();for(const[e,t]of this._allControls)t.dispose();this.worlds.clear()}async fitToItems(e){const t=await this.getItemsBounding(e);await this.controls.fitToSphere(t,!0)}async setOrbitToItems(e){const t=await this.getItemsBounding(e);this.controls.setOrbitPoint(t.center.x,t.center.y,t.center.z)}update(e){this.enabled&&(this.onBeforeUpdate.trigger(this),this.controls.update(e),this.onAfterUpdate.trigger(this))}async getItemsBounding(e){const t=this.components.get(ji),s=this.components.get(tO);s.list.clear();const i=new l.Sphere;if(e)await s.addFromModelIdMap(e);else for(const[,e]of t.list)s.list.add(e.box);return s.get().getBoundingSphere(i),s.list.clear(),i}setupCamera(){const e=window.innerWidth/window.innerHeight,t=new l.PerspectiveCamera(60,e,1,1e3);return t.position.set(50,50,50),t.lookAt(new l.Vector3(0,0,0)),t}newCameraControls(){if(!this.currentWorld)throw new Error("This camera needs a world to work!");if(!this.currentWorld.renderer)throw new Error("This camera needs a renderer to work!");n.install({THREE:bO.getSubsetOfThree()});const{domElement:e}=this.currentWorld.renderer.three,t=new n(this.three,e);return t.smoothTime=.2,t.dollyToCursor=!0,t.infinityDolly=!0,t.minDistance=6,t}setupEvents(e){if(this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),e){if(!this.currentWorld)throw new Error("This camera needs a world to work!");if(!this.currentWorld.renderer)throw new Error("This camera needs a renderer to work!");const{domElement:e}=this.currentWorld.renderer.three;this._resizeObserver=new ResizeObserver(this.updateAspect),this._resizeObserver.observe(e)}}static getSubsetOfThree(){return{MOUSE:l.MOUSE,Vector2:l.Vector2,Vector3:l.Vector3,Vector4:l.Vector4,Quaternion:l.Quaternion,Matrix4:l.Matrix4,Spherical:l.Spherical,Box3:l.Box3,Sphere:l.Sphere,Raycaster:l.Raycaster,MathUtils:l.MathUtils}}}const _O=class e extends d{constructor(i){super(i),t(this,"onAfterUpdate",new u),t(this,"onBeforeUpdate",new u),t(this,"onDisposed",new u),t(this,"list",new s.DataMap),t(this,"enabled",!0),i.add(e.uuid,this)}create(){const e=new pO(this.components),t=e.uuid;if(this.list.has(t))throw new Error("There is already a world with this name!");return this.list.set(t,e),e}delete(e){if(!this.list.has(e.uuid))throw new Error("The provided world is not found in the list!");this.list.delete(e.uuid),e.dispose()}dispose(){this.enabled=!1;for(const[e,t]of this.list)t.dispose();this.list.clear(),this.onDisposed.trigger()}update(e){if(this.enabled)for(const[t,s]of this.list)s.update(e)}};t(_O,"uuid","fdb61dc4-2ec1-4966-b83d-54ea795fad4a");let wO=_O;class vO extends ke{constructor(){super(...arguments),t(this,"_config",{visible:{value:!0,type:"Boolean"},color:{value:new l.Color,type:"Color"},primarySize:{type:"Number",interpolable:!0,value:1,min:0,max:1e3},secondarySize:{type:"Number",interpolable:!0,value:10,min:0,max:1e3},distance:{type:"Number",interpolable:!0,value:500,min:0,max:500}})}get visible(){return this._config.visible.value}set visible(e){this._config.visible.value=e,this._component.visible=e}get color(){return this._config.color.value}set color(e){this._config.color.value=e,this._component.material.uniforms.uColor.value=e,this._component.material.uniformsNeedUpdate=!0}get primarySize(){return this._config.primarySize.value}set primarySize(e){this._config.primarySize.value=e,this._component.material.uniforms.uSize1.value=e,this._component.material.uniformsNeedUpdate=!0}get secondarySize(){return this._config.secondarySize.value}set secondarySize(e){this._config.secondarySize.value=e,this._component.material.uniforms.uSize2.value=e,this._component.material.uniformsNeedUpdate=!0}get distance(){return this._config.distance.value}set distance(e){this._config.distance.value=e,this._component.material.uniforms.uDistance.value=e,this._component.material.uniformsNeedUpdate=!0}}class TO{constructor(e,s){t(this,"onDisposed",new u),t(this,"onSetup",new u),t(this,"isSetup",!1),t(this,"world"),t(this,"components"),t(this,"config"),t(this,"_defaultConfig",{visible:!0,color:new l.Color(12303291),primarySize:1,secondarySize:10,distance:500}),t(this,"three"),t(this,"_fade",3),t(this,"updateZoom",()=>{this.world.camera instanceof bO&&(this.material.uniforms.uZoom.value=this.world.camera.three.zoom)}),this.world=s;const{color:i,primarySize:r,secondarySize:n,distance:o}=this._defaultConfig;this.components=e,this.config=new vO(this,this.components,"Grid");const a=new l.PlaneGeometry(2,2,1,1),h=new l.ShaderMaterial({side:l.DoubleSide,uniforms:{uSize1:{value:r},uSize2:{value:n},uColor:{value:i},uDistance:{value:o},uFade:{value:this._fade},uZoom:{value:1}},transparent:!0,vertexShader:"\n \n varying vec3 worldPosition;\n \n uniform float uDistance;\n \n void main() {\n \n vec3 pos = position.xzy * uDistance;\n pos.xz += cameraPosition.xz;\n \n worldPosition = pos;\n \n gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);\n \n }\n ",fragmentShader:"\n \n varying vec3 worldPosition;\n \n uniform float uZoom;\n uniform float uFade;\n uniform float uSize1;\n uniform float uSize2;\n uniform vec3 uColor;\n uniform float uDistance;\n \n \n \n float getGrid(float size) {\n \n vec2 r = worldPosition.xz / size;\n \n \n vec2 grid = abs(fract(r - 0.5) - 0.5) / fwidth(r);\n float line = min(grid.x, grid.y);\n \n \n return 1.0 - min(line, 1.0);\n }\n \n void main() {\n \n \n float d = 1.0 - min(distance(cameraPosition.xz, worldPosition.xz) / uDistance, 1.0);\n \n float g1 = getGrid(uSize1);\n float g2 = getGrid(uSize2);\n \n // Ortho camera fades the grid away when zooming out\n float minZoom = step(0.2, uZoom);\n float zoomFactor = pow(min(uZoom, 1.), 2.) * minZoom;\n \n gl_FragColor = vec4(uColor.rgb, mix(g2, g1, g1) * pow(d, uFade));\n gl_FragColor.a = mix(0.5 * gl_FragColor.a, gl_FragColor.a, g2) * zoomFactor;\n \n if ( gl_FragColor.a <= 0.0 ) discard;\n \n \n }\n \n ",extensions:{derivatives:!0}});this.three=new l.Mesh(a,h),this.three.frustumCulled=!1,s.scene.three.add(this.three),this.setupEvents(!0)}get visible(){return this.three.visible}set visible(e){if(this.three.visible=e,e){this.world.scene.three.add(this.three)}else this.three.removeFromParent()}get material(){return this.three.material}get fade(){return 3===this._fade}set fade(e){this._fade=e?3:0,this.material.uniforms.uFade.value=this._fade}setup(e){const t={...this._defaultConfig,...e};this.config.visible=!0,this.config.color=t.color,this.config.primarySize=t.primarySize,this.config.secondarySize=t.secondarySize,this.config.distance=t.distance,this.isSetup=!0,this.onSetup.trigger()}dispose(){this.setupEvents(!1);this.components.get(Ge).list.delete(this.config.uuid);this.components.get(y).destroy(this.three),this.onDisposed.trigger(),this.onDisposed.reset(),this.world=null,this.components=null}setupEvents(e){if(this.world.isDisposing)return;if(!(this.world.camera instanceof bO))return;const t=this.world.camera.controls;e?t.addEventListener("update",this.updateZoom):t.removeEventListener("update",this.updateZoom)}}const SO=class e extends d{constructor(s){super(s),t(this,"list",new Map),t(this,"onDisposed",new u),t(this,"enabled",!0),s.add(e.uuid,this)}create(e){if(this.list.has(e.uuid))throw new Error("This world already has a grid!");const t=new TO(this.components,e);return this.list.set(e.uuid,t),e.onDisposed.add(()=>{this.delete(e)}),t}delete(e){const t=this.list.get(e.uuid);t&&t.dispose(),this.list.delete(e.uuid)}dispose(){for(const[e,t]of this.list)t.dispose();this.list.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}};t(SO,"uuid","d1e814d5-b81c-4452-87a2-f039375e0489");let MO=SO;const AO=class e{constructor(){t(this,"onDisposed",new u),t(this,"list",new s.DataMap),t(this,"enabled",!1),t(this,"_clock"),t(this,"onInit",new u),t(this,"update",()=>{if(!this.enabled)return;const e=this._clock.getDelta();for(const[t,s]of this.list)s.enabled&&s.isUpdateable()&&s.update(e);requestAnimationFrame(this.update)}),this._clock=new l.Clock,e.setupBVH()}add(e,t){if(this.list.has(e))throw new Error("You're trying to add a component that already exists in the components instance. Use Components.get() instead.");w.validate(e),this.list.set(e,t)}get(e){var t;const s=e.uuid;if(!this.list.has(s)){const i=new e(this);return(null==(t=i.isDisposeable)?void 0:t.call(i))&&i.onDisposed.add(()=>this.list.delete(s)),this.list.has(s)||this.add(s,i),i}return this.list.get(s)}init(){this.enabled=!0;for(const[e,t]of this.list.entries())t.enabled=!0;this._clock.start(),this.update(),this.onInit.trigger()}dispose(){let e;this.enabled=!1;for(const[t,s]of this.list)s.enabled=!1,t!==ji.uuid?s.isDisposeable()&&s.dispose():e=s;null==e||e.dispose(),this._clock.stop(),this.onDisposed.trigger()}static setupBVH(){l.BufferGeometry.prototype.computeBoundsTree=ki,l.BufferGeometry.prototype.disposeBoundsTree=Ui,l.Mesh.prototype.raycast=Vi,l.LineSegments.prototype.raycast=Vi}};t(AO,"release","2.4.3");let NO=AO;class EO{constructor(e){t(this,"enabled",!1),t(this,"id","FirstPerson"),this.camera=e}set(e){if(this.enabled=e,e){if("Perspective"!==this.camera.projection.current)return void this.camera.set("Orbit");this.setupFirstPersonCamera()}}setupFirstPersonCamera(){const e=this.camera.controls,t=new l.Vector3;e.distance--,e.getPosition(t),e.minDistance=1,e.maxDistance=1,e.distance=1,e.moveTo(t.x,t.y,t.z),e.truckSpeed=50,e.mouseButtons.wheel=n.ACTION.DOLLY,e.touches.two=n.ACTION.TOUCH_ZOOM_TRUCK}}class CO{constructor(e){t(this,"enabled",!0),t(this,"id","Orbit"),this.camera=e,this.activateOrbitControls()}set(e){this.enabled=e,e&&this.activateOrbitControls()}activateOrbitControls(){const e=this.camera.controls;e.minDistance=1,e.maxDistance=300;const t=new l.Vector3;e.getPosition(t);const s=t.length();e.distance=s,e.truckSpeed=2;const{rotation:i}=this.camera.three,r=new l.Vector3(0,0,-1).applyEuler(i),n=t.addScaledVector(r,s);e.moveTo(n.x,n.y,n.z)}}class RO{constructor(e){t(this,"enabled",!1),t(this,"id","Plan"),t(this,"mouseAction1"),t(this,"mouseAction2"),t(this,"mouseInitialized",!1),t(this,"defaultAzimuthSpeed"),t(this,"defaultPolarSpeed"),this.camera=e,this.defaultAzimuthSpeed=e.controls.azimuthRotateSpeed,this.defaultPolarSpeed=e.controls.polarRotateSpeed}set(e){this.enabled=e;const t=this.camera.controls;t.azimuthRotateSpeed=e?0:this.defaultAzimuthSpeed,t.polarRotateSpeed=e?0:this.defaultPolarSpeed,this.mouseInitialized||(this.mouseAction1=t.touches.one,this.mouseAction2=t.touches.two,this.mouseInitialized=!0),e?(t.mouseButtons.left=n.ACTION.TRUCK,t.touches.one=n.ACTION.TOUCH_TRUCK,t.touches.two=n.ACTION.TOUCH_ZOOM):(t.mouseButtons.left=n.ACTION.ROTATE,t.touches.one=this.mouseAction1,t.touches.two=this.mouseAction2)}}class PO{constructor(e){t(this,"onChanged",new u),t(this,"current","Perspective"),t(this,"camera"),t(this,"matchOrthoDistanceEnabled",!1),t(this,"_component"),t(this,"_previousDistance",-1),this._component=e,this.camera=e.three}async set(e){this.current!==e&&("Orthographic"===e?this.setOrthoCamera():await this.setPerspectiveCamera(),this.onChanged.trigger(this.camera))}async toggle(){const e="Perspective"===this.current?"Orthographic":"Perspective";await this.set(e)}setOrthoCamera(){if(null===this._component.mode)return;if("FirstPerson"===this._component.mode.id)return;this._previousDistance=this._component.controls.distance,this._component.controls.distance=200;const e=this.getPerspectiveDims();if(!e)return;const{width:t,height:s}=e;this.setupOrthoCamera(s,t),this.camera=this._component.threeOrtho,this.current="Orthographic"}getPerspectiveDims(){const e=this._component.currentWorld;if(!e||!e.renderer)return null;const t=new l.Vector3;this._component.threePersp.getWorldDirection(t);const s=new l.Vector3;this._component.controls.getTarget(s);const i=s.clone().sub(this._component.threePersp.position).dot(t),r=e.renderer.getSize(),n=r.x/r.y,o=this._component.threePersp,a=2*i*Math.atan(o.fov*(Math.PI/180)/2);return{width:a*n,height:a}}setupOrthoCamera(e,t){this._component.controls.mouseButtons.wheel=n.ACTION.ZOOM,this._component.controls.mouseButtons.middle=n.ACTION.ZOOM;const s=this._component.threePersp,i=this._component.threeOrtho;i.zoom=1,i.left=t/-2,i.right=t/2,i.top=e/2,i.bottom=e/-2,i.updateProjectionMatrix(),i.position.copy(s.position),i.quaternion.copy(s.quaternion),this._component.controls.camera=i}getDistance(){const e=this._component.threePersp,t=this._component.threeOrtho;return(t.top-t.bottom)/t.zoom/(2*Math.atan(e.fov*(Math.PI/180)/2))}async setPerspectiveCamera(){this._component.controls.mouseButtons.wheel=n.ACTION.DOLLY,this._component.controls.mouseButtons.middle=n.ACTION.DOLLY;const e=this._component.threePersp,t=this._component.threeOrtho;e.position.copy(t.position),e.quaternion.copy(t.quaternion),this._component.controls.mouseButtons.wheel=n.ACTION.DOLLY,this.matchOrthoDistanceEnabled?this._component.controls.distance=this.getDistance():this._component.controls.distance=this._previousDistance,await this._component.controls.zoomTo(1),e.updateProjectionMatrix(),this._component.controls.camera=e,this.camera=e,this.current="Perspective"}}class BO extends bO{constructor(e){super(e),t(this,"projection"),t(this,"threeOrtho"),t(this,"threePersp"),t(this,"_userInputButtons",{}),t(this,"_frustumSize",50),t(this,"_navigationModes",new Map),t(this,"_mode",null),t(this,"previousSize",null),this.threePersp=this.three,this.threeOrtho=this.newOrthoCamera(),this.projection=new PO(this),this.onAspectUpdated.add(()=>{this.setOrthoPerspCameraAspect()}),this.projection.onChanged.add(e=>{this.three=e,this.updateAspect()}),this.worlds.onItemSet.add(()=>{this._navigationModes.clear(),this._navigationModes.set("Orbit",new CO(this)),this._navigationModes.set("FirstPerson",new EO(this)),this._navigationModes.set("Plan",new RO(this)),this._mode=this._navigationModes.get("Orbit"),this.mode.set(!0,{preventTargetAdjustment:!0}),this.currentWorld&&this.currentWorld.renderer&&(this.previousSize=this.currentWorld.renderer.getSize().clone())}),this.worlds.onItemDeleted.add(()=>{this._navigationModes.clear()})}get mode(){if(!this._mode)throw new Error("Mode not found, camera not initialized");return this._mode}dispose(){super.dispose(),this.threeOrtho.removeFromParent()}set(e){if(null!==this.mode&&this.mode.id!==e){if(this.mode.set(!1),!this._navigationModes.has(e))throw new Error("The specified mode does not exist!");this._mode=this._navigationModes.get(e),this.mode.set(!0)}}async fit(e,t=1.5){if(!this.enabled)return;const s=Number.MAX_VALUE,i=Number.MIN_VALUE,r=new l.Vector3(s,s,s),n=new l.Vector3(i,i,i);for(const t of e){const e=(new l.Box3).setFromObject(t);e.min.x<r.x&&(r.x=e.min.x),e.min.y<r.y&&(r.y=e.min.y),e.min.z<r.z&&(r.z=e.min.z),e.max.x>n.x&&(n.x=e.max.x),e.max.y>n.y&&(n.y=e.max.y),e.max.z>n.z&&(n.z=e.max.z)}const o=new l.Box3(r,n),a=this.components.get(ji);if(a.initialized)for(const[,e]of a.list){const t=e.box;t.min.x<r.x&&(r.x=t.min.x),t.min.y<r.y&&(r.y=t.min.y),t.min.z<r.z&&(r.z=t.min.z),t.max.x>n.x&&(n.x=t.max.x),t.max.y>n.y&&(n.y=t.max.y),t.max.z>n.z&&(n.z=t.max.z)}const h=new l.Vector3;o.getSize(h);const u=new l.Vector3;o.getCenter(u);const c=Math.max(h.x,h.y,h.z)*t,d=new l.Sphere(u,c);await this.controls.fitToSphere(d,!0)}setUserInput(e){e?this.enableUserInput():this.disableUserInput()}addCustomNavigationMode(e){this._navigationModes.set(e.id,e)}disableUserInput(){this._userInputButtons.left=this.controls.mouseButtons.left,this._userInputButtons.right=this.controls.mouseButtons.right,this._userInputButtons.middle=this.controls.mouseButtons.middle,this._userInputButtons.wheel=this.controls.mouseButtons.wheel,this.controls.mouseButtons.left=0,this.controls.mouseButtons.right=0,this.controls.mouseButtons.middle=0,this.controls.mouseButtons.wheel=0}enableUserInput(){0!==Object.keys(this._userInputButtons).length&&(this.controls.mouseButtons.left=this._userInputButtons.left,this.controls.mouseButtons.right=this._userInputButtons.right,this.controls.mouseButtons.middle=this._userInputButtons.middle,this.controls.mouseButtons.wheel=this._userInputButtons.wheel)}newOrthoCamera(){const e=window.innerWidth/window.innerHeight;return new l.OrthographicCamera(this._frustumSize*e/-2,this._frustumSize*e/2,this._frustumSize/2,this._frustumSize/-2,.1,1e3)}setOrthoPerspCameraAspect(){if(!this.currentWorld||!this.currentWorld.renderer)return;if(!this.previousSize)return;const e=this.currentWorld.renderer.getSize(),t=this.threeOrtho.top,s=this.threeOrtho.right,i=t*(e.y/this.previousSize.y),r=s*(e.x/this.previousSize.x);this.threeOrtho.left=-r,this.threeOrtho.right=r,this.threeOrtho.top=i,this.threeOrtho.bottom=-i,this.threeOrtho.updateProjectionMatrix(),this.previousSize.copy(e)}}var IO="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function DO(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function LO(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var FO={exports:{}};
9
17
  /*!
10
18
 
11
19
  JSZip v3.10.1 - A JavaScript class for generating and reading zip files
@@ -16,4 +24,4 @@ Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/js
16
24
 
17
25
  JSZip uses the library pako released under the MIT license :
18
26
  https://github.com/nodeca/pako/blob/main/LICENSE
19
- */const or=x(rr.exports=function t(e,i,s){function n(o,a){if(!i[o]){if(!e[o]){if(!a&&nr)return nr(o);if(r)return r(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var h=i[o]={exports:{}};e[o][0].call(h.exports,function(t){return n(e[o][1][t]||t)},h,h.exports,t,e,i,s)}return i[o].exports}for(var r=nr,o=0;o<s.length;o++)n(s[o]);return n}({1:[function(t,e,i){var s=t("./utils"),n=t("./support"),r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";i.encode=function(t){for(var e,i,n,o,a,l,h,c=[],d=0,u=t.length,p=u,f="string"!==s.getTypeOf(t);d<t.length;)p=u-d,n=f?(e=t[d++],i=d<u?t[d++]:0,d<u?t[d++]:0):(e=t.charCodeAt(d++),i=d<u?t.charCodeAt(d++):0,d<u?t.charCodeAt(d++):0),o=e>>2,a=(3&e)<<4|i>>4,l=1<p?(15&i)<<2|n>>6:64,h=2<p?63&n:64,c.push(r.charAt(o)+r.charAt(a)+r.charAt(l)+r.charAt(h));return c.join("")},i.decode=function(t){var e,i,s,o,a,l,h=0,c=0,d="data:";if(t.substr(0,d.length)===d)throw new Error("Invalid base64 input, it looks like a data url.");var u,p=3*(t=t.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(t.charAt(t.length-1)===r.charAt(64)&&p--,t.charAt(t.length-2)===r.charAt(64)&&p--,p%1!=0)throw new Error("Invalid base64 input, bad content length.");for(u=n.uint8array?new Uint8Array(0|p):new Array(0|p);h<t.length;)e=r.indexOf(t.charAt(h++))<<2|(o=r.indexOf(t.charAt(h++)))>>4,i=(15&o)<<4|(a=r.indexOf(t.charAt(h++)))>>2,s=(3&a)<<6|(l=r.indexOf(t.charAt(h++))),u[c++]=e,64!==a&&(u[c++]=i),64!==l&&(u[c++]=s);return u}},{"./support":30,"./utils":32}],2:[function(t,e,i){var s=t("./external"),n=t("./stream/DataWorker"),r=t("./stream/Crc32Probe"),o=t("./stream/DataLengthProbe");function a(t,e,i,s,n){this.compressedSize=t,this.uncompressedSize=e,this.crc32=i,this.compression=s,this.compressedContent=n}a.prototype={getContentWorker:function(){var t=new n(s.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new o("data_length")),e=this;return t.on("end",function(){if(this.streamInfo.data_length!==e.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),t},getCompressedWorker:function(){return new n(s.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},a.createWorkerFrom=function(t,e,i){return t.pipe(new r).pipe(new o("uncompressedSize")).pipe(e.compressWorker(i)).pipe(new o("compressedSize")).withStreamInfo("compression",e)},e.exports=a},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(t,e,i){var s=t("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new s("STORE compression")},uncompressWorker:function(){return new s("STORE decompression")}},i.DEFLATE=t("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(t,e,i){var s=t("./utils"),n=function(){for(var t,e=[],i=0;i<256;i++){t=i;for(var s=0;s<8;s++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e}();e.exports=function(t,e){return void 0!==t&&t.length?"string"!==s.getTypeOf(t)?function(t,e,i,s){var r=n,o=s+i;t^=-1;for(var a=s;a<o;a++)t=t>>>8^r[255&(t^e[a])];return-1^t}(0|e,t,t.length,0):function(t,e,i,s){var r=n,o=s+i;t^=-1;for(var a=s;a<o;a++)t=t>>>8^r[255&(t^e.charCodeAt(a))];return-1^t}(0|e,t,t.length,0):0}},{"./utils":32}],5:[function(t,e,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(t,e,i){var s=null;s="undefined"!=typeof Promise?Promise:t("lie"),e.exports={Promise:s}},{lie:37}],7:[function(t,e,i){var s="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,n=t("pako"),r=t("./utils"),o=t("./stream/GenericWorker"),a=s?"uint8array":"array";function l(t,e){o.call(this,"FlateWorker/"+t),this._pako=null,this._pakoAction=t,this._pakoOptions=e,this.meta={}}i.magic="\b\0",r.inherits(l,o),l.prototype.processChunk=function(t){this.meta=t.meta,null===this._pako&&this._createPako(),this._pako.push(r.transformTo(a,t.data),!1)},l.prototype.flush=function(){o.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},l.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this._pako=null},l.prototype._createPako=function(){this._pako=new n[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var t=this;this._pako.onData=function(e){t.push({data:e,meta:t.meta})}},i.compressWorker=function(t){return new l("Deflate",t)},i.uncompressWorker=function(){return new l("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(t,e,i){function s(t,e){var i,s="";for(i=0;i<e;i++)s+=String.fromCharCode(255&t),t>>>=8;return s}function n(t,e,i,n,o,c){var d,u,p=t.file,f=t.compression,m=c!==a.utf8encode,g=r.transformTo("string",c(p.name)),_=r.transformTo("string",a.utf8encode(p.name)),y=p.comment,w=r.transformTo("string",c(y)),v=r.transformTo("string",a.utf8encode(y)),b=_.length!==p.name.length,x=v.length!==y.length,T="",C="",E="",S=p.dir,A=p.date,O={crc32:0,compressedSize:0,uncompressedSize:0};e&&!i||(O.crc32=t.crc32,O.compressedSize=t.compressedSize,O.uncompressedSize=t.uncompressedSize);var P=0;e&&(P|=8),m||!b&&!x||(P|=2048);var I,M,D,k=0,z=0;S&&(k|=16),"UNIX"===o?(z=798,k|=(I=p.unixPermissions,M=S,D=I,I||(D=M?16893:33204),(65535&D)<<16)):(z=20,k|=function(t){return 63&(t||0)}(p.dosPermissions)),d=A.getUTCHours(),d<<=6,d|=A.getUTCMinutes(),d<<=5,d|=A.getUTCSeconds()/2,u=A.getUTCFullYear()-1980,u<<=4,u|=A.getUTCMonth()+1,u<<=5,u|=A.getUTCDate(),b&&(C=s(1,1)+s(l(g),4)+_,T+="up"+s(C.length,2)+C),x&&(E=s(1,1)+s(l(w),4)+v,T+="uc"+s(E.length,2)+E);var B="";return B+="\n\0",B+=s(P,2),B+=f.magic,B+=s(d,2),B+=s(u,2),B+=s(O.crc32,4),B+=s(O.compressedSize,4),B+=s(O.uncompressedSize,4),B+=s(g.length,2),B+=s(T.length,2),{fileRecord:h.LOCAL_FILE_HEADER+B+g+T,dirRecord:h.CENTRAL_FILE_HEADER+s(z,2)+B+s(w.length,2)+"\0\0\0\0"+s(k,4)+s(n,4)+g+T+w}}var r=t("../utils"),o=t("../stream/GenericWorker"),a=t("../utf8"),l=t("../crc32"),h=t("../signature");function c(t,e,i,s){o.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=e,this.zipPlatform=i,this.encodeFileName=s,this.streamFiles=t,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}r.inherits(c,o),c.prototype.push=function(t){var e=t.meta.percent||0,i=this.entriesCount,s=this._sources.length;this.accumulate?this.contentBuffer.push(t):(this.bytesWritten+=t.data.length,o.prototype.push.call(this,{data:t.data,meta:{currentFile:this.currentFile,percent:i?(e+100*(i-s-1))/i:100}}))},c.prototype.openedSource=function(t){this.currentSourceOffset=this.bytesWritten,this.currentFile=t.file.name;var e=this.streamFiles&&!t.file.dir;if(e){var i=n(t,e,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:i.fileRecord,meta:{percent:0}})}else this.accumulate=!0},c.prototype.closedSource=function(t){this.accumulate=!1;var e,i=this.streamFiles&&!t.file.dir,r=n(t,i,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(r.dirRecord),i)this.push({data:(e=t,h.DATA_DESCRIPTOR+s(e.crc32,4)+s(e.compressedSize,4)+s(e.uncompressedSize,4)),meta:{percent:100}});else for(this.push({data:r.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},c.prototype.flush=function(){for(var t=this.bytesWritten,e=0;e<this.dirRecords.length;e++)this.push({data:this.dirRecords[e],meta:{percent:100}});var i,n,o,a,l,c,d=this.bytesWritten-t,u=(i=this.dirRecords.length,n=d,o=t,a=this.zipComment,l=this.encodeFileName,c=r.transformTo("string",l(a)),h.CENTRAL_DIRECTORY_END+"\0\0\0\0"+s(i,2)+s(i,2)+s(n,4)+s(o,4)+s(c.length,2)+c);this.push({data:u,meta:{percent:100}})},c.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},c.prototype.registerPrevious=function(t){this._sources.push(t);var e=this;return t.on("data",function(t){e.processChunk(t)}),t.on("end",function(){e.closedSource(e.previous.streamInfo),e._sources.length?e.prepareNextSource():e.end()}),t.on("error",function(t){e.error(t)}),this},c.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},c.prototype.error=function(t){var e=this._sources;if(!o.prototype.error.call(this,t))return!1;for(var i=0;i<e.length;i++)try{e[i].error(t)}catch(t){}return!0},c.prototype.lock=function(){o.prototype.lock.call(this);for(var t=this._sources,e=0;e<t.length;e++)t[e].lock()},e.exports=c},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(t,e,i){var s=t("../compressions"),n=t("./ZipFileWorker");i.generateWorker=function(t,e,i){var r=new n(e.streamFiles,i,e.platform,e.encodeFileName),o=0;try{t.forEach(function(t,i){o++;var n=function(t,e){var i=t||e,n=s[i];if(!n)throw new Error(i+" is not a valid compression method !");return n}(i.options.compression,e.compression),a=i.options.compressionOptions||e.compressionOptions||{},l=i.dir,h=i.date;i._compressWorker(n,a).withStreamInfo("file",{name:t,dir:l,date:h,comment:i.comment||"",unixPermissions:i.unixPermissions,dosPermissions:i.dosPermissions}).pipe(r)}),r.entriesCount=o}catch(t){r.error(t)}return r}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(t,e,i){function s(){if(!(this instanceof s))return new s;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var t=new s;for(var e in this)"function"!=typeof this[e]&&(t[e]=this[e]);return t}}(s.prototype=t("./object")).loadAsync=t("./load"),s.support=t("./support"),s.defaults=t("./defaults"),s.version="3.10.1",s.loadAsync=function(t,e){return(new s).loadAsync(t,e)},s.external=t("./external"),e.exports=s},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(t,e,i){var s=t("./utils"),n=t("./external"),r=t("./utf8"),o=t("./zipEntries"),a=t("./stream/Crc32Probe"),l=t("./nodejsUtils");function h(t){return new n.Promise(function(e,i){var s=t.decompressed.getContentWorker().pipe(new a);s.on("error",function(t){i(t)}).on("end",function(){s.streamInfo.crc32!==t.decompressed.crc32?i(new Error("Corrupted zip : CRC32 mismatch")):e()}).resume()})}e.exports=function(t,e){var i=this;return e=s.extend(e||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:r.utf8decode}),l.isNode&&l.isStream(t)?n.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):s.prepareContent("the loaded zip file",t,!0,e.optimizedBinaryString,e.base64).then(function(t){var i=new o(e);return i.load(t),i}).then(function(t){var i=[n.Promise.resolve(t)],s=t.files;if(e.checkCRC32)for(var r=0;r<s.length;r++)i.push(h(s[r]));return n.Promise.all(i)}).then(function(t){for(var n=t.shift(),r=n.files,o=0;o<r.length;o++){var a=r[o],l=a.fileNameStr,h=s.resolve(a.fileNameStr);i.file(h,a.decompressed,{binary:!0,optimizedBinaryString:!0,date:a.date,dir:a.dir,comment:a.fileCommentStr.length?a.fileCommentStr:null,unixPermissions:a.unixPermissions,dosPermissions:a.dosPermissions,createFolders:e.createFolders}),a.dir||(i.file(h).unsafeOriginalName=l)}return n.zipComment.length&&(i.comment=n.zipComment),i})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(t,e,i){var s=t("../utils"),n=t("../stream/GenericWorker");function r(t,e){n.call(this,"Nodejs stream input adapter for "+t),this._upstreamEnded=!1,this._bindStream(e)}s.inherits(r,n),r.prototype._bindStream=function(t){var e=this;(this._stream=t).pause(),t.on("data",function(t){e.push({data:t,meta:{percent:0}})}).on("error",function(t){e.isPaused?this.generatedError=t:e.error(t)}).on("end",function(){e.isPaused?e._upstreamEnded=!0:e.end()})},r.prototype.pause=function(){return!!n.prototype.pause.call(this)&&(this._stream.pause(),!0)},r.prototype.resume=function(){return!!n.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},e.exports=r},{"../stream/GenericWorker":28,"../utils":32}],13:[function(t,e,i){var s=t("readable-stream").Readable;function n(t,e,i){s.call(this,e),this._helper=t;var n=this;t.on("data",function(t,e){n.push(t)||n._helper.pause(),i&&i(e)}).on("error",function(t){n.emit("error",t)}).on("end",function(){n.push(null)})}t("../utils").inherits(n,s),n.prototype._read=function(){this._helper.resume()},e.exports=n},{"../utils":32,"readable-stream":16}],14:[function(t,e,i){e.exports={isNode:"undefined"!=typeof Buffer,newBufferFrom:function(t,e){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(t,e);if("number"==typeof t)throw new Error('The "data" argument must not be a number');return new Buffer(t,e)},allocBuffer:function(t){if(Buffer.alloc)return Buffer.alloc(t);var e=new Buffer(t);return e.fill(0),e},isBuffer:function(t){return Buffer.isBuffer(t)},isStream:function(t){return t&&"function"==typeof t.on&&"function"==typeof t.pause&&"function"==typeof t.resume}}},{}],15:[function(t,e,i){function s(t,e,i){var s,n=r.getTypeOf(e),a=r.extend(i||{},l);a.date=a.date||new Date,null!==a.compression&&(a.compression=a.compression.toUpperCase()),"string"==typeof a.unixPermissions&&(a.unixPermissions=parseInt(a.unixPermissions,8)),a.unixPermissions&&16384&a.unixPermissions&&(a.dir=!0),a.dosPermissions&&16&a.dosPermissions&&(a.dir=!0),a.dir&&(t=m(t)),a.createFolders&&(s=f(t))&&g.call(this,s,!0);var d="string"===n&&!1===a.binary&&!1===a.base64;i&&void 0!==i.binary||(a.binary=!d),(e instanceof h&&0===e.uncompressedSize||a.dir||!e||0===e.length)&&(a.base64=!1,a.binary=!0,e="",a.compression="STORE",n="string");var _=null;_=e instanceof h||e instanceof o?e:u.isNode&&u.isStream(e)?new p(t,e):r.prepareContent(t,e,a.binary,a.optimizedBinaryString,a.base64);var y=new c(t,_,a);this.files[t]=y}var n=t("./utf8"),r=t("./utils"),o=t("./stream/GenericWorker"),a=t("./stream/StreamHelper"),l=t("./defaults"),h=t("./compressedObject"),c=t("./zipObject"),d=t("./generate"),u=t("./nodejsUtils"),p=t("./nodejs/NodejsStreamInputAdapter"),f=function(t){"/"===t.slice(-1)&&(t=t.substring(0,t.length-1));var e=t.lastIndexOf("/");return 0<e?t.substring(0,e):""},m=function(t){return"/"!==t.slice(-1)&&(t+="/"),t},g=function(t,e){return e=void 0!==e?e:l.createFolders,t=m(t),this.files[t]||s.call(this,t,null,{dir:!0,createFolders:e}),this.files[t]};function _(t){return"[object RegExp]"===Object.prototype.toString.call(t)}var y={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(t){var e,i,s;for(e in this.files)s=this.files[e],(i=e.slice(this.root.length,e.length))&&e.slice(0,this.root.length)===this.root&&t(i,s)},filter:function(t){var e=[];return this.forEach(function(i,s){t(i,s)&&e.push(s)}),e},file:function(t,e,i){if(1!==arguments.length)return t=this.root+t,s.call(this,t,e,i),this;if(_(t)){var n=t;return this.filter(function(t,e){return!e.dir&&n.test(t)})}var r=this.files[this.root+t];return r&&!r.dir?r:null},folder:function(t){if(!t)return this;if(_(t))return this.filter(function(e,i){return i.dir&&t.test(e)});var e=this.root+t,i=g.call(this,e),s=this.clone();return s.root=i.name,s},remove:function(t){t=this.root+t;var e=this.files[t];if(e||("/"!==t.slice(-1)&&(t+="/"),e=this.files[t]),e&&!e.dir)delete this.files[t];else for(var i=this.filter(function(e,i){return i.name.slice(0,t.length)===t}),s=0;s<i.length;s++)delete this.files[i[s].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(t){var e,i={};try{if((i=r.extend(t||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:n.utf8encode})).type=i.type.toLowerCase(),i.compression=i.compression.toUpperCase(),"binarystring"===i.type&&(i.type="string"),!i.type)throw new Error("No output type specified.");r.checkSupport(i.type),"darwin"!==i.platform&&"freebsd"!==i.platform&&"linux"!==i.platform&&"sunos"!==i.platform||(i.platform="UNIX"),"win32"===i.platform&&(i.platform="DOS");var s=i.comment||this.comment||"";e=d.generateWorker(this,i,s)}catch(t){(e=new o("error")).error(t)}return new a(e,i.type||"string",i.mimeType)},generateAsync:function(t,e){return this.generateInternalStream(t).accumulate(e)},generateNodeStream:function(t,e){return(t=t||{}).type||(t.type="nodebuffer"),this.generateInternalStream(t).toNodejsStream(e)}};e.exports=y},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(t,e,i){e.exports=t("stream")},{stream:void 0}],17:[function(t,e,i){var s=t("./DataReader");function n(t){s.call(this,t);for(var e=0;e<this.data.length;e++)t[e]=255&t[e]}t("../utils").inherits(n,s),n.prototype.byteAt=function(t){return this.data[this.zero+t]},n.prototype.lastIndexOfSignature=function(t){for(var e=t.charCodeAt(0),i=t.charCodeAt(1),s=t.charCodeAt(2),n=t.charCodeAt(3),r=this.length-4;0<=r;--r)if(this.data[r]===e&&this.data[r+1]===i&&this.data[r+2]===s&&this.data[r+3]===n)return r-this.zero;return-1},n.prototype.readAndCheckSignature=function(t){var e=t.charCodeAt(0),i=t.charCodeAt(1),s=t.charCodeAt(2),n=t.charCodeAt(3),r=this.readData(4);return e===r[0]&&i===r[1]&&s===r[2]&&n===r[3]},n.prototype.readData=function(t){if(this.checkOffset(t),0===t)return[];var e=this.data.slice(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=n},{"../utils":32,"./DataReader":18}],18:[function(t,e,i){var s=t("../utils");function n(t){this.data=t,this.length=t.length,this.index=0,this.zero=0}n.prototype={checkOffset:function(t){this.checkIndex(this.index+t)},checkIndex:function(t){if(this.length<this.zero+t||t<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+t+"). Corrupted zip ?")},setIndex:function(t){this.checkIndex(t),this.index=t},skip:function(t){this.setIndex(this.index+t)},byteAt:function(){},readInt:function(t){var e,i=0;for(this.checkOffset(t),e=this.index+t-1;e>=this.index;e--)i=(i<<8)+this.byteAt(e);return this.index+=t,i},readString:function(t){return s.transformTo("string",this.readData(t))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var t=this.readInt(4);return new Date(Date.UTC(1980+(t>>25&127),(t>>21&15)-1,t>>16&31,t>>11&31,t>>5&63,(31&t)<<1))}},e.exports=n},{"../utils":32}],19:[function(t,e,i){var s=t("./Uint8ArrayReader");function n(t){s.call(this,t)}t("../utils").inherits(n,s),n.prototype.readData=function(t){this.checkOffset(t);var e=this.data.slice(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=n},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(t,e,i){var s=t("./DataReader");function n(t){s.call(this,t)}t("../utils").inherits(n,s),n.prototype.byteAt=function(t){return this.data.charCodeAt(this.zero+t)},n.prototype.lastIndexOfSignature=function(t){return this.data.lastIndexOf(t)-this.zero},n.prototype.readAndCheckSignature=function(t){return t===this.readData(4)},n.prototype.readData=function(t){this.checkOffset(t);var e=this.data.slice(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=n},{"../utils":32,"./DataReader":18}],21:[function(t,e,i){var s=t("./ArrayReader");function n(t){s.call(this,t)}t("../utils").inherits(n,s),n.prototype.readData=function(t){if(this.checkOffset(t),0===t)return new Uint8Array(0);var e=this.data.subarray(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=n},{"../utils":32,"./ArrayReader":17}],22:[function(t,e,i){var s=t("../utils"),n=t("../support"),r=t("./ArrayReader"),o=t("./StringReader"),a=t("./NodeBufferReader"),l=t("./Uint8ArrayReader");e.exports=function(t){var e=s.getTypeOf(t);return s.checkSupport(e),"string"!==e||n.uint8array?"nodebuffer"===e?new a(t):n.uint8array?new l(s.transformTo("uint8array",t)):new r(s.transformTo("array",t)):new o(t)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(t,e,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\b"},{}],24:[function(t,e,i){var s=t("./GenericWorker"),n=t("../utils");function r(t){s.call(this,"ConvertWorker to "+t),this.destType=t}n.inherits(r,s),r.prototype.processChunk=function(t){this.push({data:n.transformTo(this.destType,t.data),meta:t.meta})},e.exports=r},{"../utils":32,"./GenericWorker":28}],25:[function(t,e,i){var s=t("./GenericWorker"),n=t("../crc32");function r(){s.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}t("../utils").inherits(r,s),r.prototype.processChunk=function(t){this.streamInfo.crc32=n(t.data,this.streamInfo.crc32||0),this.push(t)},e.exports=r},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(t,e,i){var s=t("../utils"),n=t("./GenericWorker");function r(t){n.call(this,"DataLengthProbe for "+t),this.propName=t,this.withStreamInfo(t,0)}s.inherits(r,n),r.prototype.processChunk=function(t){if(t){var e=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=e+t.data.length}n.prototype.processChunk.call(this,t)},e.exports=r},{"../utils":32,"./GenericWorker":28}],27:[function(t,e,i){var s=t("../utils"),n=t("./GenericWorker");function r(t){n.call(this,"DataWorker");var e=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,t.then(function(t){e.dataIsReady=!0,e.data=t,e.max=t&&t.length||0,e.type=s.getTypeOf(t),e.isPaused||e._tickAndRepeat()},function(t){e.error(t)})}s.inherits(r,n),r.prototype.cleanUp=function(){n.prototype.cleanUp.call(this),this.data=null},r.prototype.resume=function(){return!!n.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,s.delay(this._tickAndRepeat,[],this)),!0)},r.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(s.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},r.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var t=null,e=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":t=this.data.substring(this.index,e);break;case"uint8array":t=this.data.subarray(this.index,e);break;case"array":case"nodebuffer":t=this.data.slice(this.index,e)}return this.index=e,this.push({data:t,meta:{percent:this.max?this.index/this.max*100:0}})},e.exports=r},{"../utils":32,"./GenericWorker":28}],28:[function(t,e,i){function s(t){this.name=t||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}s.prototype={push:function(t){this.emit("data",t)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(t){this.emit("error",t)}return!0},error:function(t){return!this.isFinished&&(this.isPaused?this.generatedError=t:(this.isFinished=!0,this.emit("error",t),this.previous&&this.previous.error(t),this.cleanUp()),!0)},on:function(t,e){return this._listeners[t].push(e),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(t,e){if(this._listeners[t])for(var i=0;i<this._listeners[t].length;i++)this._listeners[t][i].call(this,e)},pipe:function(t){return t.registerPrevious(this)},registerPrevious:function(t){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=t.streamInfo,this.mergeStreamInfo(),this.previous=t;var e=this;return t.on("data",function(t){e.processChunk(t)}),t.on("end",function(){e.end()}),t.on("error",function(t){e.error(t)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var t=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),t=!0),this.previous&&this.previous.resume(),!t},flush:function(){},processChunk:function(t){this.push(t)},withStreamInfo:function(t,e){return this.extraStreamInfo[t]=e,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var t in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,t)&&(this.streamInfo[t]=this.extraStreamInfo[t])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var t="Worker "+this.name;return this.previous?this.previous+" -> "+t:t}},e.exports=s},{}],29:[function(t,e,i){var s=t("../utils"),n=t("./ConvertWorker"),r=t("./GenericWorker"),o=t("../base64"),a=t("../support"),l=t("../external"),h=null;if(a.nodestream)try{h=t("../nodejs/NodejsStreamOutputAdapter")}catch(t){}function c(t,e){return new l.Promise(function(i,n){var r=[],a=t._internalType,l=t._outputType,h=t._mimeType;t.on("data",function(t,i){r.push(t),e&&e(i)}).on("error",function(t){r=[],n(t)}).on("end",function(){try{var t=function(t,e,i){switch(t){case"blob":return s.newBlob(s.transformTo("arraybuffer",e),i);case"base64":return o.encode(e);default:return s.transformTo(t,e)}}(l,function(t,e){var i,s=0,n=null,r=0;for(i=0;i<e.length;i++)r+=e[i].length;switch(t){case"string":return e.join("");case"array":return Array.prototype.concat.apply([],e);case"uint8array":for(n=new Uint8Array(r),i=0;i<e.length;i++)n.set(e[i],s),s+=e[i].length;return n;case"nodebuffer":return Buffer.concat(e);default:throw new Error("concat : unsupported type '"+t+"'")}}(a,r),h);i(t)}catch(t){n(t)}r=[]}).resume()})}function d(t,e,i){var o=e;switch(e){case"blob":case"arraybuffer":o="uint8array";break;case"base64":o="string"}try{this._internalType=o,this._outputType=e,this._mimeType=i,s.checkSupport(o),this._worker=t.pipe(new n(o)),t.lock()}catch(t){this._worker=new r("error"),this._worker.error(t)}}d.prototype={accumulate:function(t){return c(this,t)},on:function(t,e){var i=this;return"data"===t?this._worker.on(t,function(t){e.call(i,t.data,t.meta)}):this._worker.on(t,function(){s.delay(e,arguments,i)}),this},resume:function(){return s.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(t){if(s.checkSupport("nodestream"),"nodebuffer"!==this._outputType)throw new Error(this._outputType+" is not supported by this method");return new h(this,{objectMode:"nodebuffer"!==this._outputType},t)}},e.exports=d},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(t,e,i){if(i.base64=!0,i.array=!0,i.string=!0,i.arraybuffer="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array,i.nodebuffer="undefined"!=typeof Buffer,i.uint8array="undefined"!=typeof Uint8Array,"undefined"==typeof ArrayBuffer)i.blob=!1;else{var s=new ArrayBuffer(0);try{i.blob=0===new Blob([s],{type:"application/zip"}).size}catch(t){try{var n=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);n.append(s),i.blob=0===n.getBlob("application/zip").size}catch(t){i.blob=!1}}}try{i.nodestream=!!t("readable-stream").Readable}catch(t){i.nodestream=!1}},{"readable-stream":16}],31:[function(t,e,i){for(var s=t("./utils"),n=t("./support"),r=t("./nodejsUtils"),o=t("./stream/GenericWorker"),a=new Array(256),l=0;l<256;l++)a[l]=252<=l?6:248<=l?5:240<=l?4:224<=l?3:192<=l?2:1;function h(){o.call(this,"utf-8 decode"),this.leftOver=null}function c(){o.call(this,"utf-8 encode")}a[254]=a[254]=1,i.utf8encode=function(t){return n.nodebuffer?r.newBufferFrom(t,"utf-8"):function(t){var e,i,s,r,o,a=t.length,l=0;for(r=0;r<a;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(s=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(s-56320),r++),l+=i<128?1:i<2048?2:i<65536?3:4;for(e=n.uint8array?new Uint8Array(l):new Array(l),r=o=0;o<l;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(s=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(s-56320),r++),i<128?e[o++]=i:(i<2048?e[o++]=192|i>>>6:(i<65536?e[o++]=224|i>>>12:(e[o++]=240|i>>>18,e[o++]=128|i>>>12&63),e[o++]=128|i>>>6&63),e[o++]=128|63&i);return e}(t)},i.utf8decode=function(t){return n.nodebuffer?s.transformTo("nodebuffer",t).toString("utf-8"):function(t){var e,i,n,r,o=t.length,l=new Array(2*o);for(e=i=0;e<o;)if((n=t[e++])<128)l[i++]=n;else if(4<(r=a[n]))l[i++]=65533,e+=r-1;else{for(n&=2===r?31:3===r?15:7;1<r&&e<o;)n=n<<6|63&t[e++],r--;1<r?l[i++]=65533:n<65536?l[i++]=n:(n-=65536,l[i++]=55296|n>>10&1023,l[i++]=56320|1023&n)}return l.length!==i&&(l.subarray?l=l.subarray(0,i):l.length=i),s.applyFromCharCode(l)}(t=s.transformTo(n.uint8array?"uint8array":"array",t))},s.inherits(h,o),h.prototype.processChunk=function(t){var e=s.transformTo(n.uint8array?"uint8array":"array",t.data);if(this.leftOver&&this.leftOver.length){if(n.uint8array){var r=e;(e=new Uint8Array(r.length+this.leftOver.length)).set(this.leftOver,0),e.set(r,this.leftOver.length)}else e=this.leftOver.concat(e);this.leftOver=null}var o=function(t,e){var i;for((e=e||t.length)>t.length&&(e=t.length),i=e-1;0<=i&&128==(192&t[i]);)i--;return i<0||0===i?e:i+a[t[i]]>e?i:e}(e),l=e;o!==e.length&&(n.uint8array?(l=e.subarray(0,o),this.leftOver=e.subarray(o,e.length)):(l=e.slice(0,o),this.leftOver=e.slice(o,e.length))),this.push({data:i.utf8decode(l),meta:t.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=h,s.inherits(c,o),c.prototype.processChunk=function(t){this.push({data:i.utf8encode(t.data),meta:t.meta})},i.Utf8EncodeWorker=c},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(t,e,i){var s=t("./support"),n=t("./base64"),r=t("./nodejsUtils"),o=t("./external");function a(t){return t}function l(t,e){for(var i=0;i<t.length;++i)e[i]=255&t.charCodeAt(i);return e}t("setimmediate"),i.newBlob=function(t,e){i.checkSupport("blob");try{return new Blob([t],{type:e})}catch(i){try{var s=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return s.append(t),s.getBlob(e)}catch(t){throw new Error("Bug : can't construct the Blob.")}}};var h={stringifyByChunk:function(t,e,i){var s=[],n=0,r=t.length;if(r<=i)return String.fromCharCode.apply(null,t);for(;n<r;)"array"===e||"nodebuffer"===e?s.push(String.fromCharCode.apply(null,t.slice(n,Math.min(n+i,r)))):s.push(String.fromCharCode.apply(null,t.subarray(n,Math.min(n+i,r)))),n+=i;return s.join("")},stringifyByChar:function(t){for(var e="",i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return e},applyCanBeUsed:{uint8array:function(){try{return s.uint8array&&1===String.fromCharCode.apply(null,new Uint8Array(1)).length}catch(t){return!1}}(),nodebuffer:function(){try{return s.nodebuffer&&1===String.fromCharCode.apply(null,r.allocBuffer(1)).length}catch(t){return!1}}()}};function c(t){var e=65536,s=i.getTypeOf(t),n=!0;if("uint8array"===s?n=h.applyCanBeUsed.uint8array:"nodebuffer"===s&&(n=h.applyCanBeUsed.nodebuffer),n)for(;1<e;)try{return h.stringifyByChunk(t,s,e)}catch(t){e=Math.floor(e/2)}return h.stringifyByChar(t)}function d(t,e){for(var i=0;i<t.length;i++)e[i]=t[i];return e}i.applyFromCharCode=c;var u={};u.string={string:a,array:function(t){return l(t,new Array(t.length))},arraybuffer:function(t){return u.string.uint8array(t).buffer},uint8array:function(t){return l(t,new Uint8Array(t.length))},nodebuffer:function(t){return l(t,r.allocBuffer(t.length))}},u.array={string:c,array:a,arraybuffer:function(t){return new Uint8Array(t).buffer},uint8array:function(t){return new Uint8Array(t)},nodebuffer:function(t){return r.newBufferFrom(t)}},u.arraybuffer={string:function(t){return c(new Uint8Array(t))},array:function(t){return d(new Uint8Array(t),new Array(t.byteLength))},arraybuffer:a,uint8array:function(t){return new Uint8Array(t)},nodebuffer:function(t){return r.newBufferFrom(new Uint8Array(t))}},u.uint8array={string:c,array:function(t){return d(t,new Array(t.length))},arraybuffer:function(t){return t.buffer},uint8array:a,nodebuffer:function(t){return r.newBufferFrom(t)}},u.nodebuffer={string:c,array:function(t){return d(t,new Array(t.length))},arraybuffer:function(t){return u.nodebuffer.uint8array(t).buffer},uint8array:function(t){return d(t,new Uint8Array(t.length))},nodebuffer:a},i.transformTo=function(t,e){if(e=e||"",!t)return e;i.checkSupport(t);var s=i.getTypeOf(e);return u[s][t](e)},i.resolve=function(t){for(var e=t.split("/"),i=[],s=0;s<e.length;s++){var n=e[s];"."===n||""===n&&0!==s&&s!==e.length-1||(".."===n?i.pop():i.push(n))}return i.join("/")},i.getTypeOf=function(t){return"string"==typeof t?"string":"[object Array]"===Object.prototype.toString.call(t)?"array":s.nodebuffer&&r.isBuffer(t)?"nodebuffer":s.uint8array&&t instanceof Uint8Array?"uint8array":s.arraybuffer&&t instanceof ArrayBuffer?"arraybuffer":void 0},i.checkSupport=function(t){if(!s[t.toLowerCase()])throw new Error(t+" is not supported by this platform")},i.MAX_VALUE_16BITS=65535,i.MAX_VALUE_32BITS=-1,i.pretty=function(t){var e,i,s="";for(i=0;i<(t||"").length;i++)s+="\\x"+((e=t.charCodeAt(i))<16?"0":"")+e.toString(16).toUpperCase();return s},i.delay=function(t,e,i){setImmediate(function(){t.apply(i||null,e||[])})},i.inherits=function(t,e){function i(){}i.prototype=e.prototype,t.prototype=new i},i.extend=function(){var t,e,i={};for(t=0;t<arguments.length;t++)for(e in arguments[t])Object.prototype.hasOwnProperty.call(arguments[t],e)&&void 0===i[e]&&(i[e]=arguments[t][e]);return i},i.prepareContent=function(t,e,r,a,h){return o.Promise.resolve(e).then(function(t){return s.blob&&(t instanceof Blob||-1!==["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(t)))&&"undefined"!=typeof FileReader?new o.Promise(function(e,i){var s=new FileReader;s.onload=function(t){e(t.target.result)},s.onerror=function(t){i(t.target.error)},s.readAsArrayBuffer(t)}):t}).then(function(e){var c,d=i.getTypeOf(e);return d?("arraybuffer"===d?e=i.transformTo("uint8array",e):"string"===d&&(h?e=n.decode(e):r&&!0!==a&&(e=l(c=e,s.uint8array?new Uint8Array(c.length):new Array(c.length)))),e):o.Promise.reject(new Error("Can't read the data of '"+t+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(t,e,i){var s=t("./reader/readerFor"),n=t("./utils"),r=t("./signature"),o=t("./zipEntry"),a=t("./support");function l(t){this.files=[],this.loadOptions=t}l.prototype={checkSignature:function(t){if(!this.reader.readAndCheckSignature(t)){this.reader.index-=4;var e=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+n.pretty(e)+", expected "+n.pretty(t)+")")}},isSignature:function(t,e){var i=this.reader.index;this.reader.setIndex(t);var s=this.reader.readString(4)===e;return this.reader.setIndex(i),s},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var t=this.reader.readData(this.zipCommentLength),e=a.uint8array?"uint8array":"array",i=n.transformTo(e,t);this.zipComment=this.loadOptions.decodeFileName(i)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var t,e,i,s=this.zip64EndOfCentralSize-44;0<s;)t=this.reader.readInt(2),e=this.reader.readInt(4),i=this.reader.readData(e),this.zip64ExtensibleData[t]={id:t,length:e,value:i}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var t,e;for(t=0;t<this.files.length;t++)e=this.files[t],this.reader.setIndex(e.localHeaderOffset),this.checkSignature(r.LOCAL_FILE_HEADER),e.readLocalPart(this.reader),e.handleUTF8(),e.processAttributes()},readCentralDir:function(){var t;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(r.CENTRAL_FILE_HEADER);)(t=new o({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(t);if(this.centralDirRecords!==this.files.length&&0!==this.centralDirRecords&&0===this.files.length)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var t=this.reader.lastIndexOfSignature(r.CENTRAL_DIRECTORY_END);if(t<0)throw this.isSignature(0,r.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(t);var e=t;if(this.checkSignature(r.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===n.MAX_VALUE_16BITS||this.diskWithCentralDirStart===n.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===n.MAX_VALUE_16BITS||this.centralDirRecords===n.MAX_VALUE_16BITS||this.centralDirSize===n.MAX_VALUE_32BITS||this.centralDirOffset===n.MAX_VALUE_32BITS){if(this.zip64=!0,(t=this.reader.lastIndexOfSignature(r.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(t),this.checkSignature(r.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,r.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(r.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(r.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var i=this.centralDirOffset+this.centralDirSize;this.zip64&&(i+=20,i+=12+this.zip64EndOfCentralSize);var s=e-i;if(0<s)this.isSignature(e,r.CENTRAL_FILE_HEADER)||(this.reader.zero=s);else if(s<0)throw new Error("Corrupted zip: missing "+Math.abs(s)+" bytes.")},prepareReader:function(t){this.reader=s(t)},load:function(t){this.prepareReader(t),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},e.exports=l},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(t,e,i){var s=t("./reader/readerFor"),n=t("./utils"),r=t("./compressedObject"),o=t("./crc32"),a=t("./utf8"),l=t("./compressions"),h=t("./support");function c(t,e){this.options=t,this.loadOptions=e}c.prototype={isEncrypted:function(){return!(1&~this.bitFlag)},useUTF8:function(){return!(2048&~this.bitFlag)},readLocalPart:function(t){var e,i;if(t.skip(22),this.fileNameLength=t.readInt(2),i=t.readInt(2),this.fileName=t.readData(this.fileNameLength),t.skip(i),-1===this.compressedSize||-1===this.uncompressedSize)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(null===(e=function(t){for(var e in l)if(Object.prototype.hasOwnProperty.call(l,e)&&l[e].magic===t)return l[e];return null}(this.compressionMethod)))throw new Error("Corrupted zip : compression "+n.pretty(this.compressionMethod)+" unknown (inner file : "+n.transformTo("string",this.fileName)+")");this.decompressed=new r(this.compressedSize,this.uncompressedSize,this.crc32,e,t.readData(this.compressedSize))},readCentralPart:function(t){this.versionMadeBy=t.readInt(2),t.skip(2),this.bitFlag=t.readInt(2),this.compressionMethod=t.readString(2),this.date=t.readDate(),this.crc32=t.readInt(4),this.compressedSize=t.readInt(4),this.uncompressedSize=t.readInt(4);var e=t.readInt(2);if(this.extraFieldsLength=t.readInt(2),this.fileCommentLength=t.readInt(2),this.diskNumberStart=t.readInt(2),this.internalFileAttributes=t.readInt(2),this.externalFileAttributes=t.readInt(4),this.localHeaderOffset=t.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");t.skip(e),this.readExtraFields(t),this.parseZIP64ExtraField(t),this.fileComment=t.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var t=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),0==t&&(this.dosPermissions=63&this.externalFileAttributes),3==t&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var t=s(this.extraFields[1].value);this.uncompressedSize===n.MAX_VALUE_32BITS&&(this.uncompressedSize=t.readInt(8)),this.compressedSize===n.MAX_VALUE_32BITS&&(this.compressedSize=t.readInt(8)),this.localHeaderOffset===n.MAX_VALUE_32BITS&&(this.localHeaderOffset=t.readInt(8)),this.diskNumberStart===n.MAX_VALUE_32BITS&&(this.diskNumberStart=t.readInt(4))}},readExtraFields:function(t){var e,i,s,n=t.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});t.index+4<n;)e=t.readInt(2),i=t.readInt(2),s=t.readData(i),this.extraFields[e]={id:e,length:i,value:s};t.setIndex(n)},handleUTF8:function(){var t=h.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=a.utf8decode(this.fileName),this.fileCommentStr=a.utf8decode(this.fileComment);else{var e=this.findExtraFieldUnicodePath();if(null!==e)this.fileNameStr=e;else{var i=n.transformTo(t,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(i)}var s=this.findExtraFieldUnicodeComment();if(null!==s)this.fileCommentStr=s;else{var r=n.transformTo(t,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(r)}}},findExtraFieldUnicodePath:function(){var t=this.extraFields[28789];if(t){var e=s(t.value);return 1!==e.readInt(1)||o(this.fileName)!==e.readInt(4)?null:a.utf8decode(e.readData(t.length-5))}return null},findExtraFieldUnicodeComment:function(){var t=this.extraFields[25461];if(t){var e=s(t.value);return 1!==e.readInt(1)||o(this.fileComment)!==e.readInt(4)?null:a.utf8decode(e.readData(t.length-5))}return null}},e.exports=c},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(t,e,i){function s(t,e,i){this.name=t,this.dir=i.dir,this.date=i.date,this.comment=i.comment,this.unixPermissions=i.unixPermissions,this.dosPermissions=i.dosPermissions,this._data=e,this._dataBinary=i.binary,this.options={compression:i.compression,compressionOptions:i.compressionOptions}}var n=t("./stream/StreamHelper"),r=t("./stream/DataWorker"),o=t("./utf8"),a=t("./compressedObject"),l=t("./stream/GenericWorker");s.prototype={internalStream:function(t){var e=null,i="string";try{if(!t)throw new Error("No output type specified.");var s="string"===(i=t.toLowerCase())||"text"===i;"binarystring"!==i&&"text"!==i||(i="string"),e=this._decompressWorker();var r=!this._dataBinary;r&&!s&&(e=e.pipe(new o.Utf8EncodeWorker)),!r&&s&&(e=e.pipe(new o.Utf8DecodeWorker))}catch(t){(e=new l("error")).error(t)}return new n(e,i,"")},async:function(t,e){return this.internalStream(t).accumulate(e)},nodeStream:function(t,e){return this.internalStream(t||"nodebuffer").toNodejsStream(e)},_compressWorker:function(t,e){if(this._data instanceof a&&this._data.compression.magic===t.magic)return this._data.getCompressedWorker();var i=this._decompressWorker();return this._dataBinary||(i=i.pipe(new o.Utf8EncodeWorker)),a.createWorkerFrom(i,t,e)},_decompressWorker:function(){return this._data instanceof a?this._data.getContentWorker():this._data instanceof l?this._data:new r(this._data)}};for(var h=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],c=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},d=0;d<h.length;d++)s.prototype[h[d]]=c;e.exports=s},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(t,e,i){(function(t){var i,s,n=t.MutationObserver||t.WebKitMutationObserver;if(n){var r=0,o=new n(c),a=t.document.createTextNode("");o.observe(a,{characterData:!0}),i=function(){a.data=r=++r%2}}else if(t.setImmediate||void 0===t.MessageChannel)i="document"in t&&"onreadystatechange"in t.document.createElement("script")?function(){var e=t.document.createElement("script");e.onreadystatechange=function(){c(),e.onreadystatechange=null,e.parentNode.removeChild(e),e=null},t.document.documentElement.appendChild(e)}:function(){setTimeout(c,0)};else{var l=new t.MessageChannel;l.port1.onmessage=c,i=function(){l.port2.postMessage(0)}}var h=[];function c(){var t,e;s=!0;for(var i=h.length;i;){for(e=h,h=[],t=-1;++t<i;)e[t]();i=h.length}s=!1}e.exports=function(t){1!==h.push(t)||s||i()}}).call(this,void 0!==b?b:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],37:[function(t,e,i){var s=t("immediate");function n(){}var r={},o=["REJECTED"],a=["FULFILLED"],l=["PENDING"];function h(t){if("function"!=typeof t)throw new TypeError("resolver must be a function");this.state=l,this.queue=[],this.outcome=void 0,t!==n&&p(this,t)}function c(t,e,i){this.promise=t,"function"==typeof e&&(this.onFulfilled=e,this.callFulfilled=this.otherCallFulfilled),"function"==typeof i&&(this.onRejected=i,this.callRejected=this.otherCallRejected)}function d(t,e,i){s(function(){var s;try{s=e(i)}catch(e){return r.reject(t,e)}s===t?r.reject(t,new TypeError("Cannot resolve promise with itself")):r.resolve(t,s)})}function u(t){var e=t&&t.then;if(t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof e)return function(){e.apply(t,arguments)}}function p(t,e){var i=!1;function s(e){i||(i=!0,r.reject(t,e))}function n(e){i||(i=!0,r.resolve(t,e))}var o=f(function(){e(n,s)});"error"===o.status&&s(o.value)}function f(t,e){var i={};try{i.value=t(e),i.status="success"}catch(t){i.status="error",i.value=t}return i}(e.exports=h).prototype.finally=function(t){if("function"!=typeof t)return this;var e=this.constructor;return this.then(function(i){return e.resolve(t()).then(function(){return i})},function(i){return e.resolve(t()).then(function(){throw i})})},h.prototype.catch=function(t){return this.then(null,t)},h.prototype.then=function(t,e){if("function"!=typeof t&&this.state===a||"function"!=typeof e&&this.state===o)return this;var i=new this.constructor(n);return this.state!==l?d(i,this.state===a?t:e,this.outcome):this.queue.push(new c(i,t,e)),i},c.prototype.callFulfilled=function(t){r.resolve(this.promise,t)},c.prototype.otherCallFulfilled=function(t){d(this.promise,this.onFulfilled,t)},c.prototype.callRejected=function(t){r.reject(this.promise,t)},c.prototype.otherCallRejected=function(t){d(this.promise,this.onRejected,t)},r.resolve=function(t,e){var i=f(u,e);if("error"===i.status)return r.reject(t,i.value);var s=i.value;if(s)p(t,s);else{t.state=a,t.outcome=e;for(var n=-1,o=t.queue.length;++n<o;)t.queue[n].callFulfilled(e)}return t},r.reject=function(t,e){t.state=o,t.outcome=e;for(var i=-1,s=t.queue.length;++i<s;)t.queue[i].callRejected(e);return t},h.resolve=function(t){return t instanceof this?t:r.resolve(new this(n),t)},h.reject=function(t){var e=new this(n);return r.reject(e,t)},h.all=function(t){var e=this;if("[object Array]"!==Object.prototype.toString.call(t))return this.reject(new TypeError("must be an array"));var i=t.length,s=!1;if(!i)return this.resolve([]);for(var o=new Array(i),a=0,l=-1,h=new this(n);++l<i;)c(t[l],l);return h;function c(t,n){e.resolve(t).then(function(t){o[n]=t,++a!==i||s||(s=!0,r.resolve(h,o))},function(t){s||(s=!0,r.reject(h,t))})}},h.race=function(t){var e=this;if("[object Array]"!==Object.prototype.toString.call(t))return this.reject(new TypeError("must be an array"));var i=t.length,s=!1;if(!i)return this.resolve([]);for(var o,a=-1,l=new this(n);++a<i;)o=t[a],e.resolve(o).then(function(t){s||(s=!0,r.resolve(l,t))},function(t){s||(s=!0,r.reject(l,t))});return l}},{immediate:36}],38:[function(t,e,i){var s={};(0,t("./lib/utils/common").assign)(s,t("./lib/deflate"),t("./lib/inflate"),t("./lib/zlib/constants")),e.exports=s},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(t,e,i){var s=t("./zlib/deflate"),n=t("./utils/common"),r=t("./utils/strings"),o=t("./zlib/messages"),a=t("./zlib/zstream"),l=Object.prototype.toString,h=0,c=-1,d=0,u=8;function p(t){if(!(this instanceof p))return new p(t);this.options=n.assign({level:c,method:u,chunkSize:16384,windowBits:15,memLevel:8,strategy:d,to:""},t||{});var e=this.options;e.raw&&0<e.windowBits?e.windowBits=-e.windowBits:e.gzip&&0<e.windowBits&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var i=s.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==h)throw new Error(o[i]);if(e.header&&s.deflateSetHeader(this.strm,e.header),e.dictionary){var f;if(f="string"==typeof e.dictionary?r.string2buf(e.dictionary):"[object ArrayBuffer]"===l.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,(i=s.deflateSetDictionary(this.strm,f))!==h)throw new Error(o[i]);this._dict_set=!0}}function f(t,e){var i=new p(e);if(i.push(t,!0),i.err)throw i.msg||o[i.err];return i.result}p.prototype.push=function(t,e){var i,o,a=this.strm,c=this.options.chunkSize;if(this.ended)return!1;o=e===~~e?e:!0===e?4:0,"string"==typeof t?a.input=r.string2buf(t):"[object ArrayBuffer]"===l.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;do{if(0===a.avail_out&&(a.output=new n.Buf8(c),a.next_out=0,a.avail_out=c),1!==(i=s.deflate(a,o))&&i!==h)return this.onEnd(i),!(this.ended=!0);0!==a.avail_out&&(0!==a.avail_in||4!==o&&2!==o)||("string"===this.options.to?this.onData(r.buf2binstring(n.shrinkBuf(a.output,a.next_out))):this.onData(n.shrinkBuf(a.output,a.next_out)))}while((0<a.avail_in||0===a.avail_out)&&1!==i);return 4===o?(i=s.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===h):2!==o||(this.onEnd(h),!(a.avail_out=0))},p.prototype.onData=function(t){this.chunks.push(t)},p.prototype.onEnd=function(t){t===h&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=n.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},i.Deflate=p,i.deflate=f,i.deflateRaw=function(t,e){return(e=e||{}).raw=!0,f(t,e)},i.gzip=function(t,e){return(e=e||{}).gzip=!0,f(t,e)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(t,e,i){var s=t("./zlib/inflate"),n=t("./utils/common"),r=t("./utils/strings"),o=t("./zlib/constants"),a=t("./zlib/messages"),l=t("./zlib/zstream"),h=t("./zlib/gzheader"),c=Object.prototype.toString;function d(t){if(!(this instanceof d))return new d(t);this.options=n.assign({chunkSize:16384,windowBits:0,to:""},t||{});var e=this.options;e.raw&&0<=e.windowBits&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(0<=e.windowBits&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),15<e.windowBits&&e.windowBits<48&&!(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var i=s.inflateInit2(this.strm,e.windowBits);if(i!==o.Z_OK)throw new Error(a[i]);this.header=new h,s.inflateGetHeader(this.strm,this.header)}function u(t,e){var i=new d(e);if(i.push(t,!0),i.err)throw i.msg||a[i.err];return i.result}d.prototype.push=function(t,e){var i,a,l,h,d,u,p=this.strm,f=this.options.chunkSize,m=this.options.dictionary,g=!1;if(this.ended)return!1;a=e===~~e?e:!0===e?o.Z_FINISH:o.Z_NO_FLUSH,"string"==typeof t?p.input=r.binstring2buf(t):"[object ArrayBuffer]"===c.call(t)?p.input=new Uint8Array(t):p.input=t,p.next_in=0,p.avail_in=p.input.length;do{if(0===p.avail_out&&(p.output=new n.Buf8(f),p.next_out=0,p.avail_out=f),(i=s.inflate(p,o.Z_NO_FLUSH))===o.Z_NEED_DICT&&m&&(u="string"==typeof m?r.string2buf(m):"[object ArrayBuffer]"===c.call(m)?new Uint8Array(m):m,i=s.inflateSetDictionary(this.strm,u)),i===o.Z_BUF_ERROR&&!0===g&&(i=o.Z_OK,g=!1),i!==o.Z_STREAM_END&&i!==o.Z_OK)return this.onEnd(i),!(this.ended=!0);p.next_out&&(0!==p.avail_out&&i!==o.Z_STREAM_END&&(0!==p.avail_in||a!==o.Z_FINISH&&a!==o.Z_SYNC_FLUSH)||("string"===this.options.to?(l=r.utf8border(p.output,p.next_out),h=p.next_out-l,d=r.buf2string(p.output,l),p.next_out=h,p.avail_out=f-h,h&&n.arraySet(p.output,p.output,l,h,0),this.onData(d)):this.onData(n.shrinkBuf(p.output,p.next_out)))),0===p.avail_in&&0===p.avail_out&&(g=!0)}while((0<p.avail_in||0===p.avail_out)&&i!==o.Z_STREAM_END);return i===o.Z_STREAM_END&&(a=o.Z_FINISH),a===o.Z_FINISH?(i=s.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===o.Z_OK):a!==o.Z_SYNC_FLUSH||(this.onEnd(o.Z_OK),!(p.avail_out=0))},d.prototype.onData=function(t){this.chunks.push(t)},d.prototype.onEnd=function(t){t===o.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=n.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},i.Inflate=d,i.inflate=u,i.inflateRaw=function(t,e){return(e=e||{}).raw=!0,u(t,e)},i.ungzip=u},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(t,e,i){var s="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;i.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var i=e.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(var s in i)i.hasOwnProperty(s)&&(t[s]=i[s])}}return t},i.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var n={arraySet:function(t,e,i,s,n){if(e.subarray&&t.subarray)t.set(e.subarray(i,i+s),n);else for(var r=0;r<s;r++)t[n+r]=e[i+r]},flattenChunks:function(t){var e,i,s,n,r,o;for(e=s=0,i=t.length;e<i;e++)s+=t[e].length;for(o=new Uint8Array(s),e=n=0,i=t.length;e<i;e++)r=t[e],o.set(r,n),n+=r.length;return o}},r={arraySet:function(t,e,i,s,n){for(var r=0;r<s;r++)t[n+r]=e[i+r]},flattenChunks:function(t){return[].concat.apply([],t)}};i.setTyped=function(t){t?(i.Buf8=Uint8Array,i.Buf16=Uint16Array,i.Buf32=Int32Array,i.assign(i,n)):(i.Buf8=Array,i.Buf16=Array,i.Buf32=Array,i.assign(i,r))},i.setTyped(s)},{}],42:[function(t,e,i){var s=t("./common"),n=!0,r=!0;try{String.fromCharCode.apply(null,[0])}catch(t){n=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){r=!1}for(var o=new s.Buf8(256),a=0;a<256;a++)o[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function l(t,e){if(e<65537&&(t.subarray&&r||!t.subarray&&n))return String.fromCharCode.apply(null,s.shrinkBuf(t,e));for(var i="",o=0;o<e;o++)i+=String.fromCharCode(t[o]);return i}o[254]=o[254]=1,i.string2buf=function(t){var e,i,n,r,o,a=t.length,l=0;for(r=0;r<a;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(n=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),l+=i<128?1:i<2048?2:i<65536?3:4;for(e=new s.Buf8(l),r=o=0;o<l;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(n=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),i<128?e[o++]=i:(i<2048?e[o++]=192|i>>>6:(i<65536?e[o++]=224|i>>>12:(e[o++]=240|i>>>18,e[o++]=128|i>>>12&63),e[o++]=128|i>>>6&63),e[o++]=128|63&i);return e},i.buf2binstring=function(t){return l(t,t.length)},i.binstring2buf=function(t){for(var e=new s.Buf8(t.length),i=0,n=e.length;i<n;i++)e[i]=t.charCodeAt(i);return e},i.buf2string=function(t,e){var i,s,n,r,a=e||t.length,h=new Array(2*a);for(i=s=0;i<a;)if((n=t[i++])<128)h[s++]=n;else if(4<(r=o[n]))h[s++]=65533,i+=r-1;else{for(n&=2===r?31:3===r?15:7;1<r&&i<a;)n=n<<6|63&t[i++],r--;1<r?h[s++]=65533:n<65536?h[s++]=n:(n-=65536,h[s++]=55296|n>>10&1023,h[s++]=56320|1023&n)}return l(h,s)},i.utf8border=function(t,e){var i;for((e=e||t.length)>t.length&&(e=t.length),i=e-1;0<=i&&128==(192&t[i]);)i--;return i<0||0===i?e:i+o[t[i]]>e?i:e}},{"./common":41}],43:[function(t,e,i){e.exports=function(t,e,i,s){for(var n=65535&t,r=t>>>16&65535,o=0;0!==i;){for(i-=o=2e3<i?2e3:i;r=r+(n=n+e[s++]|0)|0,--o;);n%=65521,r%=65521}return n|r<<16}},{}],44:[function(t,e,i){e.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(t,e,i){var s=function(){for(var t,e=[],i=0;i<256;i++){t=i;for(var s=0;s<8;s++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e}();e.exports=function(t,e,i,n){var r=s,o=n+i;t^=-1;for(var a=n;a<o;a++)t=t>>>8^r[255&(t^e[a])];return-1^t}},{}],46:[function(t,e,i){var s,n=t("../utils/common"),r=t("./trees"),o=t("./adler32"),a=t("./crc32"),l=t("./messages"),h=0,c=4,d=0,u=-2,p=-1,f=4,m=2,g=8,_=9,y=286,w=30,v=19,b=2*y+1,x=15,T=3,C=258,E=C+T+1,S=42,A=113,O=1,P=2,I=3,M=4;function D(t,e){return t.msg=l[e],e}function k(t){return(t<<1)-(4<t?9:0)}function z(t){for(var e=t.length;0<=--e;)t[e]=0}function B(t){var e=t.state,i=e.pending;i>t.avail_out&&(i=t.avail_out),0!==i&&(n.arraySet(t.output,e.pending_buf,e.pending_out,i,t.next_out),t.next_out+=i,e.pending_out+=i,t.total_out+=i,t.avail_out-=i,e.pending-=i,0===e.pending&&(e.pending_out=0))}function N(t,e){r._tr_flush_block(t,0<=t.block_start?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,B(t.strm)}function U(t,e){t.pending_buf[t.pending++]=e}function L(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function R(t,e){var i,s,n=t.max_chain_length,r=t.strstart,o=t.prev_length,a=t.nice_match,l=t.strstart>t.w_size-E?t.strstart-(t.w_size-E):0,h=t.window,c=t.w_mask,d=t.prev,u=t.strstart+C,p=h[r+o-1],f=h[r+o];t.prev_length>=t.good_match&&(n>>=2),a>t.lookahead&&(a=t.lookahead);do{if(h[(i=e)+o]===f&&h[i+o-1]===p&&h[i]===h[r]&&h[++i]===h[r+1]){r+=2,i++;do{}while(h[++r]===h[++i]&&h[++r]===h[++i]&&h[++r]===h[++i]&&h[++r]===h[++i]&&h[++r]===h[++i]&&h[++r]===h[++i]&&h[++r]===h[++i]&&h[++r]===h[++i]&&r<u);if(s=C-(u-r),r=u-C,o<s){if(t.match_start=e,a<=(o=s))break;p=h[r+o-1],f=h[r+o]}}}while((e=d[e&c])>l&&0!=--n);return o<=t.lookahead?o:t.lookahead}function F(t){var e,i,s,r,l,h,c,d,u,p,f=t.w_size;do{if(r=t.window_size-t.lookahead-t.strstart,t.strstart>=f+(f-E)){for(n.arraySet(t.window,t.window,f,f,0),t.match_start-=f,t.strstart-=f,t.block_start-=f,e=i=t.hash_size;s=t.head[--e],t.head[e]=f<=s?s-f:0,--i;);for(e=i=f;s=t.prev[--e],t.prev[e]=f<=s?s-f:0,--i;);r+=f}if(0===t.strm.avail_in)break;if(h=t.strm,c=t.window,d=t.strstart+t.lookahead,p=void 0,(u=r)<(p=h.avail_in)&&(p=u),i=0===p?0:(h.avail_in-=p,n.arraySet(c,h.input,h.next_in,p,d),1===h.state.wrap?h.adler=o(h.adler,c,p,d):2===h.state.wrap&&(h.adler=a(h.adler,c,p,d)),h.next_in+=p,h.total_in+=p,p),t.lookahead+=i,t.lookahead+t.insert>=T)for(l=t.strstart-t.insert,t.ins_h=t.window[l],t.ins_h=(t.ins_h<<t.hash_shift^t.window[l+1])&t.hash_mask;t.insert&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[l+T-1])&t.hash_mask,t.prev[l&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=l,l++,t.insert--,!(t.lookahead+t.insert<T)););}while(t.lookahead<E&&0!==t.strm.avail_in)}function V(t,e){for(var i,s;;){if(t.lookahead<E){if(F(t),t.lookahead<E&&e===h)return O;if(0===t.lookahead)break}if(i=0,t.lookahead>=T&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+T-1])&t.hash_mask,i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==i&&t.strstart-i<=t.w_size-E&&(t.match_length=R(t,i)),t.match_length>=T)if(s=r._tr_tally(t,t.strstart-t.match_start,t.match_length-T),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=T){for(t.match_length--;t.strstart++,t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+T-1])&t.hash_mask,i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart,0!=--t.match_length;);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+1])&t.hash_mask;else s=r._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(s&&(N(t,!1),0===t.strm.avail_out))return O}return t.insert=t.strstart<T-1?t.strstart:T-1,e===c?(N(t,!0),0===t.strm.avail_out?I:M):t.last_lit&&(N(t,!1),0===t.strm.avail_out)?O:P}function j(t,e){for(var i,s,n;;){if(t.lookahead<E){if(F(t),t.lookahead<E&&e===h)return O;if(0===t.lookahead)break}if(i=0,t.lookahead>=T&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+T-1])&t.hash_mask,i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=T-1,0!==i&&t.prev_length<t.max_lazy_match&&t.strstart-i<=t.w_size-E&&(t.match_length=R(t,i),t.match_length<=5&&(1===t.strategy||t.match_length===T&&4096<t.strstart-t.match_start)&&(t.match_length=T-1)),t.prev_length>=T&&t.match_length<=t.prev_length){for(n=t.strstart+t.lookahead-T,s=r._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-T),t.lookahead-=t.prev_length-1,t.prev_length-=2;++t.strstart<=n&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+T-1])&t.hash_mask,i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!=--t.prev_length;);if(t.match_available=0,t.match_length=T-1,t.strstart++,s&&(N(t,!1),0===t.strm.avail_out))return O}else if(t.match_available){if((s=r._tr_tally(t,0,t.window[t.strstart-1]))&&N(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return O}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(s=r._tr_tally(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<T-1?t.strstart:T-1,e===c?(N(t,!0),0===t.strm.avail_out?I:M):t.last_lit&&(N(t,!1),0===t.strm.avail_out)?O:P}function H(t,e,i,s,n){this.good_length=t,this.max_lazy=e,this.nice_length=i,this.max_chain=s,this.func=n}function Z(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=g,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new n.Buf16(2*b),this.dyn_dtree=new n.Buf16(2*(2*w+1)),this.bl_tree=new n.Buf16(2*(2*v+1)),z(this.dyn_ltree),z(this.dyn_dtree),z(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new n.Buf16(x+1),this.heap=new n.Buf16(2*y+1),z(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new n.Buf16(2*y+1),z(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function $(t){var e;return t&&t.state?(t.total_in=t.total_out=0,t.data_type=m,(e=t.state).pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?S:A,t.adler=2===e.wrap?0:1,e.last_flush=h,r._tr_init(e),d):D(t,u)}function W(t){var e,i=$(t);return i===d&&((e=t.state).window_size=2*e.w_size,z(e.head),e.max_lazy_match=s[e.level].max_lazy,e.good_match=s[e.level].good_length,e.nice_match=s[e.level].nice_length,e.max_chain_length=s[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=T-1,e.match_available=0,e.ins_h=0),i}function Y(t,e,i,s,r,o){if(!t)return u;var a=1;if(e===p&&(e=6),s<0?(a=0,s=-s):15<s&&(a=2,s-=16),r<1||_<r||i!==g||s<8||15<s||e<0||9<e||o<0||f<o)return D(t,u);8===s&&(s=9);var l=new Z;return(t.state=l).strm=t,l.wrap=a,l.gzhead=null,l.w_bits=s,l.w_size=1<<l.w_bits,l.w_mask=l.w_size-1,l.hash_bits=r+7,l.hash_size=1<<l.hash_bits,l.hash_mask=l.hash_size-1,l.hash_shift=~~((l.hash_bits+T-1)/T),l.window=new n.Buf8(2*l.w_size),l.head=new n.Buf16(l.hash_size),l.prev=new n.Buf16(l.w_size),l.lit_bufsize=1<<r+6,l.pending_buf_size=4*l.lit_bufsize,l.pending_buf=new n.Buf8(l.pending_buf_size),l.d_buf=1*l.lit_bufsize,l.l_buf=3*l.lit_bufsize,l.level=e,l.strategy=o,l.method=i,W(t)}s=[new H(0,0,0,0,function(t,e){var i=65535;for(i>t.pending_buf_size-5&&(i=t.pending_buf_size-5);;){if(t.lookahead<=1){if(F(t),0===t.lookahead&&e===h)return O;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var s=t.block_start+i;if((0===t.strstart||t.strstart>=s)&&(t.lookahead=t.strstart-s,t.strstart=s,N(t,!1),0===t.strm.avail_out))return O;if(t.strstart-t.block_start>=t.w_size-E&&(N(t,!1),0===t.strm.avail_out))return O}return t.insert=0,e===c?(N(t,!0),0===t.strm.avail_out?I:M):(t.strstart>t.block_start&&(N(t,!1),t.strm.avail_out),O)}),new H(4,4,8,4,V),new H(4,5,16,8,V),new H(4,6,32,32,V),new H(4,4,16,16,j),new H(8,16,32,32,j),new H(8,16,128,128,j),new H(8,32,128,256,j),new H(32,128,258,1024,j),new H(32,258,258,4096,j)],i.deflateInit=function(t,e){return Y(t,e,g,15,8,0)},i.deflateInit2=Y,i.deflateReset=W,i.deflateResetKeep=$,i.deflateSetHeader=function(t,e){return t&&t.state?2!==t.state.wrap?u:(t.state.gzhead=e,d):u},i.deflate=function(t,e){var i,n,o,l;if(!t||!t.state||5<e||e<0)return t?D(t,u):u;if(n=t.state,!t.output||!t.input&&0!==t.avail_in||666===n.status&&e!==c)return D(t,0===t.avail_out?-5:u);if(n.strm=t,i=n.last_flush,n.last_flush=e,n.status===S)if(2===n.wrap)t.adler=0,U(n,31),U(n,139),U(n,8),n.gzhead?(U(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),U(n,255&n.gzhead.time),U(n,n.gzhead.time>>8&255),U(n,n.gzhead.time>>16&255),U(n,n.gzhead.time>>24&255),U(n,9===n.level?2:2<=n.strategy||n.level<2?4:0),U(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(U(n,255&n.gzhead.extra.length),U(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(t.adler=a(t.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69):(U(n,0),U(n,0),U(n,0),U(n,0),U(n,0),U(n,9===n.level?2:2<=n.strategy||n.level<2?4:0),U(n,3),n.status=A);else{var p=g+(n.w_bits-8<<4)<<8;p|=(2<=n.strategy||n.level<2?0:n.level<6?1:6===n.level?2:3)<<6,0!==n.strstart&&(p|=32),p+=31-p%31,n.status=A,L(n,p),0!==n.strstart&&(L(n,t.adler>>>16),L(n,65535&t.adler)),t.adler=1}if(69===n.status)if(n.gzhead.extra){for(o=n.pending;n.gzindex<(65535&n.gzhead.extra.length)&&(n.pending!==n.pending_buf_size||(n.gzhead.hcrc&&n.pending>o&&(t.adler=a(t.adler,n.pending_buf,n.pending-o,o)),B(t),o=n.pending,n.pending!==n.pending_buf_size));)U(n,255&n.gzhead.extra[n.gzindex]),n.gzindex++;n.gzhead.hcrc&&n.pending>o&&(t.adler=a(t.adler,n.pending_buf,n.pending-o,o)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=73)}else n.status=73;if(73===n.status)if(n.gzhead.name){o=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>o&&(t.adler=a(t.adler,n.pending_buf,n.pending-o,o)),B(t),o=n.pending,n.pending===n.pending_buf_size)){l=1;break}l=n.gzindex<n.gzhead.name.length?255&n.gzhead.name.charCodeAt(n.gzindex++):0,U(n,l)}while(0!==l);n.gzhead.hcrc&&n.pending>o&&(t.adler=a(t.adler,n.pending_buf,n.pending-o,o)),0===l&&(n.gzindex=0,n.status=91)}else n.status=91;if(91===n.status)if(n.gzhead.comment){o=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>o&&(t.adler=a(t.adler,n.pending_buf,n.pending-o,o)),B(t),o=n.pending,n.pending===n.pending_buf_size)){l=1;break}l=n.gzindex<n.gzhead.comment.length?255&n.gzhead.comment.charCodeAt(n.gzindex++):0,U(n,l)}while(0!==l);n.gzhead.hcrc&&n.pending>o&&(t.adler=a(t.adler,n.pending_buf,n.pending-o,o)),0===l&&(n.status=103)}else n.status=103;if(103===n.status&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&B(t),n.pending+2<=n.pending_buf_size&&(U(n,255&t.adler),U(n,t.adler>>8&255),t.adler=0,n.status=A)):n.status=A),0!==n.pending){if(B(t),0===t.avail_out)return n.last_flush=-1,d}else if(0===t.avail_in&&k(e)<=k(i)&&e!==c)return D(t,-5);if(666===n.status&&0!==t.avail_in)return D(t,-5);if(0!==t.avail_in||0!==n.lookahead||e!==h&&666!==n.status){var f=2===n.strategy?function(t,e){for(var i;;){if(0===t.lookahead&&(F(t),0===t.lookahead)){if(e===h)return O;break}if(t.match_length=0,i=r._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(N(t,!1),0===t.strm.avail_out))return O}return t.insert=0,e===c?(N(t,!0),0===t.strm.avail_out?I:M):t.last_lit&&(N(t,!1),0===t.strm.avail_out)?O:P}(n,e):3===n.strategy?function(t,e){for(var i,s,n,o,a=t.window;;){if(t.lookahead<=C){if(F(t),t.lookahead<=C&&e===h)return O;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=T&&0<t.strstart&&(s=a[n=t.strstart-1])===a[++n]&&s===a[++n]&&s===a[++n]){o=t.strstart+C;do{}while(s===a[++n]&&s===a[++n]&&s===a[++n]&&s===a[++n]&&s===a[++n]&&s===a[++n]&&s===a[++n]&&s===a[++n]&&n<o);t.match_length=C-(o-n),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=T?(i=r._tr_tally(t,1,t.match_length-T),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=r._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(N(t,!1),0===t.strm.avail_out))return O}return t.insert=0,e===c?(N(t,!0),0===t.strm.avail_out?I:M):t.last_lit&&(N(t,!1),0===t.strm.avail_out)?O:P}(n,e):s[n.level].func(n,e);if(f!==I&&f!==M||(n.status=666),f===O||f===I)return 0===t.avail_out&&(n.last_flush=-1),d;if(f===P&&(1===e?r._tr_align(n):5!==e&&(r._tr_stored_block(n,0,0,!1),3===e&&(z(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),B(t),0===t.avail_out))return n.last_flush=-1,d}return e!==c?d:n.wrap<=0?1:(2===n.wrap?(U(n,255&t.adler),U(n,t.adler>>8&255),U(n,t.adler>>16&255),U(n,t.adler>>24&255),U(n,255&t.total_in),U(n,t.total_in>>8&255),U(n,t.total_in>>16&255),U(n,t.total_in>>24&255)):(L(n,t.adler>>>16),L(n,65535&t.adler)),B(t),0<n.wrap&&(n.wrap=-n.wrap),0!==n.pending?d:1)},i.deflateEnd=function(t){var e;return t&&t.state?(e=t.state.status)!==S&&69!==e&&73!==e&&91!==e&&103!==e&&e!==A&&666!==e?D(t,u):(t.state=null,e===A?D(t,-3):d):u},i.deflateSetDictionary=function(t,e){var i,s,r,a,l,h,c,p,f=e.length;if(!t||!t.state)return u;if(2===(a=(i=t.state).wrap)||1===a&&i.status!==S||i.lookahead)return u;for(1===a&&(t.adler=o(t.adler,e,f,0)),i.wrap=0,f>=i.w_size&&(0===a&&(z(i.head),i.strstart=0,i.block_start=0,i.insert=0),p=new n.Buf8(i.w_size),n.arraySet(p,e,f-i.w_size,i.w_size,0),e=p,f=i.w_size),l=t.avail_in,h=t.next_in,c=t.input,t.avail_in=f,t.next_in=0,t.input=e,F(i);i.lookahead>=T;){for(s=i.strstart,r=i.lookahead-(T-1);i.ins_h=(i.ins_h<<i.hash_shift^i.window[s+T-1])&i.hash_mask,i.prev[s&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=s,s++,--r;);i.strstart=s,i.lookahead=T-1,F(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=T-1,i.match_available=0,t.next_in=h,t.input=c,t.avail_in=l,i.wrap=a,d},i.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(t,e,i){e.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(t,e,i){e.exports=function(t,e){var i,s,n,r,o,a,l,h,c,d,u,p,f,m,g,_,y,w,v,b,x,T,C,E,S;i=t.state,s=t.next_in,E=t.input,n=s+(t.avail_in-5),r=t.next_out,S=t.output,o=r-(e-t.avail_out),a=r+(t.avail_out-257),l=i.dmax,h=i.wsize,c=i.whave,d=i.wnext,u=i.window,p=i.hold,f=i.bits,m=i.lencode,g=i.distcode,_=(1<<i.lenbits)-1,y=(1<<i.distbits)-1;t:do{f<15&&(p+=E[s++]<<f,f+=8,p+=E[s++]<<f,f+=8),w=m[p&_];e:for(;;){if(p>>>=v=w>>>24,f-=v,0==(v=w>>>16&255))S[r++]=65535&w;else{if(!(16&v)){if(!(64&v)){w=m[(65535&w)+(p&(1<<v)-1)];continue e}if(32&v){i.mode=12;break t}t.msg="invalid literal/length code",i.mode=30;break t}b=65535&w,(v&=15)&&(f<v&&(p+=E[s++]<<f,f+=8),b+=p&(1<<v)-1,p>>>=v,f-=v),f<15&&(p+=E[s++]<<f,f+=8,p+=E[s++]<<f,f+=8),w=g[p&y];i:for(;;){if(p>>>=v=w>>>24,f-=v,!(16&(v=w>>>16&255))){if(!(64&v)){w=g[(65535&w)+(p&(1<<v)-1)];continue i}t.msg="invalid distance code",i.mode=30;break t}if(x=65535&w,f<(v&=15)&&(p+=E[s++]<<f,(f+=8)<v&&(p+=E[s++]<<f,f+=8)),l<(x+=p&(1<<v)-1)){t.msg="invalid distance too far back",i.mode=30;break t}if(p>>>=v,f-=v,(v=r-o)<x){if(c<(v=x-v)&&i.sane){t.msg="invalid distance too far back",i.mode=30;break t}if(C=u,(T=0)===d){if(T+=h-v,v<b){for(b-=v;S[r++]=u[T++],--v;);T=r-x,C=S}}else if(d<v){if(T+=h+d-v,(v-=d)<b){for(b-=v;S[r++]=u[T++],--v;);if(T=0,d<b){for(b-=v=d;S[r++]=u[T++],--v;);T=r-x,C=S}}}else if(T+=d-v,v<b){for(b-=v;S[r++]=u[T++],--v;);T=r-x,C=S}for(;2<b;)S[r++]=C[T++],S[r++]=C[T++],S[r++]=C[T++],b-=3;b&&(S[r++]=C[T++],1<b&&(S[r++]=C[T++]))}else{for(T=r-x;S[r++]=S[T++],S[r++]=S[T++],S[r++]=S[T++],2<(b-=3););b&&(S[r++]=S[T++],1<b&&(S[r++]=S[T++]))}break}}break}}while(s<n&&r<a);s-=b=f>>3,p&=(1<<(f-=b<<3))-1,t.next_in=s,t.next_out=r,t.avail_in=s<n?n-s+5:5-(s-n),t.avail_out=r<a?a-r+257:257-(r-a),i.hold=p,i.bits=f}},{}],49:[function(t,e,i){var s=t("../utils/common"),n=t("./adler32"),r=t("./crc32"),o=t("./inffast"),a=t("./inftrees"),l=1,h=2,c=0,d=-2,u=1,p=852,f=592;function m(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function g(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function _(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=u,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new s.Buf32(p),e.distcode=e.distdyn=new s.Buf32(f),e.sane=1,e.back=-1,c):d}function y(t){var e;return t&&t.state?((e=t.state).wsize=0,e.whave=0,e.wnext=0,_(t)):d}function w(t,e){var i,s;return t&&t.state?(s=t.state,e<0?(i=0,e=-e):(i=1+(e>>4),e<48&&(e&=15)),e&&(e<8||15<e)?d:(null!==s.window&&s.wbits!==e&&(s.window=null),s.wrap=i,s.wbits=e,y(t))):d}function v(t,e){var i,s;return t?(s=new g,(t.state=s).window=null,(i=w(t,e))!==c&&(t.state=null),i):d}var b,x,T=!0;function C(t){if(T){var e;for(b=new s.Buf32(512),x=new s.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(a(l,t.lens,0,288,b,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;a(h,t.lens,0,32,x,0,t.work,{bits:5}),T=!1}t.lencode=b,t.lenbits=9,t.distcode=x,t.distbits=5}function E(t,e,i,n){var r,o=t.state;return null===o.window&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new s.Buf8(o.wsize)),n>=o.wsize?(s.arraySet(o.window,e,i-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(n<(r=o.wsize-o.wnext)&&(r=n),s.arraySet(o.window,e,i-n,r,o.wnext),(n-=r)?(s.arraySet(o.window,e,i-n,n,0),o.wnext=n,o.whave=o.wsize):(o.wnext+=r,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=r))),0}i.inflateReset=y,i.inflateReset2=w,i.inflateResetKeep=_,i.inflateInit=function(t){return v(t,15)},i.inflateInit2=v,i.inflate=function(t,e){var i,p,f,g,_,y,w,v,b,x,T,S,A,O,P,I,M,D,k,z,B,N,U,L,R=0,F=new s.Buf8(4),V=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!t||!t.state||!t.output||!t.input&&0!==t.avail_in)return d;12===(i=t.state).mode&&(i.mode=13),_=t.next_out,f=t.output,w=t.avail_out,g=t.next_in,p=t.input,y=t.avail_in,v=i.hold,b=i.bits,x=y,T=w,N=c;t:for(;;)switch(i.mode){case u:if(0===i.wrap){i.mode=13;break}for(;b<16;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}if(2&i.wrap&&35615===v){F[i.check=0]=255&v,F[1]=v>>>8&255,i.check=r(i.check,F,2,0),b=v=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&v)<<8)+(v>>8))%31){t.msg="incorrect header check",i.mode=30;break}if(8!=(15&v)){t.msg="unknown compression method",i.mode=30;break}if(b-=4,B=8+(15&(v>>>=4)),0===i.wbits)i.wbits=B;else if(B>i.wbits){t.msg="invalid window size",i.mode=30;break}i.dmax=1<<B,t.adler=i.check=1,i.mode=512&v?10:12,b=v=0;break;case 2:for(;b<16;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}if(i.flags=v,8!=(255&i.flags)){t.msg="unknown compression method",i.mode=30;break}if(57344&i.flags){t.msg="unknown header flags set",i.mode=30;break}i.head&&(i.head.text=v>>8&1),512&i.flags&&(F[0]=255&v,F[1]=v>>>8&255,i.check=r(i.check,F,2,0)),b=v=0,i.mode=3;case 3:for(;b<32;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}i.head&&(i.head.time=v),512&i.flags&&(F[0]=255&v,F[1]=v>>>8&255,F[2]=v>>>16&255,F[3]=v>>>24&255,i.check=r(i.check,F,4,0)),b=v=0,i.mode=4;case 4:for(;b<16;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}i.head&&(i.head.xflags=255&v,i.head.os=v>>8),512&i.flags&&(F[0]=255&v,F[1]=v>>>8&255,i.check=r(i.check,F,2,0)),b=v=0,i.mode=5;case 5:if(1024&i.flags){for(;b<16;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}i.length=v,i.head&&(i.head.extra_len=v),512&i.flags&&(F[0]=255&v,F[1]=v>>>8&255,i.check=r(i.check,F,2,0)),b=v=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&(y<(S=i.length)&&(S=y),S&&(i.head&&(B=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),s.arraySet(i.head.extra,p,g,S,B)),512&i.flags&&(i.check=r(i.check,p,S,g)),y-=S,g+=S,i.length-=S),i.length))break t;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===y)break t;for(S=0;B=p[g+S++],i.head&&B&&i.length<65536&&(i.head.name+=String.fromCharCode(B)),B&&S<y;);if(512&i.flags&&(i.check=r(i.check,p,S,g)),y-=S,g+=S,B)break t}else i.head&&(i.head.name=null);i.length=0,i.mode=8;case 8:if(4096&i.flags){if(0===y)break t;for(S=0;B=p[g+S++],i.head&&B&&i.length<65536&&(i.head.comment+=String.fromCharCode(B)),B&&S<y;);if(512&i.flags&&(i.check=r(i.check,p,S,g)),y-=S,g+=S,B)break t}else i.head&&(i.head.comment=null);i.mode=9;case 9:if(512&i.flags){for(;b<16;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}if(v!==(65535&i.check)){t.msg="header crc mismatch",i.mode=30;break}b=v=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),t.adler=i.check=0,i.mode=12;break;case 10:for(;b<32;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}t.adler=i.check=m(v),b=v=0,i.mode=11;case 11:if(0===i.havedict)return t.next_out=_,t.avail_out=w,t.next_in=g,t.avail_in=y,i.hold=v,i.bits=b,2;t.adler=i.check=1,i.mode=12;case 12:if(5===e||6===e)break t;case 13:if(i.last){v>>>=7&b,b-=7&b,i.mode=27;break}for(;b<3;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}switch(i.last=1&v,b-=1,3&(v>>>=1)){case 0:i.mode=14;break;case 1:if(C(i),i.mode=20,6!==e)break;v>>>=2,b-=2;break t;case 2:i.mode=17;break;case 3:t.msg="invalid block type",i.mode=30}v>>>=2,b-=2;break;case 14:for(v>>>=7&b,b-=7&b;b<32;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}if((65535&v)!=(v>>>16^65535)){t.msg="invalid stored block lengths",i.mode=30;break}if(i.length=65535&v,b=v=0,i.mode=15,6===e)break t;case 15:i.mode=16;case 16:if(S=i.length){if(y<S&&(S=y),w<S&&(S=w),0===S)break t;s.arraySet(f,p,g,S,_),y-=S,g+=S,w-=S,_+=S,i.length-=S;break}i.mode=12;break;case 17:for(;b<14;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}if(i.nlen=257+(31&v),v>>>=5,b-=5,i.ndist=1+(31&v),v>>>=5,b-=5,i.ncode=4+(15&v),v>>>=4,b-=4,286<i.nlen||30<i.ndist){t.msg="too many length or distance symbols",i.mode=30;break}i.have=0,i.mode=18;case 18:for(;i.have<i.ncode;){for(;b<3;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}i.lens[V[i.have++]]=7&v,v>>>=3,b-=3}for(;i.have<19;)i.lens[V[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,U={bits:i.lenbits},N=a(0,i.lens,0,19,i.lencode,0,i.work,U),i.lenbits=U.bits,N){t.msg="invalid code lengths set",i.mode=30;break}i.have=0,i.mode=19;case 19:for(;i.have<i.nlen+i.ndist;){for(;I=(R=i.lencode[v&(1<<i.lenbits)-1])>>>16&255,M=65535&R,!((P=R>>>24)<=b);){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}if(M<16)v>>>=P,b-=P,i.lens[i.have++]=M;else{if(16===M){for(L=P+2;b<L;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}if(v>>>=P,b-=P,0===i.have){t.msg="invalid bit length repeat",i.mode=30;break}B=i.lens[i.have-1],S=3+(3&v),v>>>=2,b-=2}else if(17===M){for(L=P+3;b<L;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}b-=P,B=0,S=3+(7&(v>>>=P)),v>>>=3,b-=3}else{for(L=P+7;b<L;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}b-=P,B=0,S=11+(127&(v>>>=P)),v>>>=7,b-=7}if(i.have+S>i.nlen+i.ndist){t.msg="invalid bit length repeat",i.mode=30;break}for(;S--;)i.lens[i.have++]=B}}if(30===i.mode)break;if(0===i.lens[256]){t.msg="invalid code -- missing end-of-block",i.mode=30;break}if(i.lenbits=9,U={bits:i.lenbits},N=a(l,i.lens,0,i.nlen,i.lencode,0,i.work,U),i.lenbits=U.bits,N){t.msg="invalid literal/lengths set",i.mode=30;break}if(i.distbits=6,i.distcode=i.distdyn,U={bits:i.distbits},N=a(h,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,U),i.distbits=U.bits,N){t.msg="invalid distances set",i.mode=30;break}if(i.mode=20,6===e)break t;case 20:i.mode=21;case 21:if(6<=y&&258<=w){t.next_out=_,t.avail_out=w,t.next_in=g,t.avail_in=y,i.hold=v,i.bits=b,o(t,T),_=t.next_out,f=t.output,w=t.avail_out,g=t.next_in,p=t.input,y=t.avail_in,v=i.hold,b=i.bits,12===i.mode&&(i.back=-1);break}for(i.back=0;I=(R=i.lencode[v&(1<<i.lenbits)-1])>>>16&255,M=65535&R,!((P=R>>>24)<=b);){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}if(I&&!(240&I)){for(D=P,k=I,z=M;I=(R=i.lencode[z+((v&(1<<D+k)-1)>>D)])>>>16&255,M=65535&R,!(D+(P=R>>>24)<=b);){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}v>>>=D,b-=D,i.back+=D}if(v>>>=P,b-=P,i.back+=P,i.length=M,0===I){i.mode=26;break}if(32&I){i.back=-1,i.mode=12;break}if(64&I){t.msg="invalid literal/length code",i.mode=30;break}i.extra=15&I,i.mode=22;case 22:if(i.extra){for(L=i.extra;b<L;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}i.length+=v&(1<<i.extra)-1,v>>>=i.extra,b-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;I=(R=i.distcode[v&(1<<i.distbits)-1])>>>16&255,M=65535&R,!((P=R>>>24)<=b);){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}if(!(240&I)){for(D=P,k=I,z=M;I=(R=i.distcode[z+((v&(1<<D+k)-1)>>D)])>>>16&255,M=65535&R,!(D+(P=R>>>24)<=b);){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}v>>>=D,b-=D,i.back+=D}if(v>>>=P,b-=P,i.back+=P,64&I){t.msg="invalid distance code",i.mode=30;break}i.offset=M,i.extra=15&I,i.mode=24;case 24:if(i.extra){for(L=i.extra;b<L;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}i.offset+=v&(1<<i.extra)-1,v>>>=i.extra,b-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){t.msg="invalid distance too far back",i.mode=30;break}i.mode=25;case 25:if(0===w)break t;if(S=T-w,i.offset>S){if((S=i.offset-S)>i.whave&&i.sane){t.msg="invalid distance too far back",i.mode=30;break}A=S>i.wnext?(S-=i.wnext,i.wsize-S):i.wnext-S,S>i.length&&(S=i.length),O=i.window}else O=f,A=_-i.offset,S=i.length;for(w<S&&(S=w),w-=S,i.length-=S;f[_++]=O[A++],--S;);0===i.length&&(i.mode=21);break;case 26:if(0===w)break t;f[_++]=i.length,w--,i.mode=21;break;case 27:if(i.wrap){for(;b<32;){if(0===y)break t;y--,v|=p[g++]<<b,b+=8}if(T-=w,t.total_out+=T,i.total+=T,T&&(t.adler=i.check=i.flags?r(i.check,f,T,_-T):n(i.check,f,T,_-T)),T=w,(i.flags?v:m(v))!==i.check){t.msg="incorrect data check",i.mode=30;break}b=v=0}i.mode=28;case 28:if(i.wrap&&i.flags){for(;b<32;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}if(v!==(4294967295&i.total)){t.msg="incorrect length check",i.mode=30;break}b=v=0}i.mode=29;case 29:N=1;break t;case 30:N=-3;break t;case 31:return-4;default:return d}return t.next_out=_,t.avail_out=w,t.next_in=g,t.avail_in=y,i.hold=v,i.bits=b,(i.wsize||T!==t.avail_out&&i.mode<30&&(i.mode<27||4!==e))&&E(t,t.output,t.next_out,T-t.avail_out)?(i.mode=31,-4):(x-=t.avail_in,T-=t.avail_out,t.total_in+=x,t.total_out+=T,i.total+=T,i.wrap&&T&&(t.adler=i.check=i.flags?r(i.check,f,T,t.next_out-T):n(i.check,f,T,t.next_out-T)),t.data_type=i.bits+(i.last?64:0)+(12===i.mode?128:0)+(20===i.mode||15===i.mode?256:0),(0==x&&0===T||4===e)&&N===c&&(N=-5),N)},i.inflateEnd=function(t){if(!t||!t.state)return d;var e=t.state;return e.window&&(e.window=null),t.state=null,c},i.inflateGetHeader=function(t,e){var i;return t&&t.state&&2&(i=t.state).wrap?((i.head=e).done=!1,c):d},i.inflateSetDictionary=function(t,e){var i,s=e.length;return t&&t.state?0!==(i=t.state).wrap&&11!==i.mode?d:11===i.mode&&n(1,e,s,0)!==i.check?-3:E(t,e,s,s)?(i.mode=31,-4):(i.havedict=1,c):d},i.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(t,e,i){var s=t("../utils/common"),n=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],r=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],o=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];e.exports=function(t,e,i,l,h,c,d,u){var p,f,m,g,_,y,w,v,b,x=u.bits,T=0,C=0,E=0,S=0,A=0,O=0,P=0,I=0,M=0,D=0,k=null,z=0,B=new s.Buf16(16),N=new s.Buf16(16),U=null,L=0;for(T=0;T<=15;T++)B[T]=0;for(C=0;C<l;C++)B[e[i+C]]++;for(A=x,S=15;1<=S&&0===B[S];S--);if(S<A&&(A=S),0===S)return h[c++]=20971520,h[c++]=20971520,u.bits=1,0;for(E=1;E<S&&0===B[E];E++);for(A<E&&(A=E),T=I=1;T<=15;T++)if(I<<=1,(I-=B[T])<0)return-1;if(0<I&&(0===t||1!==S))return-1;for(N[1]=0,T=1;T<15;T++)N[T+1]=N[T]+B[T];for(C=0;C<l;C++)0!==e[i+C]&&(d[N[e[i+C]]++]=C);if(y=0===t?(k=U=d,19):1===t?(k=n,z-=257,U=r,L-=257,256):(k=o,U=a,-1),T=E,_=c,P=C=D=0,m=-1,g=(M=1<<(O=A))-1,1===t&&852<M||2===t&&592<M)return 1;for(;;){for(w=T-P,b=d[C]<y?(v=0,d[C]):d[C]>y?(v=U[L+d[C]],k[z+d[C]]):(v=96,0),p=1<<T-P,E=f=1<<O;h[_+(D>>P)+(f-=p)]=w<<24|v<<16|b,0!==f;);for(p=1<<T-1;D&p;)p>>=1;if(0!==p?(D&=p-1,D+=p):D=0,C++,0==--B[T]){if(T===S)break;T=e[i+d[C]]}if(A<T&&(D&g)!==m){for(0===P&&(P=A),_+=E,I=1<<(O=T-P);O+P<S&&!((I-=B[O+P])<=0);)O++,I<<=1;if(M+=1<<O,1===t&&852<M||2===t&&592<M)return 1;h[m=D&g]=A<<24|O<<16|_-c}}return 0!==D&&(h[_+D]=T-P<<24|64<<16),u.bits=A,0}},{"../utils/common":41}],51:[function(t,e,i){e.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(t,e,i){var s=t("../utils/common"),n=0,r=1;function o(t){for(var e=t.length;0<=--e;)t[e]=0}var a=0,l=29,h=256,c=h+1+l,d=30,u=19,p=2*c+1,f=15,m=16,g=7,_=256,y=16,w=17,v=18,b=[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],x=[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],T=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],C=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],E=new Array(2*(c+2));o(E);var S=new Array(2*d);o(S);var A=new Array(512);o(A);var O=new Array(256);o(O);var P=new Array(l);o(P);var I,M,D,k=new Array(d);function z(t,e,i,s,n){this.static_tree=t,this.extra_bits=e,this.extra_base=i,this.elems=s,this.max_length=n,this.has_stree=t&&t.length}function B(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function N(t){return t<256?A[t]:A[256+(t>>>7)]}function U(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function L(t,e,i){t.bi_valid>m-i?(t.bi_buf|=e<<t.bi_valid&65535,U(t,t.bi_buf),t.bi_buf=e>>m-t.bi_valid,t.bi_valid+=i-m):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=i)}function R(t,e,i){L(t,i[2*e],i[2*e+1])}function F(t,e){for(var i=0;i|=1&t,t>>>=1,i<<=1,0<--e;);return i>>>1}function V(t,e,i){var s,n,r=new Array(f+1),o=0;for(s=1;s<=f;s++)r[s]=o=o+i[s-1]<<1;for(n=0;n<=e;n++){var a=t[2*n+1];0!==a&&(t[2*n]=F(r[a]++,a))}}function j(t){var e;for(e=0;e<c;e++)t.dyn_ltree[2*e]=0;for(e=0;e<d;e++)t.dyn_dtree[2*e]=0;for(e=0;e<u;e++)t.bl_tree[2*e]=0;t.dyn_ltree[2*_]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0}function H(t){8<t.bi_valid?U(t,t.bi_buf):0<t.bi_valid&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function Z(t,e,i,s){var n=2*e,r=2*i;return t[n]<t[r]||t[n]===t[r]&&s[e]<=s[i]}function $(t,e,i){for(var s=t.heap[i],n=i<<1;n<=t.heap_len&&(n<t.heap_len&&Z(e,t.heap[n+1],t.heap[n],t.depth)&&n++,!Z(e,s,t.heap[n],t.depth));)t.heap[i]=t.heap[n],i=n,n<<=1;t.heap[i]=s}function W(t,e,i){var s,n,r,o,a=0;if(0!==t.last_lit)for(;s=t.pending_buf[t.d_buf+2*a]<<8|t.pending_buf[t.d_buf+2*a+1],n=t.pending_buf[t.l_buf+a],a++,0===s?R(t,n,e):(R(t,(r=O[n])+h+1,e),0!==(o=b[r])&&L(t,n-=P[r],o),R(t,r=N(--s),i),0!==(o=x[r])&&L(t,s-=k[r],o)),a<t.last_lit;);R(t,_,e)}function Y(t,e){var i,s,n,r=e.dyn_tree,o=e.stat_desc.static_tree,a=e.stat_desc.has_stree,l=e.stat_desc.elems,h=-1;for(t.heap_len=0,t.heap_max=p,i=0;i<l;i++)0!==r[2*i]?(t.heap[++t.heap_len]=h=i,t.depth[i]=0):r[2*i+1]=0;for(;t.heap_len<2;)r[2*(n=t.heap[++t.heap_len]=h<2?++h:0)]=1,t.depth[n]=0,t.opt_len--,a&&(t.static_len-=o[2*n+1]);for(e.max_code=h,i=t.heap_len>>1;1<=i;i--)$(t,r,i);for(n=l;i=t.heap[1],t.heap[1]=t.heap[t.heap_len--],$(t,r,1),s=t.heap[1],t.heap[--t.heap_max]=i,t.heap[--t.heap_max]=s,r[2*n]=r[2*i]+r[2*s],t.depth[n]=(t.depth[i]>=t.depth[s]?t.depth[i]:t.depth[s])+1,r[2*i+1]=r[2*s+1]=n,t.heap[1]=n++,$(t,r,1),2<=t.heap_len;);t.heap[--t.heap_max]=t.heap[1],function(t,e){var i,s,n,r,o,a,l=e.dyn_tree,h=e.max_code,c=e.stat_desc.static_tree,d=e.stat_desc.has_stree,u=e.stat_desc.extra_bits,m=e.stat_desc.extra_base,g=e.stat_desc.max_length,_=0;for(r=0;r<=f;r++)t.bl_count[r]=0;for(l[2*t.heap[t.heap_max]+1]=0,i=t.heap_max+1;i<p;i++)g<(r=l[2*l[2*(s=t.heap[i])+1]+1]+1)&&(r=g,_++),l[2*s+1]=r,h<s||(t.bl_count[r]++,o=0,m<=s&&(o=u[s-m]),a=l[2*s],t.opt_len+=a*(r+o),d&&(t.static_len+=a*(c[2*s+1]+o)));if(0!==_){do{for(r=g-1;0===t.bl_count[r];)r--;t.bl_count[r]--,t.bl_count[r+1]+=2,t.bl_count[g]--,_-=2}while(0<_);for(r=g;0!==r;r--)for(s=t.bl_count[r];0!==s;)h<(n=t.heap[--i])||(l[2*n+1]!==r&&(t.opt_len+=(r-l[2*n+1])*l[2*n],l[2*n+1]=r),s--)}}(t,e),V(r,h,t.bl_count)}function G(t,e,i){var s,n,r=-1,o=e[1],a=0,l=7,h=4;for(0===o&&(l=138,h=3),e[2*(i+1)+1]=65535,s=0;s<=i;s++)n=o,o=e[2*(s+1)+1],++a<l&&n===o||(a<h?t.bl_tree[2*n]+=a:0!==n?(n!==r&&t.bl_tree[2*n]++,t.bl_tree[2*y]++):a<=10?t.bl_tree[2*w]++:t.bl_tree[2*v]++,r=n,h=(a=0)===o?(l=138,3):n===o?(l=6,3):(l=7,4))}function X(t,e,i){var s,n,r=-1,o=e[1],a=0,l=7,h=4;for(0===o&&(l=138,h=3),s=0;s<=i;s++)if(n=o,o=e[2*(s+1)+1],!(++a<l&&n===o)){if(a<h)for(;R(t,n,t.bl_tree),0!=--a;);else 0!==n?(n!==r&&(R(t,n,t.bl_tree),a--),R(t,y,t.bl_tree),L(t,a-3,2)):a<=10?(R(t,w,t.bl_tree),L(t,a-3,3)):(R(t,v,t.bl_tree),L(t,a-11,7));r=n,h=(a=0)===o?(l=138,3):n===o?(l=6,3):(l=7,4)}}o(k);var q=!1;function Q(t,e,i,n){var r,o,l;L(t,(a<<1)+(n?1:0),3),o=e,l=i,H(r=t),U(r,l),U(r,~l),s.arraySet(r.pending_buf,r.window,o,l,r.pending),r.pending+=l}i._tr_init=function(t){q||(function(){var t,e,i,s,n,r=new Array(f+1);for(s=i=0;s<l-1;s++)for(P[s]=i,t=0;t<1<<b[s];t++)O[i++]=s;for(O[i-1]=s,s=n=0;s<16;s++)for(k[s]=n,t=0;t<1<<x[s];t++)A[n++]=s;for(n>>=7;s<d;s++)for(k[s]=n<<7,t=0;t<1<<x[s]-7;t++)A[256+n++]=s;for(e=0;e<=f;e++)r[e]=0;for(t=0;t<=143;)E[2*t+1]=8,t++,r[8]++;for(;t<=255;)E[2*t+1]=9,t++,r[9]++;for(;t<=279;)E[2*t+1]=7,t++,r[7]++;for(;t<=287;)E[2*t+1]=8,t++,r[8]++;for(V(E,c+1,r),t=0;t<d;t++)S[2*t+1]=5,S[2*t]=F(t,5);I=new z(E,b,h+1,c,f),M=new z(S,x,0,d,f),D=new z(new Array(0),T,0,u,g)}(),q=!0),t.l_desc=new B(t.dyn_ltree,I),t.d_desc=new B(t.dyn_dtree,M),t.bl_desc=new B(t.bl_tree,D),t.bi_buf=0,t.bi_valid=0,j(t)},i._tr_stored_block=Q,i._tr_flush_block=function(t,e,i,s){var o,a,l=0;0<t.level?(2===t.strm.data_type&&(t.strm.data_type=function(t){var e,i=4093624447;for(e=0;e<=31;e++,i>>>=1)if(1&i&&0!==t.dyn_ltree[2*e])return n;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return r;for(e=32;e<h;e++)if(0!==t.dyn_ltree[2*e])return r;return n}(t)),Y(t,t.l_desc),Y(t,t.d_desc),l=function(t){var e;for(G(t,t.dyn_ltree,t.l_desc.max_code),G(t,t.dyn_dtree,t.d_desc.max_code),Y(t,t.bl_desc),e=u-1;3<=e&&0===t.bl_tree[2*C[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}(t),o=t.opt_len+3+7>>>3,(a=t.static_len+3+7>>>3)<=o&&(o=a)):o=a=i+5,i+4<=o&&-1!==e?Q(t,e,i,s):4===t.strategy||a===o?(L(t,2+(s?1:0),3),W(t,E,S)):(L(t,4+(s?1:0),3),function(t,e,i,s){var n;for(L(t,e-257,5),L(t,i-1,5),L(t,s-4,4),n=0;n<s;n++)L(t,t.bl_tree[2*C[n]+1],3);X(t,t.dyn_ltree,e-1),X(t,t.dyn_dtree,i-1)}(t,t.l_desc.max_code+1,t.d_desc.max_code+1,l+1),W(t,t.dyn_ltree,t.dyn_dtree)),j(t),s&&H(t)},i._tr_tally=function(t,e,i){return t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&i,t.last_lit++,0===e?t.dyn_ltree[2*i]++:(t.matches++,e--,t.dyn_ltree[2*(O[i]+h+1)]++,t.dyn_dtree[2*N(e)]++),t.last_lit===t.lit_bufsize-1},i._tr_align=function(t){var e;L(t,2,3),R(t,_,E),16===(e=t).bi_valid?(U(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):8<=e.bi_valid&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}},{"../utils/common":41}],53:[function(t,e,i){e.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(t,e,i){(function(t){!function(t,e){if(!t.setImmediate){var i,s,n,r,o=1,a={},l=!1,h=t.document,c=Object.getPrototypeOf&&Object.getPrototypeOf(t);c=c&&c.setTimeout?c:t,i="[object process]"==={}.toString.call(t.process)?function(t){process.nextTick(function(){u(t)})}:function(){if(t.postMessage&&!t.importScripts){var e=!0,i=t.onmessage;return t.onmessage=function(){e=!1},t.postMessage("","*"),t.onmessage=i,e}}()?(r="setImmediate$"+Math.random()+"$",t.addEventListener?t.addEventListener("message",p,!1):t.attachEvent("onmessage",p),function(e){t.postMessage(r+e,"*")}):t.MessageChannel?((n=new MessageChannel).port1.onmessage=function(t){u(t.data)},function(t){n.port2.postMessage(t)}):h&&"onreadystatechange"in h.createElement("script")?(s=h.documentElement,function(t){var e=h.createElement("script");e.onreadystatechange=function(){u(t),e.onreadystatechange=null,s.removeChild(e),e=null},s.appendChild(e)}):function(t){setTimeout(u,0,t)},c.setImmediate=function(t){"function"!=typeof t&&(t=new Function(""+t));for(var e=new Array(arguments.length-1),s=0;s<e.length;s++)e[s]=arguments[s+1];var n={callback:t,args:e};return a[o]=n,i(o),o++},c.clearImmediate=d}function d(t){delete a[t]}function u(t){if(l)setTimeout(u,0,t);else{var i=a[t];if(i){l=!0;try{!function(t){var i=t.callback,s=t.args;switch(s.length){case 0:i();break;case 1:i(s[0]);break;case 2:i(s[0],s[1]);break;case 3:i(s[0],s[1],s[2]);break;default:i.apply(e,s)}}(i)}finally{d(t),l=!1}}}}function p(e){e.source===t&&"string"==typeof e.data&&0===e.data.indexOf(r)&&u(+e.data.slice(r.length))}}("undefined"==typeof self?void 0===t?this:t:self)}).call(this,void 0!==b?b:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[10])(10));class ar{constructor(t,i){e(this,"date",new Date),e(this,"author"),e(this,"guid",v.create()),e(this,"viewpoint"),e(this,"modifiedAuthor"),e(this,"modifiedDate"),e(this,"topic"),e(this,"_components"),e(this,"_comment",""),this._components=t,this._comment=i;const s=this._components.get(pr);this.author=s.config.author}set comment(t){var e;const i=this._components.get(pr);this._comment=t,this.modifiedDate=new Date,this.modifiedAuthor=i.config.author,null==(e=this.topic)||e.comments.set(this.guid,this)}get comment(){return this._comment}toJSON(){var t,e;const i={guid:this.guid,date:this.date.toISOString(),author:this.author,comment:this.comment,topic_guid:null==(t=this.topic)?void 0:t.guid,viewpoint_guid:this.viewpoint,modified_date:null==(e=this.modifiedDate)?void 0:e.toISOString(),modified_author:this.modifiedAuthor};for(const[t,e]of Object.entries(i))void 0===e&&delete i[t];return i}}const lr=class t{constructor(s){e(this,"guid",v.create()),e(this,"title",t.default.title),e(this,"creationDate",new Date),e(this,"creationAuthor",""),e(this,"viewpoints",new i.DataSet),e(this,"relatedTopics",new i.DataSet),e(this,"comments",new i.DataMap),e(this,"documentReferences",new i.DataSet),e(this,"customData",{}),e(this,"description"),e(this,"serverAssignedId"),e(this,"dueDate"),e(this,"modifiedAuthor"),e(this,"modifiedDate"),e(this,"index"),e(this,"_type",t.default.type),e(this,"_status",t.default.status),e(this,"_priority",t.default.priority),e(this,"_stage",t.default.stage),e(this,"_assignedTo",t.default.assignedTo),e(this,"_labels",t.default.labels??new Set),e(this,"_components"),this._components=s;const n=s.get(pr);this.creationAuthor=n.config.author,this.relatedTopics.guard=t=>t!==this.guid}set type(t){const e=this._components.get(pr),{strict:i,types:s}=e.config;(!i||s.has(t))&&(this._type=t)}get type(){return this._type}set status(t){const e=this._components.get(pr),{strict:i,statuses:s}=e.config;(!i||s.has(t))&&(this._status=t)}get status(){return this._status}set priority(t){const e=this._components.get(pr);if(t){const{strict:i,priorities:s}=e.config;if(!(!i||s.has(t)))return;this._priority=t}else this._priority=t}get priority(){return this._priority}set stage(t){const e=this._components.get(pr);if(t){const{strict:i,stages:s}=e.config;if(!(!i||s.has(t)))return;this._stage=t}else this._stage=t}get stage(){return this._stage}set assignedTo(t){const e=this._components.get(pr);if(t){const{strict:i,users:s}=e.config;if(!(!i||s.has(t)))return;this._assignedTo=t}else this._assignedTo=t}get assignedTo(){return this._assignedTo}set labels(t){const e=this._components.get(pr),{strict:i,labels:s}=e.config;if(i){const e=new Set;for(const n of t){(!i||s.has(n))&&e.add(n)}this._labels=e}else this._labels=t}get labels(){return this._labels}get _managerVersion(){return this._components.get(pr).config.version}set(t){const e=t,i=this;for(const s in t){if("guid"===s)continue;const t=e[s];s in this&&(i[s]=t)}return this._components.get(pr).list.set(this.guid,this),this}createComment(t,e){const i=new ar(this._components,t);return i.viewpoint=e,i.topic=this,this.comments.set(i.guid,i),i}createLabelTags(){const t=[...this.labels];if(this._components.get(pr).config.exportCustomDataAsLabels)for(const e in this.customData){const i=this.customData[e];"string"==typeof i&&t.push(i)}return t}createCommentTags(){return[...this.comments.values()].map(t=>{var e;return{$Guid:t.guid,Date:t.date.toISOString(),Author:t.author,Comment:t.comment,ModifiedAuthor:t.modifiedAuthor,ModifiedDate:null==(e=t.modifiedDate)?void 0:e.toISOString(),Viewpoint:t.viewpoint?{$Guid:t.viewpoint}:void 0}})}createViewpointTags(){const t=this._components.get(to);return[...this.viewpoints].map(e=>t.list.get(e)).filter(t=>t).map(e=>{const i={$Guid:e.guid,Viewpoint:`${e.title??e.guid}.bcfv`};if(t.snapshots.get(e.snapshot)){const s=t.getSnapshotExtension(e.snapshot);i.Snapshot=`${e.snapshot}.${s}`}return i})}createRelatedTopicTags(){return[...this.relatedTopics].map(t=>({$Guid:t}))}createDocumentReferencesTag(t=this._managerVersion){const e=[];if("3"!==t&&"2.1"!==t)return e;const i=this._components.get(pr);for(const s of this.documentReferences){const n=i.documents.get(s);if(!n)continue;let r={$Guid:v.create(),Description:n.description};"2.1"===t&&(r={...r,$isExternal:"external"===n.type||void 0,ReferencedDocument:"external"===n.type?n.url:`../${n.fileName}`}),"3"===t&&(r={...r,DocumentGuid:"internal"===n.type?s:void 0,Url:"external"===n.type?n.url:void 0}),Object.keys(r).length>0&&e.push(r)}return e}toJSON(){var t,e;const i={guid:this.guid,server_assigned_id:this.serverAssignedId,topic_type:this.type,topic_status:this.status,title:this.title,priority:this.priority,index:this.index,labels:[...this.labels],creation_date:this.creationDate.toISOString(),creation_author:this.creationAuthor,modified_date:null==(t=this.modifiedDate)?void 0:t.toISOString(),modified_author:this.modifiedAuthor,assigned_to:this.assignedTo,stage:this.stage,description:this.description,due_date:null==(e=this.dueDate)?void 0:e.toISOString(),comments:[...this.comments].map(([t,e])=>e.toJSON()),relatedTopics:[...this.relatedTopics].map(t=>({related_topic_guid:t}))},s=this._components.get(to);for(const t of this.viewpoints){const e=s.list.get(t);e&&(i.viewpoints||(i.viewpoints=[]),i.viewpoints.push(e.toJSON()))}const n=this._components.get(pr);for(const t of this.documentReferences){const e=n.documents.get(t);e&&(i.document_references||(i.document_references=[]),"external"===e.type?i.document_references.push({guid:v.create(),description:e.description,url:e.url}):i.document_references.push({guid:v.create(),description:e.description,document_guid:t}))}for(const[t,e]of Object.entries(i))(void 0===e||Array.isArray(e)&&0===e.length)&&delete i[t];return i}serialize(){var t,e;const i=this._managerVersion,s={$Guid:this.guid,$TopicType:this.type,$TopicStatus:this.status,$ServerAssignedId:this.serverAssignedId,Title:this.title,CreationAuthor:this.creationAuthor,CreationDate:this.creationDate.toISOString(),Priority:this.priority,Index:"2.1"===i?this.index:void 0,ModifiedDate:null==(t=this.modifiedDate)?void 0:t.toISOString(),ModifiedAuthor:this.modifiedAuthor,DueDate:null==(e=this.dueDate)?void 0:e.toISOString(),AssignedTo:this.assignedTo,Description:this.description,Stage:this.stage,DocumentReferences:"3"===i?{DocumentReference:this.createDocumentReferencesTag(i)}:void 0,RelatedTopics:"3"===i?{RelatedTopic:this.createRelatedTopicTags()}:void 0,RelatedTopic:"2.1"===i?this.createRelatedTopicTags():void 0,Labels:"3"===i?{Label:this.createLabelTags()}:void 0,Viewpoints:"3"===i?{ViewPoint:this.createViewpointTags()}:void 0,Comments:"3"===i?{Comment:this.createCommentTags()}:void 0};"2.1"===i&&(s.Labels=this.createLabelTags(),s.DocumentReference=this.createDocumentReferencesTag(i));const n={Markup:{Topic:s}};return"2.1"===i&&(n.Markup.Viewpoints=this.createViewpointTags(),n.Markup.Comment=this.createCommentTags()),`<?xml version="1.0" encoding="UTF-8"?>\n ${Vt.builder.build(n)}`}};e(lr,"default",{title:"BCF Topic",type:"Issue",status:"Active"});let hr=lr;const cr=(t,e)=>{if(""===e.trim())return;const i=pr.xmlParser.parse(e).Extensions;if(!i)return;const{Priorities:s,TopicStatuses:n,TopicTypes:r,Users:o}=i;if(s&&s.Priority){const e=Array.isArray(s.Priority)?s.Priority:[s.Priority];for(const i of e)t.config.priorities.add(i)}if(n&&n.TopicStatus){const e=Array.isArray(n.TopicStatus)?n.TopicStatus:[n.TopicStatus];for(const i of e)t.config.statuses.add(i)}if(r&&r.TopicType){const e=Array.isArray(r.TopicType)?r.TopicType:[r.TopicType];for(const i of e)t.config.types.add(i)}if(o&&o.User){const e=Array.isArray(o.User)?o.User:[o.User];for(const i of e)t.config.users.add(i)}};class dr extends $t{constructor(){super(...arguments),e(this,"_config",{version:{type:"Select",options:new Set(["2.1","3"]),multiple:!1,value:""},author:{type:"Text",value:""},types:{type:"TextSet",value:new Set},statuses:{type:"TextSet",value:new Set},priorities:{type:"TextSet",value:new Set},labels:{type:"TextSet",value:new Set},stages:{type:"TextSet",value:new Set},users:{type:"TextSet",value:new Set},includeSelectionTag:{type:"Boolean",value:!1},updateExtensionsOnImport:{type:"Boolean",value:!1},strict:{type:"Boolean",value:!1},includeAllExtensionsOnExport:{type:"Boolean",value:!1},fallbackVersionOnImport:{type:"Select",multiple:!1,options:new Set(["2.1","3"]),value:""},ignoreIncompleteTopicsOnImport:{type:"Boolean",value:!1},exportCustomDataAsLabels:{type:"Boolean",value:!1}})}get version(){return this._config.version.value}set version(t){this._config.version.value=t}get author(){return this._config.author.value}set author(t){this._config.author.value=t}get types(){return this._config.types.value}set types(t){this._config.types.value=t}get statuses(){return this._config.statuses.value}set statuses(t){this._config.statuses.value=t}get priorities(){return this._config.priorities.value}set priorities(t){this._config.priorities.value=t}get labels(){return this._config.labels.value}set labels(t){this._config.labels.value=t}get stages(){return this._config.stages.value}set stages(t){this._config.stages.value=t}get users(){return this._config.users.value}set users(t){this._config.users.value=t}get includeSelectionTag(){return this._config.includeSelectionTag.value}set includeSelectionTag(t){this._config.includeSelectionTag.value=t}get updateExtensionsOnImport(){return this._config.updateExtensionsOnImport.value}set updateExtensionsOnImport(t){this._config.updateExtensionsOnImport.value=t}get strict(){return this._config.strict.value}set strict(t){this._config.strict.value=t}get includeAllExtensionsOnExport(){return this._config.includeAllExtensionsOnExport.value}set includeAllExtensionsOnExport(t){this._config.includeAllExtensionsOnExport.value=t}get fallbackVersionOnImport(){return this._config.fallbackVersionOnImport.value}set fallbackVersionOnImport(t){this._config.fallbackVersionOnImport.value=t}get ignoreIncompleteTopicsOnImport(){return this._config.ignoreIncompleteTopicsOnImport.value}set ignoreIncompleteTopicsOnImport(t){this._config.ignoreIncompleteTopicsOnImport.value=t}get exportCustomDataAsLabels(){return this._config.exportCustomDataAsLabels.value}set exportCustomDataAsLabels(t){this._config.exportCustomDataAsLabels.value=t}}const ur=class t extends d{constructor(){super(...arguments),e(this,"enabled",!1),e(this,"_defaultConfig",{author:"jhon.doe@example.com",version:"2.1",types:new Set(["Clash","Failure","Fault","Inquiry","Issue","Remark","Request"]),statuses:new Set(["Active","In Progress","Done","In Review","Closed"]),priorities:new Set(["On hold","Minor","Normal","Major","Critical"]),labels:new Set,stages:new Set,users:new Set,includeSelectionTag:!1,updateExtensionsOnImport:!0,strict:!1,includeAllExtensionsOnExport:!0,fallbackVersionOnImport:"2.1",ignoreIncompleteTopicsOnImport:!1,exportCustomDataAsLabels:!1}),e(this,"config",new dr(this,this.components,"BCF Topics",t.uuid)),e(this,"list",new i.DataMap),e(this,"documents",new i.DataMap),e(this,"onSetup",new h),e(this,"isSetup",!1),e(this,"onBCFImported",new h),e(this,"onDisposed",new h)}setup(t){if(this.isSetup)return;const e={...this._defaultConfig,...t};this.config.version=e.version,this.config.author=e.author,this.config.types=e.types,this.config.statuses=e.statuses,this.config.priorities=e.priorities,this.config.labels=e.labels,this.config.stages=e.stages,this.config.users=e.users,this.config.includeSelectionTag=e.includeSelectionTag,this.config.updateExtensionsOnImport=e.updateExtensionsOnImport,this.config.strict=e.strict,this.config.includeAllExtensionsOnExport=e.includeAllExtensionsOnExport,this.config.fallbackVersionOnImport=e.fallbackVersionOnImport||"",this.config.ignoreIncompleteTopicsOnImport=e.ignoreIncompleteTopicsOnImport,this.isSetup=!0,this.enabled=!0,this.onSetup.trigger()}create(t){const e=new hr(this.components);return t?(e.guid=t.guid??e.guid,e.set(t)):this.list.set(e.guid,e),e}dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}get usedTypes(){const t=[...this.list].map(([t,e])=>e.type);return new Set(t)}get usedStatuses(){const t=[...this.list].map(([t,e])=>e.status);return new Set(t)}get usedPriorities(){const t=[...this.list].map(([t,e])=>e.priority).filter(t=>t);return new Set(t)}get usedStages(){const t=[...this.list].map(([t,e])=>e.stage).filter(t=>t);return new Set(t)}get usedUsers(){const t=[];for(const[e,i]of this.list){t.push(i.creationAuthor),i.assignedTo&&t.push(i.assignedTo),i.modifiedAuthor&&t.push(i.modifiedAuthor);for(const[e,s]of i.comments)t.push(s.author),s.modifiedAuthor&&t.push(s.modifiedAuthor)}return new Set(t)}get usedLabels(){const t=[];for(const[e,i]of this.list)t.push(...i.labels);return new Set(t)}updateExtensions(){for(const[t,e]of this.list){for(const t of e.labels)this.config.labels.add(t);this.config.types.add(e.type),e.priority&&this.config.priorities.add(e.priority),e.stage&&this.config.stages.add(e.stage),this.config.statuses.add(e.status),this.config.users.add(e.creationAuthor),e.assignedTo&&this.config.users.add(e.assignedTo),e.modifiedAuthor&&this.config.users.add(e.modifiedAuthor);for(const[t,i]of e.comments)this.config.users.add(i.author),i.modifiedAuthor&&this.config.users.add(i.modifiedAuthor)}}updateViewpointReferences(){const t=this.components.get(to);for(const[e,i]of this.list)for(const e of i.viewpoints){t.list.has(e)||i.viewpoints.delete(e)}}async export(t=this.list.values()){const e=new or;e.file("bcf.version",`<?xml version="1.0" encoding="UTF-8"?>\n <Version VersionId="${this.config.version}" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/buildingSMART/BCF-XML/release_3_0/Schemas/version.xsd"\n xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n </Version>`);for(const[t,i]of this.documents.entries())"external"!==i.type&&e.file("2.1"===this.config.version?i.fileName:`documents/${t}`,i.data);if("3"===this.config.version){const t=[];for(const[e,i]of this.documents.entries()){const{type:s,description:n}=i;"external"!==s&&t.push(`<Document Guid="${e}">\n <Filename>${i.fileName}</Filename>\n ${n?`<Description>${n}</Description>`:""}\n </Document>`)}t.length>0&&e.file("documents.xml",`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n <DocumentInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="documents.xsd">\n <Documents>\n ${t.join("\n")}\n </Documents>\n </DocumentInfo>`)}e.file("bcf.extensions",this.serializeExtensions());const i=this.components.get(to);for(const s of t){const t=e.folder(s.guid);t.file("markup.bcf",s.serialize());for(const e of s.viewpoints){const s=i.list.get(e);if(!s)continue;const n=s.title??s.guid;t.file(`${n}.bcfv`,await s.serialize());const r=i.snapshots.get(s.snapshot);if(!r)continue;const o=r?s.snapshot:s.guid,a=i.getSnapshotExtension(s.snapshot);t.file(`${o}.${a}`,r,{binary:!0})}}return await e.generateAsync({type:"blob"})}serializeExtensions(){const t=[...this.config.types].map(t=>`<TopicType>${t}</TopicType>`).join("\n"),e=[...this.config.statuses].map(t=>`<TopicStatus>${t}</TopicStatus>`).join("\n"),i=[...this.config.priorities].map(t=>`<Priority>${t}</Priority>`).join("\n"),s=[...this.config.labels].map(t=>`<TopicLabel>${t}</TopicLabel>`).join("\n"),n=[...this.config.stages].map(t=>`<Stage>${t}</Stage>`).join("\n"),r=[...this.config.users].map(t=>`<User>${t}</User>`).join("\n");return`\n <?xml version="1.0" encoding="UTF-8"?>\n <Extensions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="your-schema-location.xsd">\n ${0!==t.length?`<TopicTypes>\n${t}\n</TopicTypes>`:""}\n ${0!==e.length?`<TopicStatuses>\n${e}\n</TopicStatuses>`:""}\n ${0!==i.length?`<Priorities>\n${i}\n</Priorities>`:""}\n ${0!==s.length?`<TopicLabels>\n${s}\n</TopicLabels>`:""}\n ${0!==n.length?`<Stages>\n${n}\n</Stages>`:""}\n ${0!==r.length?`<Users>\n${r}\n</Users>`:""}\n </Extensions>\n `}processMarkupComment(t){const{Guid:e,Date:i,Author:s,Comment:n,Viewpoint:r}=t;if(!(e&&i&&s&&(ar||r)))return null;const o=new ar(this.components,n??"");return o.guid=e,o.date=new Date(i),o.author=s,o.viewpoint=null==r?void 0:r.Guid,o.modifiedAuthor=t.ModifiedAuthor,o.modifiedDate=t.ModifiedDate?new Date(t.ModifiedDate):void 0,o}getMarkupComments(t,e){var i;let s;if("2.1"===e&&(s=t.Comment),"3"===e&&(s=null==(i=t.Topic.Comments)?void 0:i.Comment),!s)return[];s=Array.isArray(s)?s:[s];const n=s.map(t=>this.processMarkupComment(t)).filter(t=>t);return Array.isArray(n)?n:[n]}getMarkupLabels(t,e){var i;let s;if("2.1"===e&&(s=t.Topic.Labels),"3"===e&&(s=null==(i=t.Topic.Labels)?void 0:i.Label),!s)return[];return Array.isArray(s)?s:[s]}getMarkupViewpoints(t,e){var i;let s;return"2.1"===e&&(s=t.Viewpoints),"3"===e&&(s=null==(i=t.Topic.Viewpoints)?void 0:i.ViewPoint),s?(s=Array.isArray(s)?s:[s],s):[]}getMarkupRelatedTopics(t,e){var i;let s;if("2.1"===e&&(s=t.Topic.RelatedTopic),"3"===e&&(s=null==(i=t.Topic.RelatedTopics)?void 0:i.RelatedTopic),!s)return[];return(Array.isArray(s)?s:[s]).map(t=>t.Guid)}getMarkupDocumentReferences(t,e){var i;let s;if("2.1"===e&&(s=t.Topic.DocumentReference),"3"===e&&(s=null==(i=t.Topic.DocumentReferences)?void 0:i.DocumentReference),!s)return[];return Array.isArray(s)?s:[s]}async load(e){var i,s,n;const{fallbackVersionOnImport:r,ignoreIncompleteTopicsOnImport:o,updateExtensionsOnImport:l}=this.config,h=new or;await h.loadAsync(e);const c=Object.values(h.files);let d=r;const u=c.find(t=>t.name.endsWith(".version"));if(u){const e=await u.async("string"),i=t.xmlParser.parse(e).Version.VersionId;d=String(i)}if(!d||"2.1"!==d&&"3"!==d)throw new Error(`BCFTopics: ${d} is not supported.`);const p=c.find(t=>t.name.endsWith(".extensions"));if(l&&p){const t=await p.async("string");cr(this,t)}const f=[],m=this.components.get(to),g=c.filter(t=>t.name.endsWith(".bcfv"));for(const e of g){const s=await e.async("string"),n=t.xmlParser.parse(s).VisualizationInfo;if(!n){console.warn("Missing VisualizationInfo in Viewpoint");continue}const r={},{Guid:o,ClippingPlanes:l,Components:h,OrthogonalCamera:c,PerspectiveCamera:u}=n;if(o&&(r.guid=o),h){const t={selection:[],coloring:[],visibility:{default_visibility:!1,exceptions:[],view_setup_hints:{spaces_visible:!1,space_boundaries_visible:!1,openings_visible:!1}}};r.components=t;const{Selection:e,Visibility:s}=h;if(e&&e.Component){const i=Array.isArray(e.Component)?e.Component:[e.Component];t.selection=i.map(t=>t.IfcGuid?{ifc_guid:t.IfcGuid}:null).filter(t=>null!==t)}if(s&&"DefaultVisibility"in s&&(t.visibility.default_visibility=s.DefaultVisibility),s&&s.Exceptions&&"Component"in s.Exceptions){const{Component:e}=s.Exceptions,i=Array.isArray(e)?e:[e];t.visibility.exceptions=i.map(t=>t.IfcGuid?{ifc_guid:t.IfcGuid}:null).filter(t=>null!==t)}let n;"2.1"===d&&(n=h.ViewSetupHints),"3"===d&&(n=null==(i=h.Visibility)?void 0:i.ViewSetupHints),n&&("OpeningsVisible"in n&&(t.visibility.view_setup_hints.openings_visible=n.OpeningsVisible),"SpacesVisible"in n&&(t.visibility.view_setup_hints.spaces_visible=n.SpacesVisible),"SpaceBoundariesVisible"in n&&(t.visibility.view_setup_hints.space_boundaries_visible=n.SpaceBoundariesVisible));const{Coloring:o}=h;if(o&&o.Color){const e=Array.isArray(o.Color)?o.Color:[o.Color];for(const i of e){const{Color:e,Component:s}=i;if(6!==e.length&&8!==e.length)continue;const n=6===e.length?e:e.slice(2),r=(Array.isArray(s)?s:[s]).map(t=>t.IfcGuid?{ifc_guid:t.IfcGuid}:null).filter(t=>null!==t);t.coloring.push({color:n,components:r})}}}if(c||u){const t=n.PerspectiveCamera??n.OrthogonalCamera,{CameraViewPoint:e,CameraDirection:i}=t,s=new a.Vector3(Number(e.X),Number(e.Z),Number(-e.Y)),o=new a.Vector3(Number(i.X),Number(i.Z),Number(-i.Y)),l={camera_view_point:{x:s.x,y:s.y,z:s.z},camera_direction:{x:o.x,y:o.y,z:o.z},aspect_ratio:"AspectRatio"in t?t.AspectRatio:1,camera_up_vector:{x:0,y:0,z:0}};"ViewToWorldScale"in t&&(r.orthogonal_camera={...l,view_to_world_scale:t.ViewToWorldScale}),"FieldOfView"in t&&(r.perspective_camera={...l,field_of_view:t.FieldOfView})}if(l){const t=(Array.isArray(l.ClippingPlane)?l.ClippingPlane:[l.ClippingPlane]).map(({Location:t,Direction:e})=>({location:{x:t.x,y:t.y,z:t.z},direction:{x:e.x,y:e.y,z:e.z}}));r.clipping_planes=t}const p=new Qr(this.components,r);f.push(p)}const _={},y=[],w=c.filter(t=>t.name.endsWith(".bcf"));for(const e of w){const i=await e.async("string"),r=t.xmlParser.parse(i).Markup,a=r.Topic,{Guid:l,TopicType:h,TopicStatus:u,Title:p,CreationDate:f,CreationAuthor:g}=a;if(o&&!(l&&h&&u&&p&&f&&g))continue;const w=new hr(this.components);w.guid=l??w.guid;const v=this.getMarkupRelatedTopics(r,d);_[w.guid]=new Set(v),w.type=h??w.type,w.status=u??w.status,w.title=p??w.title,w.creationDate=f?new Date(f):w.creationDate,w.creationAuthor=g??w.creationAuthor,w.serverAssignedId=a.ServerAssignedId,w.priority=a.Priority,w.index=a.Index,w.modifiedDate=a.ModifiedDate?new Date(a.ModifiedDate):void 0,w.modifiedAuthor=a.ModifiedAuthor,w.dueDate=a.DueDate?new Date(a.DueDate):void 0,w.assignedTo=a.AssignedTo,w.description=a.Description,w.stage=a.Stage;const b=this.getMarkupLabels(r,d);for(const t of b)w.labels.add(t);const x=this.getMarkupComments(r,d);for(const t of x)w.comments.set(t.guid,t);const T=this.getMarkupViewpoints(r,d);for(const t of T){if(!t||!t.Guid)continue;const e=m.list.get(t.Guid);if(!e)continue;w.viewpoints.add(e.guid);const i=`${w.guid}/${t.Snapshot}`,s=c.find(({name:t})=>t===i);if(s){const t=await s.async("arraybuffer"),i=new Uint8Array(t);m.snapshots.set(e.guid,i),e.snapshot=e.guid??null}}const C=this.getMarkupDocumentReferences(r,d),E=c.find(t=>"documents.xml"===t.name);let S=[];const A=await(null==E?void 0:E.async("string"));if(A){const t=null==(n=null==(s=Vt.parser.parse(A).DocumentInfo)?void 0:s.Documents)?void 0:n.Document;S=Array.isArray(t)?t:[t]}for(const t of C){const{Description:e,DocumentGuid:i,Url:s,isExternal:n,ReferencedDocument:r}=t;if(i&&S.length>0){const t=S.find(({Guid:t})=>t===i),e=c.find(t=>t.name.endsWith(i)),s=await(null==e?void 0:e.async("uint8array"));if(!t||!s)continue;const{Description:n,Filename:r}=t;this.documents.set(i,{type:"internal",fileName:r,description:n,data:s}),w.documentReferences.add(i)}if(s){const t=this.documents.add({type:"external",url:s,description:e});w.documentReferences.add(t)}if(r){let t=null;if(n)t=this.documents.add({type:"external",url:r,description:e});else{const i=r.split("/"),s=i[i.length-1],n=c.find(t=>t.name.endsWith(s)),o=await(null==n?void 0:n.async("uint8array"));if(!o)continue;t=this.documents.add({type:"internal",fileName:s,data:o,description:e})}w.documentReferences.add(t)}}this.list.set(w.guid,w),y.push(w)}for(const t in _){const e=this.list.get(t);if(!e)continue;const i=_[t];for(const t of i)e.relatedTopics.add(t)}return this.onBCFImported.trigger(y),{viewpoints:f,topics:y}}};e(ur,"uuid","de977976-e4f6-4e4f-a01a-204727839802"),e(ur,"xmlParser",new Ft.XMLParser({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0}));let pr=ur;const fr=new s.Raycaster,mr=new s.Vector3,gr=new s.Vector3,_r=new s.Quaternion,yr={X:new s.Vector3(1,0,0),Y:new s.Vector3(0,1,0),Z:new s.Vector3(0,0,1)},wr={type:"change"},vr={type:"mouseDown",mode:null},br={type:"mouseUp",mode:null},xr={type:"objectChange"};class Tr extends s.Controls{constructor(t,e=null){super(void 0,e);const i=new Zr(this);this._root=i;const n=new $r;this._gizmo=n,i.add(n);const r=new Wr;this._plane=r,i.add(r);const o=this;function a(t,e){let i=e;Object.defineProperty(o,t,{get:function(){return void 0!==i?i:e},set:function(e){i!==e&&(i=e,r[t]=e,n[t]=e,o.dispatchEvent({type:t+"-changed",value:e}),o.dispatchEvent(wr))}}),o[t]=e,r[t]=e,n[t]=e}a("camera",t),a("object",void 0),a("enabled",!0),a("axis",null),a("mode","translate"),a("translationSnap",null),a("rotationSnap",null),a("scaleSnap",null),a("space","world"),a("size",1),a("dragging",!1),a("showX",!0),a("showY",!0),a("showZ",!0),a("minX",-1/0),a("maxX",1/0),a("minY",-1/0),a("maxY",1/0),a("minZ",-1/0),a("maxZ",1/0);const l=new s.Vector3,h=new s.Vector3,c=new s.Quaternion,d=new s.Quaternion,u=new s.Vector3,p=new s.Quaternion,f=new s.Vector3,m=new s.Vector3,g=new s.Vector3,_=new s.Vector3;a("worldPosition",l),a("worldPositionStart",h),a("worldQuaternion",c),a("worldQuaternionStart",d),a("cameraPosition",u),a("cameraQuaternion",p),a("pointStart",f),a("pointEnd",m),a("rotationAxis",g),a("rotationAngle",0),a("eye",_),this._offset=new s.Vector3,this._startNorm=new s.Vector3,this._endNorm=new s.Vector3,this._cameraScale=new s.Vector3,this._parentPosition=new s.Vector3,this._parentQuaternion=new s.Quaternion,this._parentQuaternionInv=new s.Quaternion,this._parentScale=new s.Vector3,this._worldScaleStart=new s.Vector3,this._worldQuaternionInv=new s.Quaternion,this._worldScale=new s.Vector3,this._positionStart=new s.Vector3,this._quaternionStart=new s.Quaternion,this._scaleStart=new s.Vector3,this._getPointer=Cr.bind(this),this._onPointerDown=Sr.bind(this),this._onPointerHover=Er.bind(this),this._onPointerMove=Ar.bind(this),this._onPointerUp=Or.bind(this),null!==e&&this.connect(e)}connect(t){super.connect(t),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointermove",this._onPointerHover),this.domElement.addEventListener("pointerup",this._onPointerUp),this.domElement.style.touchAction="none"}disconnect(){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.domElement.style.touchAction="auto"}getHelper(){return this._root}pointerHover(t){if(void 0===this.object||!0===this.dragging)return;null!==t&&fr.setFromCamera(t,this.camera);const e=Pr(this._gizmo.picker[this.mode],fr);this.axis=e?e.object.name:null}pointerDown(t){if(void 0!==this.object&&!0!==this.dragging&&(null==t||0===t.button)&&null!==this.axis){null!==t&&fr.setFromCamera(t,this.camera);const e=Pr(this._plane,fr,!0);e&&(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(e.point).sub(this.worldPositionStart)),this.dragging=!0,vr.mode=this.mode,this.dispatchEvent(vr)}}pointerMove(t){const e=this.axis,i=this.mode,s=this.object;let n=this.space;if("scale"===i?n="local":"E"!==e&&"XYZE"!==e&&"XYZ"!==e||(n="world"),void 0===s||null===e||!1===this.dragging||null!==t&&-1!==t.button)return;null!==t&&fr.setFromCamera(t,this.camera);const r=Pr(this._plane,fr,!0);if(r){if(this.pointEnd.copy(r.point).sub(this.worldPositionStart),"translate"===i)this._offset.copy(this.pointEnd).sub(this.pointStart),"local"===n&&"XYZ"!==e&&this._offset.applyQuaternion(this._worldQuaternionInv),-1===e.indexOf("X")&&(this._offset.x=0),-1===e.indexOf("Y")&&(this._offset.y=0),-1===e.indexOf("Z")&&(this._offset.z=0),"local"===n&&"XYZ"!==e?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),s.position.copy(this._offset).add(this._positionStart),this.translationSnap&&("local"===n&&(s.position.applyQuaternion(_r.copy(this._quaternionStart).invert()),-1!==e.search("X")&&(s.position.x=Math.round(s.position.x/this.translationSnap)*this.translationSnap),-1!==e.search("Y")&&(s.position.y=Math.round(s.position.y/this.translationSnap)*this.translationSnap),-1!==e.search("Z")&&(s.position.z=Math.round(s.position.z/this.translationSnap)*this.translationSnap),s.position.applyQuaternion(this._quaternionStart)),"world"===n&&(s.parent&&s.position.add(mr.setFromMatrixPosition(s.parent.matrixWorld)),-1!==e.search("X")&&(s.position.x=Math.round(s.position.x/this.translationSnap)*this.translationSnap),-1!==e.search("Y")&&(s.position.y=Math.round(s.position.y/this.translationSnap)*this.translationSnap),-1!==e.search("Z")&&(s.position.z=Math.round(s.position.z/this.translationSnap)*this.translationSnap),s.parent&&s.position.sub(mr.setFromMatrixPosition(s.parent.matrixWorld)))),s.position.x=Math.max(this.minX,Math.min(this.maxX,s.position.x)),s.position.y=Math.max(this.minY,Math.min(this.maxY,s.position.y)),s.position.z=Math.max(this.minZ,Math.min(this.maxZ,s.position.z));else if("scale"===i){if(-1!==e.search("XYZ")){let t=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(t*=-1),gr.set(t,t,t)}else mr.copy(this.pointStart),gr.copy(this.pointEnd),mr.applyQuaternion(this._worldQuaternionInv),gr.applyQuaternion(this._worldQuaternionInv),gr.divide(mr),-1===e.search("X")&&(gr.x=1),-1===e.search("Y")&&(gr.y=1),-1===e.search("Z")&&(gr.z=1);s.scale.copy(this._scaleStart).multiply(gr),this.scaleSnap&&(-1!==e.search("X")&&(s.scale.x=Math.round(s.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),-1!==e.search("Y")&&(s.scale.y=Math.round(s.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),-1!==e.search("Z")&&(s.scale.z=Math.round(s.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if("rotate"===i){this._offset.copy(this.pointEnd).sub(this.pointStart);const t=20/this.worldPosition.distanceTo(mr.setFromMatrixPosition(this.camera.matrixWorld));let i=!1;"XYZE"===e?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(mr.copy(this.rotationAxis).cross(this.eye))*t):"X"!==e&&"Y"!==e&&"Z"!==e||(this.rotationAxis.copy(yr[e]),mr.copy(yr[e]),"local"===n&&mr.applyQuaternion(this.worldQuaternion),mr.cross(this.eye),0===mr.length()?i=!0:this.rotationAngle=this._offset.dot(mr.normalize())*t),("E"===e||i)&&(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),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),"local"===n&&"E"!==e&&"XYZE"!==e?(s.quaternion.copy(this._quaternionStart),s.quaternion.multiply(_r.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),s.quaternion.copy(_r.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),s.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(wr),this.dispatchEvent(xr)}}pointerUp(t){null!==t&&0!==t.button||(this.dragging&&null!==this.axis&&(br.mode=this.mode,this.dispatchEvent(br)),this.dragging=!1,this.axis=null)}dispose(){this.disconnect(),this._root.dispose()}attach(t){return this.object=t,this._root.visible=!0,this}detach(){return this.object=void 0,this.axis=null,this._root.visible=!1,this}reset(){this.enabled&&this.dragging&&(this.object.position.copy(this._positionStart),this.object.quaternion.copy(this._quaternionStart),this.object.scale.copy(this._scaleStart),this.dispatchEvent(wr),this.dispatchEvent(xr),this.pointStart.copy(this.pointEnd))}getRaycaster(){return fr}getMode(){return this.mode}setMode(t){this.mode=t}setTranslationSnap(t){this.translationSnap=t}setRotationSnap(t){this.rotationSnap=t}setScaleSnap(t){this.scaleSnap=t}setSize(t){this.size=t}setSpace(t){this.space=t}}function Cr(t){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:t.button};{const e=this.domElement.getBoundingClientRect();return{x:(t.clientX-e.left)/e.width*2-1,y:-(t.clientY-e.top)/e.height*2+1,button:t.button}}}function Er(t){if(this.enabled)switch(t.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(t))}}function Sr(t){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(t.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(t)),this.pointerDown(this._getPointer(t)))}function Ar(t){this.enabled&&this.pointerMove(this._getPointer(t))}function Or(t){this.enabled&&(this.domElement.releasePointerCapture(t.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(t)))}function Pr(t,e,i){const s=e.intersectObject(t,!0);for(let t=0;t<s.length;t++)if(s[t].object.visible||i)return s[t];return!1}const Ir=new s.Euler,Mr=new s.Vector3(0,1,0),Dr=new s.Vector3(0,0,0),kr=new s.Matrix4,zr=new s.Quaternion,Br=new s.Quaternion,Nr=new s.Vector3,Ur=new s.Matrix4,Lr=new s.Vector3(1,0,0),Rr=new s.Vector3(0,1,0),Fr=new s.Vector3(0,0,1),Vr=new s.Vector3,jr=new s.Vector3,Hr=new s.Vector3;class Zr extends s.Object3D{constructor(t){super(),this.isTransformControlsRoot=!0,this.controls=t,this.visible=!1}updateMatrixWorld(t){const e=this.controls;void 0!==e.object&&(e.object.updateMatrixWorld(),null===e.object.parent?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):e.object.parent.matrixWorld.decompose(e._parentPosition,e._parentQuaternion,e._parentScale),e.object.matrixWorld.decompose(e.worldPosition,e.worldQuaternion,e._worldScale),e._parentQuaternionInv.copy(e._parentQuaternion).invert(),e._worldQuaternionInv.copy(e.worldQuaternion).invert()),e.camera.updateMatrixWorld(),e.camera.matrixWorld.decompose(e.cameraPosition,e.cameraQuaternion,e._cameraScale),e.camera.isOrthographicCamera?e.camera.getWorldDirection(e.eye).negate():e.eye.copy(e.cameraPosition).sub(e.worldPosition).normalize(),super.updateMatrixWorld(t)}dispose(){this.traverse(function(t){t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose()})}}class $r extends s.Object3D{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const t=new s.MeshBasicMaterial({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),e=new s.LineBasicMaterial({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),i=t.clone();i.opacity=.15;const n=e.clone();n.opacity=.5;const r=t.clone();r.color.setHex(16711680);const o=t.clone();o.color.setHex(65280);const a=t.clone();a.color.setHex(255);const l=t.clone();l.color.setHex(16711680),l.opacity=.5;const h=t.clone();h.color.setHex(65280),h.opacity=.5;const c=t.clone();c.color.setHex(255),c.opacity=.5;const d=t.clone();d.opacity=.25;const u=t.clone();u.color.setHex(16776960),u.opacity=.25;t.clone().color.setHex(16776960);const p=t.clone();p.color.setHex(7895160);const f=new s.CylinderGeometry(0,.04,.1,12);f.translate(0,.05,0);const m=new s.BoxGeometry(.08,.08,.08);m.translate(0,.04,0);const g=new s.BufferGeometry;g.setAttribute("position",new s.Float32BufferAttribute([0,0,0,1,0,0],3));const _=new s.CylinderGeometry(.0075,.0075,.5,3);function y(t,e){const i=new s.TorusGeometry(t,.0075,3,64,e*Math.PI*2);return i.rotateY(Math.PI/2),i.rotateX(Math.PI/2),i}_.translate(0,.25,0);const w={X:[[new s.Mesh(f,r),[.5,0,0],[0,0,-Math.PI/2]],[new s.Mesh(f,r),[-.5,0,0],[0,0,Math.PI/2]],[new s.Mesh(_,r),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new s.Mesh(f,o),[0,.5,0]],[new s.Mesh(f,o),[0,-.5,0],[Math.PI,0,0]],[new s.Mesh(_,o)]],Z:[[new s.Mesh(f,a),[0,0,.5],[Math.PI/2,0,0]],[new s.Mesh(f,a),[0,0,-.5],[-Math.PI/2,0,0]],[new s.Mesh(_,a),null,[Math.PI/2,0,0]]],XYZ:[[new s.Mesh(new s.OctahedronGeometry(.1,0),d.clone()),[0,0,0]]],XY:[[new s.Mesh(new s.BoxGeometry(.15,.15,.01),c.clone()),[.15,.15,0]]],YZ:[[new s.Mesh(new s.BoxGeometry(.15,.15,.01),l.clone()),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new s.Mesh(new s.BoxGeometry(.15,.15,.01),h.clone()),[.15,0,.15],[-Math.PI/2,0,0]]]},v={X:[[new s.Mesh(new s.CylinderGeometry(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new s.Mesh(new s.CylinderGeometry(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new s.Mesh(new s.CylinderGeometry(.2,0,.6,4),i),[0,.3,0]],[new s.Mesh(new s.CylinderGeometry(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new s.Mesh(new s.CylinderGeometry(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new s.Mesh(new s.CylinderGeometry(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new s.Mesh(new s.OctahedronGeometry(.2,0),i)]],XY:[[new s.Mesh(new s.BoxGeometry(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new s.Mesh(new s.BoxGeometry(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new s.Mesh(new s.BoxGeometry(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]]},b={START:[[new s.Mesh(new s.OctahedronGeometry(.01,2),n),null,null,null,"helper"]],END:[[new s.Mesh(new s.OctahedronGeometry(.01,2),n),null,null,null,"helper"]],DELTA:[[new s.Line(function(){const t=new s.BufferGeometry;return t.setAttribute("position",new s.Float32BufferAttribute([0,0,0,1,1,1],3)),t}(),n),null,null,null,"helper"]],X:[[new s.Line(g,n.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new s.Line(g,n.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new s.Line(g,n.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},x={XYZE:[[new s.Mesh(y(.5,1),p),null,[0,Math.PI/2,0]]],X:[[new s.Mesh(y(.5,.5),r)]],Y:[[new s.Mesh(y(.5,.5),o),null,[0,0,-Math.PI/2]]],Z:[[new s.Mesh(y(.5,.5),a),null,[0,Math.PI/2,0]]],E:[[new s.Mesh(y(.75,1),u),null,[0,Math.PI/2,0]]]},T={AXIS:[[new s.Line(g,n.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},C={XYZE:[[new s.Mesh(new s.SphereGeometry(.25,10,8),i)]],X:[[new s.Mesh(new s.TorusGeometry(.5,.1,4,24),i),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new s.Mesh(new s.TorusGeometry(.5,.1,4,24),i),[0,0,0],[Math.PI/2,0,0]]],Z:[[new s.Mesh(new s.TorusGeometry(.5,.1,4,24),i),[0,0,0],[0,0,-Math.PI/2]]],E:[[new s.Mesh(new s.TorusGeometry(.75,.1,2,24),i)]]},E={X:[[new s.Mesh(m,r),[.5,0,0],[0,0,-Math.PI/2]],[new s.Mesh(_,r),[0,0,0],[0,0,-Math.PI/2]],[new s.Mesh(m,r),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new s.Mesh(m,o),[0,.5,0]],[new s.Mesh(_,o)],[new s.Mesh(m,o),[0,-.5,0],[0,0,Math.PI]]],Z:[[new s.Mesh(m,a),[0,0,.5],[Math.PI/2,0,0]],[new s.Mesh(_,a),[0,0,0],[Math.PI/2,0,0]],[new s.Mesh(m,a),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new s.Mesh(new s.BoxGeometry(.15,.15,.01),c),[.15,.15,0]]],YZ:[[new s.Mesh(new s.BoxGeometry(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new s.Mesh(new s.BoxGeometry(.15,.15,.01),h),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new s.Mesh(new s.BoxGeometry(.1,.1,.1),d.clone())]]},S={X:[[new s.Mesh(new s.CylinderGeometry(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new s.Mesh(new s.CylinderGeometry(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new s.Mesh(new s.CylinderGeometry(.2,0,.6,4),i),[0,.3,0]],[new s.Mesh(new s.CylinderGeometry(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new s.Mesh(new s.CylinderGeometry(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new s.Mesh(new s.CylinderGeometry(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new s.Mesh(new s.BoxGeometry(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new s.Mesh(new s.BoxGeometry(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new s.Mesh(new s.BoxGeometry(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new s.Mesh(new s.BoxGeometry(.2,.2,.2),i),[0,0,0]]]},A={X:[[new s.Line(g,n.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new s.Line(g,n.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new s.Line(g,n.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function O(t){const e=new s.Object3D;for(const i in t)for(let s=t[i].length;s--;){const n=t[i][s][0].clone(),r=t[i][s][1],o=t[i][s][2],a=t[i][s][3],l=t[i][s][4];n.name=i,n.tag=l,r&&n.position.set(r[0],r[1],r[2]),o&&n.rotation.set(o[0],o[1],o[2]),a&&n.scale.set(a[0],a[1],a[2]),n.updateMatrix();const h=n.geometry.clone();h.applyMatrix4(n.matrix),n.geometry=h,n.renderOrder=1/0,n.position.set(0,0,0),n.rotation.set(0,0,0),n.scale.set(1,1,1),e.add(n)}return e}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=O(w)),this.add(this.gizmo.rotate=O(x)),this.add(this.gizmo.scale=O(E)),this.add(this.picker.translate=O(v)),this.add(this.picker.rotate=O(C)),this.add(this.picker.scale=O(S)),this.add(this.helper.translate=O(b)),this.add(this.helper.rotate=O(T)),this.add(this.helper.scale=O(A)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(t){const e="local"===("scale"===this.mode?"local":this.space)?this.worldQuaternion:Br;this.gizmo.translate.visible="translate"===this.mode,this.gizmo.rotate.visible="rotate"===this.mode,this.gizmo.scale.visible="scale"===this.mode,this.helper.translate.visible="translate"===this.mode,this.helper.rotate.visible="rotate"===this.mode,this.helper.scale.visible="scale"===this.mode;let i=[];i=i.concat(this.picker[this.mode].children),i=i.concat(this.gizmo[this.mode].children),i=i.concat(this.helper[this.mode].children);for(let t=0;t<i.length;t++){const s=i[t];let n;if(s.visible=!0,s.rotation.set(0,0,0),s.position.copy(this.worldPosition),n=this.camera.isOrthographicCamera?(this.camera.top-this.camera.bottom)/this.camera.zoom:this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),s.scale.set(1,1,1).multiplyScalar(n*this.size/4),"helper"!==s.tag){if(s.quaternion.copy(e),"translate"===this.mode||"scale"===this.mode){const t=.99,i=.2;"X"===s.name&&Math.abs(Mr.copy(Lr).applyQuaternion(e).dot(this.eye))>t&&(s.scale.set(1e-10,1e-10,1e-10),s.visible=!1),"Y"===s.name&&Math.abs(Mr.copy(Rr).applyQuaternion(e).dot(this.eye))>t&&(s.scale.set(1e-10,1e-10,1e-10),s.visible=!1),"Z"===s.name&&Math.abs(Mr.copy(Fr).applyQuaternion(e).dot(this.eye))>t&&(s.scale.set(1e-10,1e-10,1e-10),s.visible=!1),"XY"===s.name&&Math.abs(Mr.copy(Fr).applyQuaternion(e).dot(this.eye))<i&&(s.scale.set(1e-10,1e-10,1e-10),s.visible=!1),"YZ"===s.name&&Math.abs(Mr.copy(Lr).applyQuaternion(e).dot(this.eye))<i&&(s.scale.set(1e-10,1e-10,1e-10),s.visible=!1),"XZ"===s.name&&Math.abs(Mr.copy(Rr).applyQuaternion(e).dot(this.eye))<i&&(s.scale.set(1e-10,1e-10,1e-10),s.visible=!1)}else"rotate"===this.mode&&(zr.copy(e),Mr.copy(this.eye).applyQuaternion(_r.copy(e).invert()),-1!==s.name.search("E")&&s.quaternion.setFromRotationMatrix(kr.lookAt(this.eye,Dr,Rr)),"X"===s.name&&(_r.setFromAxisAngle(Lr,Math.atan2(-Mr.y,Mr.z)),_r.multiplyQuaternions(zr,_r),s.quaternion.copy(_r)),"Y"===s.name&&(_r.setFromAxisAngle(Rr,Math.atan2(Mr.x,Mr.z)),_r.multiplyQuaternions(zr,_r),s.quaternion.copy(_r)),"Z"===s.name&&(_r.setFromAxisAngle(Fr,Math.atan2(Mr.y,Mr.x)),_r.multiplyQuaternions(zr,_r),s.quaternion.copy(_r)));s.visible=s.visible&&(-1===s.name.indexOf("X")||this.showX),s.visible=s.visible&&(-1===s.name.indexOf("Y")||this.showY),s.visible=s.visible&&(-1===s.name.indexOf("Z")||this.showZ),s.visible=s.visible&&(-1===s.name.indexOf("E")||this.showX&&this.showY&&this.showZ),s.material._color=s.material._color||s.material.color.clone(),s.material._opacity=s.material._opacity||s.material.opacity,s.material.color.copy(s.material._color),s.material.opacity=s.material._opacity,this.enabled&&this.axis&&(s.name===this.axis||this.axis.split("").some(function(t){return s.name===t}))&&(s.material.color.setHex(16776960),s.material.opacity=1)}else s.visible=!1,"AXIS"===s.name?(s.visible=!!this.axis,"X"===this.axis&&(_r.setFromEuler(Ir.set(0,0,0)),s.quaternion.copy(e).multiply(_r),Math.abs(Mr.copy(Lr).applyQuaternion(e).dot(this.eye))>.9&&(s.visible=!1)),"Y"===this.axis&&(_r.setFromEuler(Ir.set(0,0,Math.PI/2)),s.quaternion.copy(e).multiply(_r),Math.abs(Mr.copy(Rr).applyQuaternion(e).dot(this.eye))>.9&&(s.visible=!1)),"Z"===this.axis&&(_r.setFromEuler(Ir.set(0,Math.PI/2,0)),s.quaternion.copy(e).multiply(_r),Math.abs(Mr.copy(Fr).applyQuaternion(e).dot(this.eye))>.9&&(s.visible=!1)),"XYZE"===this.axis&&(_r.setFromEuler(Ir.set(0,Math.PI/2,0)),Mr.copy(this.rotationAxis),s.quaternion.setFromRotationMatrix(kr.lookAt(Dr,Mr,Rr)),s.quaternion.multiply(_r),s.visible=this.dragging),"E"===this.axis&&(s.visible=!1)):"START"===s.name?(s.position.copy(this.worldPositionStart),s.visible=this.dragging):"END"===s.name?(s.position.copy(this.worldPosition),s.visible=this.dragging):"DELTA"===s.name?(s.position.copy(this.worldPositionStart),s.quaternion.copy(this.worldQuaternionStart),mr.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),mr.applyQuaternion(this.worldQuaternionStart.clone().invert()),s.scale.copy(mr),s.visible=this.dragging):(s.quaternion.copy(e),this.dragging?s.position.copy(this.worldPositionStart):s.position.copy(this.worldPosition),this.axis&&(s.visible=-1!==this.axis.search(s.name)))}super.updateMatrixWorld(t)}}class Wr extends s.Mesh{constructor(){super(new s.PlaneGeometry(1e5,1e5,2,2),new s.MeshBasicMaterial({visible:!1,wireframe:!0,side:s.DoubleSide,transparent:!0,opacity:.1,toneMapped:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(t){let e=this.space;switch(this.position.copy(this.worldPosition),"scale"===this.mode&&(e="local"),Vr.copy(Lr).applyQuaternion("local"===e?this.worldQuaternion:Br),jr.copy(Rr).applyQuaternion("local"===e?this.worldQuaternion:Br),Hr.copy(Fr).applyQuaternion("local"===e?this.worldQuaternion:Br),Mr.copy(jr),this.mode){case"translate":case"scale":switch(this.axis){case"X":Mr.copy(this.eye).cross(Vr),Nr.copy(Vr).cross(Mr);break;case"Y":Mr.copy(this.eye).cross(jr),Nr.copy(jr).cross(Mr);break;case"Z":Mr.copy(this.eye).cross(Hr),Nr.copy(Hr).cross(Mr);break;case"XY":Nr.copy(Hr);break;case"YZ":Nr.copy(Vr);break;case"XZ":Mr.copy(Hr),Nr.copy(jr);break;case"XYZ":case"E":Nr.set(0,0,0)}break;default:Nr.set(0,0,0)}0===Nr.length()?this.quaternion.copy(this.cameraQuaternion):(Ur.lookAt(mr.set(0,0,0),Nr,Mr),this.quaternion.setFromRotationMatrix(Ur)),super.updateMatrixWorld(t)}}class Yr{constructor(t,i,s,n,r,o=5,l=!0){if(e(this,"onDraggingStarted",new h),e(this,"onDraggingEnded",new h),e(this,"onDisposed",new h),e(this,"normal"),e(this,"origin"),e(this,"three",new a.Plane),e(this,"components"),e(this,"world"),e(this,"type","default"),e(this,"_title","Clipping Plane"),e(this,"_helper"),e(this,"_visible",!0),e(this,"_enabled",!0),e(this,"_controlsActive",!1),e(this,"_arrowBoundBox",new a.Mesh),e(this,"_planeMesh"),e(this,"_controls"),e(this,"_hiddenMaterial",new a.MeshBasicMaterial({visible:!1})),e(this,"_visibilityBeforeDisabled",!0),e(this,"notifyManager",()=>{const t=this.components.get(qr),e=t.list.getKey(this);e&&t.list.set(e,this)}),e(this,"update",()=>{this._enabled&&this.three.setFromNormalAndCoplanarPoint(this.normal,this._helper.position)}),e(this,"changeDrag",t=>{this._visible=!t.value,this.preventCameraMovement(),this.notifyDraggingChanged(t)}),this.components=t,this.world=i,!i.renderer)throw new Error("The given world must have a renderer!");this.normal=n,this.origin=s,i.renderer.setPlane(!0,this.three),this._planeMesh=Yr.newPlaneMesh(o,r),this._helper=this.newHelper(),this._controls=this.newTransformControls(),this.three.setFromNormalAndCoplanarPoint(n,s),l&&this.toggleControls(!0)}set title(t){this._title=t,this.notifyManager()}get title(){return this._title}get enabled(){return this._enabled}set enabled(t){if(!this.world.isDisposing){if(!this.world.renderer)throw new Error("No renderer found for clipping plane!");this._enabled=t,t?this.visible=this._visibilityBeforeDisabled:(this._visibilityBeforeDisabled=this.visible,this.visible=!1),this.world.renderer.setPlane(t,this.three),this.notifyManager()}}get visible(){return this._visible}set visible(t){this._visible=t,this._controls.getHelper().visible=t,this._helper.visible=t,this.toggleControls(t),this.notifyManager()}get meshes(){return[this._planeMesh,this._arrowBoundBox]}get planeMaterial(){return this._planeMesh.material}set planeMaterial(t){this._planeMesh.material=t}get size(){return this._planeMesh.scale.x}set size(t){this._planeMesh.scale.set(t,t,t)}get helper(){return this._helper}get controls(){return this._controls}setFromNormalAndCoplanarPoint(t,e){this.reset(),this.normal.equals(t)||(this.normal.copy(t),this._helper.lookAt(t)),this.origin.copy(e),this._helper.position.copy(e),this._helper.updateMatrix(),this.update()}dispose(){this._enabled=!1,this.onDraggingStarted.reset(),this.onDraggingEnded.reset(),this._helper.removeFromParent(),this.world.renderer&&this.world.renderer.setPlane(!1,this.three),this._arrowBoundBox.removeFromParent(),this._arrowBoundBox.geometry.dispose(),this._planeMesh.geometry.dispose(),this._controls.getHelper().removeFromParent(),this._controls.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}reset(){const t=new a.Vector3(1,0,0),e=new a.Vector3;this.normal.equals(t)||(this.normal.copy(t),this._helper.lookAt(t)),this.origin.copy(e),this._helper.position.copy(e),this._helper.updateMatrix()}toggleControls(t){if(t){if(this._controlsActive)return;this._controls.addEventListener("change",this.update),this._controls.addEventListener("dragging-changed",this.changeDrag)}else this._controls.removeEventListener("change",this.update),this._controls.removeEventListener("dragging-changed",this.changeDrag);this._controlsActive=t}newTransformControls(){if(!this.world.renderer)throw new Error("No renderer found for clipping plane!");const t=this.world.camera.three,e=this.world.renderer.three.domElement,i=new Tr(t,e);return this.initializeControls(i),this.world.scene.three.add(i.getHelper()),i}initializeControls(t){t.attach(this._helper),t.showX=!1,t.showY=!1,t.setSpace("local"),this.createArrowBoundingBox(),t.getHelper().children[0].children[0].add(this._arrowBoundBox)}createArrowBoundingBox(){this._arrowBoundBox.geometry=new a.CylinderGeometry(.18,.18,1.2),this._arrowBoundBox.material=this._hiddenMaterial,this._arrowBoundBox.rotateX(Math.PI/2),this._arrowBoundBox.updateMatrix(),this._arrowBoundBox.geometry.applyMatrix4(this._arrowBoundBox.matrix)}notifyDraggingChanged(t){t.value?this.onDraggingStarted.trigger():this.onDraggingEnded.trigger()}preventCameraMovement(){this.world.camera.enabled=this._visible}newHelper(){const t=new a.Object3D;return t.lookAt(this.normal),t.position.copy(this.origin),this._planeMesh.position.z+=.01,t.add(this._planeMesh),this.world.scene.three.add(t),t}static newPlaneMesh(t,e){const i=new a.PlaneGeometry(1),s=new a.Mesh(i,e);return s.scale.set(t,t,t),s}}class Gr extends $t{constructor(){super(...arguments),e(this,"_config",{enabled:{value:!0,type:"Boolean"},visible:{value:!0,type:"Boolean"},color:{value:new a.Color,type:"Color"},opacity:{type:"Number",interpolable:!0,value:1,min:0,max:1},size:{type:"Number",interpolable:!0,value:2,min:0,max:100}})}get enabled(){return this._config.enabled.value}set enabled(t){this._config.enabled.value=t,this._component.enabled=t}get visible(){return this._config.visible.value}set visible(t){this._config.visible.value=t,this._component.visible=t}get color(){return this._config.color.value}set color(t){this._config.color.value=t,this._component.material.color.copy(t)}get opacity(){return this._config.opacity.value}set opacity(t){this._config.opacity.value=t,this._component.material.opacity=t}get size(){return this._config.size.value}set size(t){this._config.size.value=t,this._component.size=t}}const Xr=class t extends d{constructor(i){super(i),e(this,"onSetup",new h),e(this,"onBeforeDrag",new h),e(this,"onAfterDrag",new h),e(this,"onBeforeCreate",new h),e(this,"onBeforeCancel",new h),e(this,"onAfterCancel",new h),e(this,"onBeforeDelete",new h),e(this,"onAfterCreate",new h),e(this,"onAfterDelete",new h),e(this,"onDisposed",new h),e(this,"isSetup",!1),e(this,"orthogonalY",!1),e(this,"toleranceOrthogonalY",.7),e(this,"Type",Yr),e(this,"list",new o.DataMap),e(this,"config",new Gr(this,this.components,"Clipper",t.uuid)),e(this,"_defaultConfig",{color:new a.Color(12255487),opacity:.2,size:2}),e(this,"_material",new a.MeshBasicMaterial({color:12255487,side:a.DoubleSide,transparent:!0,opacity:.2})),e(this,"_size",5),e(this,"_enabled",!1),e(this,"_visible",!0),e(this,"onStateChanged",new h),e(this,"_onStartDragging",()=>{this.onBeforeDrag.trigger()}),e(this,"_onEndDragging",()=>{this.onAfterDrag.trigger()}),this.components.add(t.uuid,this),this.setEvents()}get enabled(){return this._enabled}set enabled(t){this._enabled=t,this.onStateChanged.trigger(["enabled"])}get visible(){return this._visible}set visible(t){this._visible=t;for(const[e,i]of this.list)i.visible=t;this.onStateChanged.trigger(["visibility"])}get material(){return this._material}set material(t){this._material=t;for(const[e,i]of this.list)i.planeMaterial=t;this.onStateChanged.trigger(["material"])}get size(){return this._size}set size(t){this._size=t;for(const[e,i]of this.list)i.size=t;this.onStateChanged.trigger(["size"])}setEvents(){this.list.onBeforeDelete.add(({value:t})=>{if(!t.world.renderer)throw new Error("Renderer not found for this plane's world!");t.world.renderer.setPlane(!1,t.three),t.dispose(),this.updateMaterialsAndPlanes(),this.onAfterDelete.trigger(t)})}dispose(){this._enabled=!1;this.components.get(Yt).list.delete(this.config.uuid),this.list.clear(),this._material.dispose(),this.onBeforeCreate.reset(),this.onBeforeCancel.reset(),this.onBeforeDelete.reset(),this.onBeforeDrag.reset(),this.onAfterCreate.reset(),this.onAfterCancel.reset(),this.onAfterDelete.reset(),this.onAfterDrag.reset(),this.onDisposed.trigger(t.uuid),this.onDisposed.reset()}async create(t){const e=this.components.get(fe).get(t),i=await e.castRay();return i?this.createPlaneFromIntersection(t,i):null}createFromNormalAndCoplanarPoint(t,e,i){const s=this.newPlane(t,i,e);return this.updateMaterialsAndPlanes(),s}async delete(t,e){if(!e){const i=await this.pickPlane(t);if(!i)return;e=this.list.getKey(i)}e&&this.list.delete(e)}deleteAll(t){for(const[e,i]of this.list)t&&!t.has(i.type)||this.list.delete(e)}setup(t){const e={...this._defaultConfig,...t};this.config.color=e.color,this.config.opacity=e.opacity,this.config.size=e.size,this.isSetup=!0,this.onSetup.trigger()}async pickPlane(t){const e=this.components.get(fe).get(t),i=this.getAllPlaneMeshes(),s=await e.castRay({items:i});if(s){const t=s.object;return[...this.list.values()].find(e=>e.meshes.includes(t))}}getAllPlaneMeshes(){const t=[];for(const[e,i]of this.list)t.push(...i.meshes);return t}createPlaneFromIntersection(t,e){var i;if(!t.renderer)throw new Error("The given world must have a renderer!");const s=e.point.distanceTo(new a.Vector3(0,0,0)),n=e.normal||(null==(i=e.face)?void 0:i.normal);if(!s||!n)return null;const r=this.getWorldNormal(e,n),o=this.newPlane(t,e.point,r.negate()),l=this.list.get(o);return l.visible=this._visible,l.size=this._size,t.renderer.setPlane(!0,l.three),this.updateMaterialsAndPlanes(),l}getWorldNormal(t,e){const i=t.object;let s=t.object.matrixWorld.clone();if(i instanceof a.InstancedMesh&&void 0!==t.instanceId){const e=new a.Matrix4;i.getMatrixAt(t.instanceId,e),s=e.multiply(s)}const n=(new a.Matrix3).getNormalMatrix(s),r=e.clone().applyMatrix3(n).normalize();return this.normalizePlaneDirectionY(r),r}normalizePlaneDirectionY(t){this.orthogonalY&&(t.y>this.toleranceOrthogonalY&&(t.x=0,t.y=1,t.z=0),t.y<-this.toleranceOrthogonalY&&(t.x=0,t.y=-1,t.z=0))}newPlane(t,e,i){const s=new this.Type(this.components,t,e,i,this._material);s.onDraggingStarted.add(this._onStartDragging),s.onDraggingEnded.add(this._onEndDragging);const n=v.create();return this.list.set(n,s),this.onAfterCreate.trigger(s),n}updateMaterialsAndPlanes(){const t=this.components.get(wi);for(const[e,i]of t.list){if(!i.renderer)continue;i.renderer.updateClippingPlanes();const{clippingPlanes:t}=i.renderer;for(const e of i.meshes)if(e.material)if(Array.isArray(e.material))for(const i of e.material)i.clippingPlanes=t;else e.material.clippingPlanes=t}}};e(Xr,"uuid","66290bc5-18c4-4cd1-9379-2e17a0617611");let qr=Xr;class Qr{constructor(t,i){e(this,"title"),e(this,"guid",v.create()),e(this,"clippingPlanes",new o.DataSet),e(this,"camera",{aspect_ratio:1,field_of_view:60,camera_direction:{x:0,y:0,z:0},camera_view_point:{x:0,y:0,z:0},camera_up_vector:{x:0,y:1,z:0}}),e(this,"customData",{}),e(this,"exceptionComponents",new o.DataSet),e(this,"selectionComponents",new o.DataSet),e(this,"componentColors",new o.DataMap),e(this,"spacesVisible",!1),e(this,"spaceBoundariesVisible",!1),e(this,"openingsVisible",!1),e(this,"defaultVisibility",!0),e(this,"snapshot",this.guid),e(this,"_components"),e(this,"_world",null),e(this,"notifyUpdate",()=>{this._components.get(to).list.set(this.guid,this)}),this._components=t,i&&(this.guid=i.guid??this.guid,this.set(i)),this.setEvents()}async getSelectionMap(){const t=this._components.get(qt);return await t.guidsToModelIdMap([...this.selectionComponents])}async getExceptionMap(){const t=this._components.get(qt);return await t.guidsToModelIdMap([...this.exceptionComponents])}get projection(){return"field_of_view"in this.camera?"Perspective":"Orthographic"}get position(){const t=this._components.get(qt),{camera_view_point:e}=this.camera,{x:i,y:s,z:n}=e,r=new a.Vector3(i,s,n);return t.applyBaseCoordinateSystem(r,new a.Matrix4),r}set position(t){const e=t.clone(),i=this._components.get(qt);t.clone().applyMatrix4(i.baseCoordinationMatrix.clone().invert()),this.camera.camera_view_point={x:e.x,y:e.y,z:e.z}}get direction(){const{camera_direction:t}=this.camera,{x:e,y:i,z:s}=t;return new a.Vector3(e,i,s)}set world(t){this._world=t}get world(){return this._world}get _managerVersion(){return this._components.get(pr).config.version}get topics(){return[...this._components.get(pr).list.values()].filter(t=>t.viewpoints.has(this.guid))}setEvents(){this.selectionComponents.onUpdated.add(this.notifyUpdate),this.exceptionComponents.onUpdated.add(this.notifyUpdate),this.clippingPlanes.onUpdated.add(this.notifyUpdate),this.componentColors.onItemSet.add(this.notifyUpdate),this.componentColors.onItemDeleted.add(this.notifyUpdate),this.componentColors.onItemUpdated.add(this.notifyUpdate),this.componentColors.onCleared.add(this.notifyUpdate)}set(t){this.title=t.title;const{components:e,perspective_camera:i,orthogonal_camera:s,clipping_planes:n}=t;if(e){const{selection:t,visibility:i,coloring:s}=e;if(t){this.selectionComponents.clear();for(const{ifc_guid:e}of t)e&&this.selectionComponents.add(e)}if(i){const{default_visibility:t,exceptions:e,view_setup_hints:s}=i;if(void 0!==t&&(this.defaultVisibility=t),e){this.exceptionComponents.clear();for(const{ifc_guid:t}of e)t&&this.exceptionComponents.add(t)}if(s){const{spaces_visible:t,space_boundaries_visible:e,openings_visible:i}=s;void 0!==t&&(this.spacesVisible=t),void 0!==e&&(this.spaceBoundariesVisible=e),void 0!==i&&(this.openingsVisible=i)}}if(s){this.componentColors.clear();for(const t of s){const{color:e,components:i}=t,s=i.map(t=>t.ifc_guid).filter(t=>null!==t);this.componentColors.set(e,s)}}}if((i||s)&&(this.camera=i??s),n&&this.world){const t=this._components.get(qr);for(const e of n){const{location:i,direction:s}=e,n=new a.Vector3(i.x,i.z,-i.y),r=new a.Vector3(s.x,s.z,-s.y),o=t.createFromNormalAndCoplanarPoint(this.world,r,n);this.clippingPlanes.add(o),t.list.get(o).enabled=!1,t.list.get(o).visible=!1}}this.notifyUpdate()}async go(t){if(!this.world)return;const{camera:e}=this.world;if(!(e instanceof sr))throw new Error("Viewpoint: the world's camera component must be of type OrthoPerspectiveCamera to switch between perspective and orthographic projections.");const{transition:i,applyClippings:s,applyVisibility:n,clippingsVisibility:r}={transition:!0,applyClippings:!0,applyVisibility:!0,clippingsVisibility:!0,...t};e.projection.set(this.projection);const o=new a.Vector3(this.camera.camera_view_point.x,this.camera.camera_view_point.y,this.camera.camera_view_point.z),l=new a.Vector3(this.camera.camera_direction.x,this.camera.camera_direction.y,this.camera.camera_direction.z);if(o.equals(new a.Vector3)&&l.equals(new a.Vector3))return;const h=this.position,c=this.direction,d={x:h.x+80*c.x,y:h.y+80*c.y,z:h.z+80*c.z},u=[];s&&this.setClippingState(!0),n&&u.push(this.applyVisibility()),this.setClippingVisibility(r),u.push(e.controls.setLookAt(h.x,h.y,h.z,d.x,d.y,d.z,i)),await Promise.all(u)}async updateCamera(t=!0){return new Promise(e=>{if(!this.world)return void e(!1);const{camera:i,renderer:s}=this.world;if(!s)throw new Error("Viewpoint: the world needs to have a renderer!");if(!i.hasCameraControls())throw new Error("Viewpoint: world's camera need camera controls!");const n=new a.Vector3;i.controls.getPosition(n);const r=i.three,o=new a.Vector3(0,0,-1).applyEuler(r.rotation),{width:l,height:h}=s.getSize();let c=l/h;Number.isNaN(c)&&(c=1);const d=this._components.get(qt);n.applyMatrix4(d.baseCoordinationMatrix.clone().invert());const u={aspect_ratio:c,camera_view_point:{x:n.x,y:n.y,z:n.z},camera_direction:{x:o.x,y:o.y,z:o.z},camera_up_vector:{x:0,y:1,z:0}};if(r instanceof a.PerspectiveCamera?this.camera={...u,field_of_view:r.fov}:r instanceof a.OrthographicCamera&&(this.camera={...u,view_to_world_scale:r.top-r.bottom}),t){const t=this._components.get(to),n=s.three.domElement;s.three.render(this.world.scene.three,i.three),n.toBlob(async i=>{if(i){const e=await i.arrayBuffer(),s=new Uint8Array(e);t.snapshots.set(this.guid,s)}this.notifyUpdate(),e(!0)})}else this.notifyUpdate(),e(!0)})}takeSnapshot(){return new Promise(t=>{if(!this.world)return void t(!1);const{camera:e,renderer:i}=this.world;if(!i)throw new Error("Viewpoint: the world needs to have a renderer!");const s=this._components.get(to),n=i.three.domElement;i.three.render(this.world.scene.three,e.three),n.toBlob(async e=>{if(e){const t=await e.arrayBuffer(),i=new Uint8Array(t);s.snapshots.set(this.guid,i)}this.notifyUpdate(),t(!0)})})}updateClippingPlanes(){this.clippingPlanes.clear();const t=this._components.get(qr);for(const[e,i]of t.list)i.enabled&&this.clippingPlanes.add(e)}async applyVisibility(){const t=this._components.get(ee);t.set(this.defaultVisibility);const e=await this.getExceptionMap();t.set(!this.defaultVisibility,e);const i=await this.getSelectionMap();t.set(!0,i)}async setColorizationState(t){const e=this._components.get(qt),i=[];if(t)for(const[t,s]of this.componentColors){const n=`#${t}`,r=await e.guidsToModelIdMap(s);for(const[t,s]of Object.entries(r)){const r=e.list.get(t);r&&i.push(r.highlight([...s],{customId:n,color:new a.Color(n),renderedFaces:o.RenderedFaces.ONE,opacity:1,transparent:!1}))}}else for(const[t,s]of this.componentColors){const t=await e.guidsToModelIdMap(s);for(const[s,n]of Object.entries(t)){const t=e.list.get(s);t&&i.push(t.resetHighlight([...n]))}}i.push(e.core.update(!0)),await Promise.all(i)}setClippingState(t){const e=this._components.get(qr);for(const[i,s]of e.list)s.enabled=t&&this.clippingPlanes.has(i)}setClippingVisibility(t){const e=this._components.get(qr);for(const i of this.clippingPlanes){const s=e.list.get(i);s&&(s.visible=t)}}async createComponentTags(t){var e;const i=this._components.get(qt);let s="";if(this._components.get(pr).config.includeSelectionTag){const n="selection"===t?await this.getSelectionMap():await this.getExceptionMap();for(const t in n){const r=i.list.get(t);if(!r)continue;const o=n[t];for(const t of o){const i=r.getItem(t),n=await i.getGuid();if(!n)continue;const o=null==(e=await i.getAttributes())?void 0:e.getValue("Tag");let a=null;o&&(a=`AuthoringToolId="${o}"`),s+=`\n<Component IfcGuid="${n}" ${a??""} />`}}}else s=[...this.selectionComponents].map(t=>`<Component IfcGuid="${t}" />`).join("\n");return s}createColorTags(){let t="";for(const[e,i]of this.componentColors.entries()){t+=`<Color Color="${e}">\n${i.map(t=>`\n<Component IfcGuid="${t}" />`).join("\n")}\n</Color>`}return 0!==t.length?`<Coloring>\n${t}\n</Coloring>`:"<Coloring />"}toJSON(){const t=this._components.get(qr),e={guid:this.guid,components:{selection:[...this.selectionComponents].map(t=>({ifc_guid:t,authoring_tool_id:null})),coloring:[...this.componentColors].map(([t,e])=>({color:t,components:e.map(t=>({ifc_guid:t,authoring_tool_id:null}))})),visibility:{default_visibility:this.defaultVisibility,exceptions:[...this.exceptionComponents].map(t=>({ifc_guid:t,authoring_tool_id:null})),view_setup_hints:{spaces_visible:this.spacesVisible,space_boundaries_visible:this.spaceBoundariesVisible,openings_visible:this.openingsVisible}}},clipping_planes:[...this.clippingPlanes].map(e=>{const i=t.list.get(e);if(!i)return null;const s=i._controls.worldPosition??i.origin,{normal:n}=i;return{location:{x:s.x,y:-s.z,z:s.y},direction:{x:n.x,y:-n.z,z:n.y}}}).filter(t=>null!==t)};"field_of_view"in this.camera?e.perspective_camera=this.camera:e.orthogonal_camera=this.camera;const i=this._components.get(to),s=i.snapshots.get(this.snapshot);if(s){const t=s.toString(),n=btoa(t),r=i.getSnapshotExtension(this.snapshot);e.snapshot={snapshot_type:r,snapshot_data:n}}return e}async serialize(t=this._managerVersion){const e=this._components.get(qt),i=this.position;i.applyMatrix4(e.baseCoordinationMatrix.clone().invert());const s=this.direction;s.normalize();const n=(new a.Matrix4).makeRotationX(Math.PI/2),r=s.clone().applyMatrix4(n);r.normalize();const o=`<CameraViewPoint>\n <X>${i.x}</X>\n <Y>${-i.z}</Y>\n <Z>${i.y}</Z>\n </CameraViewPoint>`,l=`<CameraDirection>\n <X>${s.x}</X>\n <Y>${-s.z}</Y>\n <Z>${s.y}</Z>\n </CameraDirection>`,h=`<CameraUpVector>\n <X>${r.x}</X>\n <Y>${-r.z}</Y>\n <Z>${r.y}</Z>\n </CameraUpVector>`,c=`<AspectRatio>${this.camera.aspect_ratio}</AspectRatio>`;let d="";"view_to_world_scale"in this.camera?d=`<OrthogonalCamera>\n ${o}\n ${l}\n ${h}\n ${c}\n <ViewToWorldScale>${this.camera.view_to_world_scale}</ViewToWorldScale>\n </OrthogonalCamera>`:"field_of_view"in this.camera&&(d=`<PerspectiveCamera>\n ${o}\n ${l}\n ${h}\n ${c}\n <FieldOfView>${this.camera.field_of_view}</FieldOfView>\n </PerspectiveCamera>`);const u=`<ViewSetupHints SpacesVisible="${this.spacesVisible??!1}" SpaceBoundariesVisible="${this.spaceBoundariesVisible??!1}" OpeningsVisible="${this.openingsVisible??!1}" />`,p=(await this.createComponentTags("selection")).trim(),f=(await this.createComponentTags("exception")).trim(),m=this.createColorTags();return`<?xml version="1.0" encoding="UTF-8"?>\n <VisualizationInfo Guid="${this.guid}">\n <Components>\n ${"2.1"===t?u:""}\n ${0!==p.length?`<Selection>${p}</Selection>`:""}\n <Visibility DefaultVisibility="${this.defaultVisibility}">\n ${"3"===t?u:""}\n ${0!==f.length?`<Exceptions>${f}</Exceptions>`:""}\n </Visibility>\n ${m}\n </Components>\n ${d}\n </VisualizationInfo>`}}class Kr extends $t{constructor(){super(...arguments),e(this,"_config",{overwriteColors:{value:!1,type:"Boolean"}})}get overwriteColors(){return this._config.overwriteColors.value}set overwriteColors(t){this._config.overwriteColors.value=t}}const Jr=class t extends d{constructor(s){super(s),e(this,"enabled",!0),e(this,"world",null),e(this,"list",new i.DataMap),e(this,"snapshots",new i.DataMap),e(this,"isSetup",!1),e(this,"onSetup",new h),e(this,"config",new Kr(this,this.components,"Viewpoints",t.uuid)),e(this,"onDisposed",new h),s.add(t.uuid,this)}create(t){const e=new Qr(this.components,t);return e.world=this.world,t||this.list.set(e.guid,e),e}getSnapshotExtension(t){let e="jpeg";const i=this.snapshots.get(t);if(!i)return e;const s=i.subarray(0,4);let n="";for(let t=0;t<s.length;t++)n+=s[t].toString(16);return n.startsWith("89504e47")&&(e="png"),n.startsWith("ffd8ffe")&&(e="jpeg"),e}setup(){}dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}};e(Jr,"uuid","ee867824-a796-408d-8aa0-4e5962a83c66");let to=Jr;class eo{constructor(t,i){e(this,"_components"),e(this,"_cameraOffset",10),e(this,"_planeHelper"),e(this,"_farPlaneHelper"),e(this,"_cameraHelper"),e(this,"onStateChanged",new h),e(this,"onUpdated",new h),e(this,"onDisposed",new h),e(this,"camera"),e(this,"plane",new a.Plane),e(this,"farPlane",new a.Plane),e(this,"id",v.create()),e(this,"_open",!1),e(this,"_range",so.defaultRange),e(this,"_world",null),e(this,"_helpersVisible",!1),e(this,"_planesEnabled",!1),this._components=t,this.camera=new sr(this._components);const{threeOrtho:s}=this.camera;if((null==i?void 0:i.id)&&(this.id=i.id),(null==i?void 0:i.normal)&&(null==i?void 0:i.point)){const{normal:t,point:e}=i;this.plane.setFromNormalAndCoplanarPoint(t,e)}this._cameraHelper=new a.CameraHelper(s),this._planeHelper=new a.PlaneHelper(this.plane,50),this._farPlaneHelper=new a.PlaneHelper(this.farPlane,50),this.farPlaneHelperColor=new a.Color("blue"),this.update()}get _planeNormalOpposite(){return this.plane.normal.clone().negate()}get _planePosition(){return this.plane.normal.clone().multiplyScalar(-this.plane.constant)}get _cameraPosition(){return this._planePosition.addScaledVector(this._planeNormalOpposite,this._cameraOffset)}set open(t){this._open=t,this.onStateChanged.trigger(["open"])}get open(){return this._open}set planeHelperColor(t){!Array.isArray(this._planeHelper.material)&&"color"in this._planeHelper.material&&this._planeHelper.material.color instanceof a.Color&&(this._planeHelper.material.color=t)}set farPlaneHelperColor(t){!Array.isArray(this._farPlaneHelper.material)&&"color"in this._farPlaneHelper.material&&this._farPlaneHelper.material.color instanceof a.Color&&(this._farPlaneHelper.material.color=t)}set range(t){this._range=t,this.update()}get range(){return this._range}set distance(t){this.plane.constant=t,this.update()}get distance(){return this.plane.constant}set world(t){this._world=t,this.camera.currentWorld=t,t&&(this.camera.projection.set("Orthographic"),this.camera.set("Plan"),this.camera.controls.dollySpeed=6,this.camera.controls.restThreshold=.005,this.update())}get world(){return this._world}set helpersVisible(t){if(!t)return this._helpersVisible=t,this._planeHelper.removeFromParent(),this._farPlaneHelper.removeFromParent(),void this._cameraHelper.removeFromParent();this.world&&(this._helpersVisible=t,this.world.scene.three.add(this._planeHelper,this._farPlaneHelper))}get helpersVisible(){return this._helpersVisible}set planesEnabled(t){const{world:e}=this;if(!e)return;const{renderer:i}=e;i&&(i.setPlane(t,this.plane),i.setPlane(t,this.farPlane),this._planesEnabled=t)}get planesEnabled(){return this._planesEnabled}dispose(){this.helpersVisible=!1;const t=this._components.get(g);t.destroy(this._planeHelper),t.destroy(this._farPlaneHelper),t.destroy(this._cameraHelper),this.camera.dispose(),this.onDisposed.trigger()}update(){if(this.world){const t=this._cameraPosition,e=this._planePosition;this.camera.controls.setLookAt(t.x,t.y,t.z,e.x,e.y,e.z,!1)}this.farPlane.normal.copy(this._planeNormalOpposite),this.farPlane.constant=this.range-this.plane.constant,this.onUpdated.trigger()}flip(){this.plane.normal.negate(),this.update()}}const io=class t extends d{constructor(s){super(s),e(this,"list",new i.DataMap),e(this,"enabled",!0),e(this,"world",null),e(this,"_fragmentsUpdateEvent",()=>{this.components.get(qt).core.update(!0)}),s.add(t.uuid,this),this.setupEvents()}get hasOpenViews(){return[...this.list.values()].some(t=>t.open)}setupEvents(){this.list.onBeforeDelete.add(({key:t,value:e})=>{e.open&&this.close(t),e.dispose()})}create(t,e,i){const s=new eo(this.components,{id:null==i?void 0:i.id,normal:t,point:e});return s.world=(null==i?void 0:i.world)??this.world,this.list.set(s.id,s),s}createFromPlane(t,e){const i=new eo(this.components,{id:null==e?void 0:e.id});return i.plane.copy(t),i.update(),i.world=(null==e?void 0:e.world)??this.world,this.list.set(i.id,i),i}async createFromIfcStoreys(t){const e=[],i=this.components.get(qt),s=void 0===(null==t?void 0:t.offset)?.25:t.offset;for(const[n,r]of i.list){if(t&&t.modelIds&&!t.modelIds.some(t=>t.test(n)))continue;const i=Object.values(await r.getItemsOfCategories([/BUILDINGSTOREY/])).flat();if(0===i.length)continue;const o=await r.getItemsData(i),[,l]=await r.getCoordinates(),h=new a.Vector3(0,-1,0);for(const i of o){if(!("value"in i.Name)||!("value"in i.Elevation))continue;const{value:n}=i.Name;if((null==t?void 0:t.storeyNames)&&!t.storeyNames.some(t=>t.test(n)))continue;const r=i.Elevation.value+l+s,o=new a.Plane(h,r),c=this.createFromPlane(o,{id:n,world:null==t?void 0:t.world});e.push(c)}}return e}createElevations(t){const e=[],i=this.components.get(qt),s=void 0!==(null==t?void 0:t.combine)&&t.combine,n=(null==t?void 0:t.namingCallback)??(t=>({front:""+(s?"Front":`${t}: Front`),back:""+(s?"Back":`${t}: Back`),left:""+(s?"Left":`${t}: Left`),right:""+(s?"Right":`${t}: Right`)}));let r=[];for(const[e,s]of i.list)t&&t.modelIds&&!t.modelIds.some(t=>t.test(e))||r.push({id:e,box:s.box});if(s){const t=this.components.get(se);t.list.clear(),t.list.add(...r.map(t=>t.box));r=[{id:"combined",box:t.get()}]}for(const{id:i,box:s}of r){const{min:r,max:o}=s,l=Math.abs(o.x-r.x),h=Math.abs(o.z-r.z),c=new a.Vector3;s.getCenter(c);const d=new a.Plane(new a.Vector3(0,0,-1),o.z),u=new a.Plane(new a.Vector3(0,0,1),-r.z),p=new a.Plane(new a.Vector3(-1,0,0),o.x),f=new a.Plane(new a.Vector3(1,0,0),-r.x),{front:m,back:g,left:_,right:y}=n(i),w=this.createFromPlane(d,{id:m,world:null==t?void 0:t.world});w.range=h;const v=this.createFromPlane(u,{id:g,world:null==t?void 0:t.world});v.range=h;const b=this.createFromPlane(p,{id:_,world:null==t?void 0:t.world});b.range=l;const x=this.createFromPlane(f,{id:y,world:null==t?void 0:t.world});x.range=l,e.push(w,v,b,x)}return e}open(t){const e=this.list.get(t);if(!e)throw new Error(`Views: the view with id ${t} doesn't exist.`);if(e.open)return;const{world:i}=e;if(!i)throw new Error(`Views: no world found for view with id ${t}.`);const{renderer:s}=i;if(!s)throw new Error(`Views: no renderer found for world with id ${i.uuid}.`);for(const[,t]of this.list)t.world===i&&this.close(t.id);s.setPlane(!0,e.plane),s.setPlane(!0,e.farPlane),e.camera.controls.addEventListener("rest",this._fragmentsUpdateEvent),i.camera=e.camera,e.open=!0}close(t){let e;if(e=t?this.list.get(t):[...this.list.values()].find(t=>t.open),t&&!e)throw new Error(`Views: the view with id ${t} doesn't exist.`);if(!e)return;if(!e.open)return;const{world:i}=e;if(!i)throw new Error(`Views: no world found for view with id ${t}.`);const{renderer:s}=i;if(!s)throw new Error(`Views: no renderer found for world with id ${i.uuid}.`);s.setPlane(!1,e.plane),s.setPlane(!1,e.farPlane),e.camera.controls.removeEventListener("rest",this._fragmentsUpdateEvent),i.useDefaultCamera(),e.open=!1}};e(io,"uuid","fb22f1f5-6598-4664-a11d-de8963ae420f"),e(io,"defaultRange",15);let so=io;async function no(t,e,i,s,n,r,o){const a=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),await function(t,e,i,s){return new Promise((n,r)=>{!function o(){const a=t.clientWaitSync(e,i,0);a!==t.WAIT_FAILED?a!==t.TIMEOUT_EXPIRED?n():setTimeout(o,s):r()}()})}(t,a,0,10),t.deleteSync(a),t.bindBuffer(e,i),t.getBufferSubData(e,s,n,r,o),t.bindBuffer(e,null)}class ro{constructor(t,i){if(e(this,"onDisposed",new h),e(this,"onDistanceComputed",new h),e(this,"excludedObjects",new Set),e(this,"enabled",!0),e(this,"renderDebugFrame",!1),e(this,"components"),e(this,"scene",new a.Scene),e(this,"camera",new a.OrthographicCamera(-1,1,1,-1,0,1)),e(this,"depthMaterial"),e(this,"world"),e(this,"worker"),e(this,"_width",512),e(this,"_height",512),e(this,"_postQuad"),e(this,"tempRT"),e(this,"resultRT"),e(this,"bufferSize"),e(this,"_buffer"),e(this,"_isWorkerBusy",!1),e(this,"compute",async()=>{if(!this.enabled||this.world.isDisposing)return;if(this._isWorkerBusy)return;this._isWorkerBusy=!0,this.world.camera.three.updateMatrix();const t=this.world.renderer.three;t.setRenderTarget(this.tempRT);const e="visibilityBeforeDistanceCheck";for(const t of this.excludedObjects)t.userData[e]=t.visible,t.visible=!1;t.render(this.world.scene.three,this.world.camera.three);for(const t of this.excludedObjects)void 0!==t.userData[e]&&(t.visible=t.userData[e]);this.depthMaterial.uniforms.tDiffuse.value=this.tempRT.texture,this.depthMaterial.uniforms.tDepth.value=this.tempRT.depthTexture,t.setRenderTarget(this.resultRT),t.render(this.scene,this.camera);const i=t.getContext();try{await async function(t,e,i,s,n,r,o,a){const l=t.createBuffer();return t.bindBuffer(t.PIXEL_PACK_BUFFER,l),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(e,i,s,n,r,o,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),await no(t,t.PIXEL_PACK_BUFFER,l,0,a),t.deleteBuffer(l),a}(i,0,0,this._width,this._height,i.RGBA,i.UNSIGNED_BYTE,this._buffer)}catch(e){return t.setRenderTarget(null),void(this._isWorkerBusy=!1)}t.setRenderTarget(null),this.renderDebugFrame&&t.render(this.scene,this.camera),this.worker.postMessage({buffer:this._buffer})}),e(this,"handleWorkerMessage",t=>{if(!this.enabled||this.world.isDisposing)return;const e=t.data.colors;let i=Number.MAX_VALUE;for(const t of e)0!==t&&t<i&&(i=t);const s=this.world.camera.three||a.OrthographicCamera,n=-1*(i/255-1)*(s.far-s.near),r=Math.min(n,s.far);this.onDistanceComputed.trigger(r),this._isWorkerBusy=!1}),!i.renderer)throw new Error("The given world must have a renderer!");this.components=t,this.world=i;const s=i.camera.three;this.tempRT=new a.WebGLRenderTarget(this._width,this._height),this.bufferSize=this._width*this._height*4,this._buffer=new Uint8Array(this.bufferSize),this.tempRT.texture.minFilter=a.NearestFilter,this.tempRT.texture.magFilter=a.NearestFilter,this.tempRT.stencilBuffer=!1,this.tempRT.samples=0,this.tempRT.depthTexture=new a.DepthTexture(this._width,this._height),this.tempRT.depthTexture.format=a.DepthFormat,this.tempRT.depthTexture.type=a.UnsignedShortType,this.resultRT=new a.WebGLRenderTarget(this._width,this._height),this.depthMaterial=new a.ShaderMaterial({vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n ",fragmentShader:"\n#include <packing>\n\nvarying vec2 vUv;\nuniform sampler2D tDiffuse;\nuniform sampler2D tDepth;\nuniform float cameraNear;\nuniform float cameraFar;\n\n\nfloat readDepth( sampler2D depthSampler, vec2 coord ) {\n float fragCoordZ = texture2D( depthSampler, coord ).x;\n float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );\n return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );\n}\n\nvoid main() {\n //vec3 diffuse = texture2D( tDiffuse, vUv ).rgb;\n float depth = readDepth( tDepth, vUv );\n\n gl_FragColor.rgb = 1.0 - vec3( depth );\n gl_FragColor.a = 1.0;\n}\n ",uniforms:{cameraNear:{value:s.near},cameraFar:{value:s.far},tDiffuse:{value:null},tDepth:{value:null}}});const n=new a.PlaneGeometry(2,2);this._postQuad=new a.Mesh(n,this.depthMaterial),this.scene.add(this._postQuad);const r=new Blob(['\n addEventListener("message", (event) => {\n const { buffer } = event.data;\n const colors = new Set();\n for (let i = 0; i < buffer.length; i += 4) {\n const r = buffer[i];\n colors.add(r);\n }\n postMessage({ colors });\n });\n '],{type:"application/javascript"});this.worker=new Worker(URL.createObjectURL(r)),this.worker.addEventListener("message",this.handleWorkerMessage)}dispose(){this.enabled=!1,this.onDistanceComputed.reset(),this.worker.terminate(),this.tempRT.dispose(),this.resultRT.dispose();const t=[...this.scene.children];this.excludedObjects.clear();for(const e of t)e.removeFromParent();this._postQuad.geometry.dispose(),this._postQuad.removeFromParent(),this._buffer=null,this.onDisposed.reset()}}class oo{constructor(t){e(this,"cardinality","required"),e(this,"instructions"),e(this,"evalRequirement",(t,e,i,s)=>{const n={parameter:i,currentValue:t,requiredValue:e,pass:!1};s&&this.addCheckResult(n,s);let r=!1;if("simple"===e.type&&(r=t===e.parameter),"enumeration"===e.type&&(r=e.parameter.includes(t)),"pattern"===e.type){r=new RegExp(e.parameter).test(String(t))}if("length"===e.type){const{min:i,length:s,max:n}=e.parameter;void 0!==s&&(r=String(t).length===s),void 0!==i&&(r=String(t).length>=i),void 0!==n&&(r=String(t).length<=n)}if("bounds"===e.type&&"number"==typeof t){const{min:i,minInclusive:s,max:n,maxInclusive:o}=e.parameter;let a=!0,l=!0;void 0!==i&&(a=s?t>=i:t>i),void 0!==n&&(l=o?t<=n:t<n),r=a&&l}return"prohibited"===this.cardinality&&(r=!r),"optional"===this.cardinality&&(r=!0),n.pass=r,n.pass}),this._components=t}addCheckResult(t,e){const i=e.findIndex(({parameter:e})=>e===t.parameter);-1!==i?e[i]=t:e.push(t)}getItemChecks(t,e,i,s){if(!("value"in i._localId)||"number"!=typeof i._localId.value)return null;let n=t.get(e);n||(n=new o.DataMap,t.set(e,n));let r=n.get(i._localId.value);if(r&&s&&!r.pass)return null;if(!r){const t=[];r={guid:Array.isArray(i._guid)?void 0:i._guid.value,pass:!1,checks:t},Object.defineProperty(r,"pass",{get:()=>t.every(({pass:t})=>t)}),n.set(i._localId.value,r)}const a=[],l={facetType:this.facetType,cardinality:this.cardinality,checks:a,pass:!1};return Object.defineProperty(l,"pass",{get:()=>a.every(({pass:t})=>t)}),r.checks.push(l),l.checks}}const ao=(t,e)=>{let i="";if(!e)return i;if("simple"===e.type&&(i=`<simpleValue>${e.parameter}</simpleValue>`),"enumeration"===e.type){i=`<xs:restriction base="xs:string">\n ${e.parameter.map(t=>`<xs:enumeration value="${t}" />`).join("\n")}\n </xs:restriction>`}if("pattern"===e.type){i=`<xs:restriction base="xs:string">\n <xs:pattern value="${e.parameter}" />\n </xs:restriction>`}if("bounds"===e.type){const{min:t,minInclusive:s,max:n,maxInclusive:r}=e.parameter;let o="";void 0!==t&&(o=`<xs:min${s?"Inclusive":"Exclusive"} value="${t}">`);let a="";void 0!==n&&(a=`<xs:max${r?"Inclusive":"Exclusive"} value="${n}">`),i=`<xs:restriction base="xs:double">\n ${o}\n ${a}\n </xs:restriction>`}if("length"===e.type){const{length:t,min:s,max:n}=e.parameter;let r="";void 0!==t&&void 0===s&&void 0===n&&(r=`<xs:length value="${t}" />`);let o="";void 0!==s&&void 0===t&&(o=`<xs:minLength value="${s}" />`);let a="";void 0!==n&&void 0===t&&(a=`<xs:maxLength value="${n}" />`),i=`<xs:restriction base="xs:string">\n ${r}\n ${o}\n ${a}\n </xs:restriction>`}return`<${t[0].toLowerCase()+t.slice(1)}>\n ${i}\n </${t[0].toLowerCase()+t.slice(1)}>`};class lo extends oo{constructor(t,i){super(t),e(this,"facetType","Attribute"),e(this,"name"),e(this,"value"),this.name=i}serialize(t){const e=ao("Name",this.name),i=ao("Value",this.value);let s="";return"requirement"===t&&(s+=`cardinality="${this.cardinality}"`,s+=this.instructions?`instructions="${this.instructions}"`:""),`<attribute ${s}>\n ${e}\n ${i}\n</attribute>`}async getEntities(){}async test(t,e,i={skipIfFails:!0}){const s=this._components.get(qt);for(const[n,r]of Object.entries(t)){const t=s.list.get(n);if(!t)continue;const o=await t.getItemsData([...r]);for(const t of o){const s=this.getItemChecks(e,n,t,i.skipIfFails);if(!s)continue;const r=Object.keys(t).filter(e=>{const i=this.evalRequirement(e,this.name,"Name");if(!i)return!1;const s=t[e];return!!Array.isArray(s)||(null===s||null===s.value?"optional"===this.cardinality||"prohibited"===this.cardinality:(!Array.isArray(s.value)||0!==s.value.length)&&(("string"!=typeof s.value||""!==s.value.trim())&&i))}),o=r.length>0;if(s.push({parameter:"Name",currentValue:o?r[0]:null,requiredValue:this.name,pass:"prohibited"===this.cardinality?!o:o}),this.value)if(r[0]){const e=t[r[0]];if(Array.isArray(e))s.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality});else{Array.isArray(e.value)?s.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality}):this.evalRequirement(e.value,this.value,"Value",s)}}else s.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality})}}}}class ho extends oo{constructor(t,i){super(t),e(this,"facetType","Classification"),e(this,"system"),e(this,"value"),e(this,"uri"),this.system=i}serialize(t){const e=ao("System",this.system),i=ao("Value",this.value);let s="";return"requirement"===t&&(s+=`cardinality="${this.cardinality}"`,s+=this.uri?`uri=${this.uri}`:"",s+=this.instructions?`instructions="${this.instructions}"`:""),`<classification ${s}>\n ${e}\n ${i}\n</classification>`}async getEntities(t,e){}async test(t,e){}}class co extends oo{constructor(t,i){super(t),e(this,"facetType","Entity"),e(this,"name"),e(this,"predefinedType"),this.name=i}serialize(t){const e=ao("Name",this.name),i=ao("Name",this.predefinedType);let s="";return"requirement"===t&&(s+=`cardinality="${this.cardinality}"`,s+=this.instructions?`instructions="${this.instructions}"`:""),`<entity ${s}>\n ${e}\n ${i}\n</entity>`}async getEntities(t,e){const i=this._components.get(qt),s=new Map;for(const[e,n]of i.list){if(!t.find(t=>t.test(e)))continue;const i=await n.getCategories();for(const t of i){if(!await this.evalName(t))continue;let i=s.get(e);i||(i=[],s.set(e,i)),i.push(t)}}const n={};if(await Promise.all(Array.from(s.entries()).map(async([t,e])=>{const s=i.list.get(t);if(!s)return;const r=e.map(t=>new RegExp(`^${t}$`)),o=await s.getItemsOfCategories(r),a=Object.values(o).flat();n[t]=new Set(a)})),this.predefinedType)for(const[t,s]of Object.entries(n)){const n=i.list.get(t);if(!n)continue;const r=await n.getItemsData([...s]);for(const i of r){if(!("value"in i._localId))continue;await this.evalPredefinedType(t,i)&&jt.append(e,t,i._localId.value)}}else jt.add(e,n)}async test(t,e,i){const s=this._components.get(qt);for(const[n,r]of Object.entries(t)){const t=s.list.get(n);if(!t)continue;const o=await t.getItemsData([...r]);for(const t of o){if(!("value"in t._category))continue;const s=this.getItemChecks(e,n,t,i.skipIfFails);s&&(await this.evalName(t._category.value,s),await this.evalPredefinedType(n,t,s))}}}async evalName(t,e){return this.evalRequirement(t,this.name,"Name",e)}async evalPredefinedType(t,e,i){if(!this.predefinedType)return null;if(!("value"in e.PredefinedType))return null;const s="string"==typeof this.predefinedType.parameter&&"USERDEFINED"===this.predefinedType.parameter;let n=e.PredefinedType.value;if("USERDEFINED"===n&&!s){const t=Object.keys(e).find(t=>/^((?!Predefined).)*Type$/.test(t));if(t){const i=e[t];"value"in i&&(n=i.value)}else n="USERDEFINED"}if(!n){const i=this._components.get(qt).list.get(t);if(i&&"value"in e._localId){const[t]=await i.getItemsData([e._localId.value],{relations:{IsTypedBy:{attributes:!0,relations:!1}}});if(Array.isArray(t.IsTypedBy)){const e=t.IsTypedBy[0];if(e&&"value"in e.PredefinedType&&(n=e.PredefinedType.value,"USERDEFINED"===n&&!s)){const t=Object.keys(e).find(t=>/^((?!Predefined).)*Type$/.test(t));if(t){const i=e[t];"value"in i&&(n=i.value)}else n="USERDEFINED"}}}}return this.evalRequirement(n,this.predefinedType,"PredefinedType",i)}}class uo extends oo{constructor(t,i,s){super(t),e(this,"facetType","Property"),e(this,"propertySet"),e(this,"baseName"),e(this,"value"),e(this,"dataType"),e(this,"uri"),e(this,"_unsupportedTypes",["IFCCOMPLEXPROPERTY","IFCPHYSICALCOMPLEXQUANTITY"]),this.propertySet=i,this.baseName=s}serialize(t){const e=ao("PropertySet",this.propertySet),i=ao("BaseName",this.baseName),s=ao("Value",this.value),n=this.dataType?`dataType=${this.dataType}`:"";let r="";return"requirement"===t&&(r+=`cardinality="${this.cardinality}"`,r+=this.uri?`uri=${this.uri}`:"",r+=this.instructions?`instructions="${this.instructions}"`:""),`<property ${n} ${r}>\n ${e}\n ${i}\n ${s}\n</property>`}async getEntities(t,e){const i=this._components.get(qt);for(const[s,n]of i.list){if(!t.find(t=>t.test(s)))continue;const i=await n.getItemsOfCategories([/PROPERTYSET/,/ELEMENTQUANTITY/]),r=Object.values(i).flat();if(0===r.length)continue;const o=await n.getItemsData(r,{relations:{HasProperties:{attributes:!0,relations:!1},DefinesOcurrence:{attributes:!0,relations:!1}}});for(const t of o){if(!("value"in t._localId&&"value"in t._category&&"value"in t.Name&&Array.isArray(t.DefinesOcurrence)))continue;if(!this.evalRequirement(t.Name.value,this.propertySet,"PropertySet"))continue;let i;if("IFCPROPERTYSET"===t._category.value&&(i="HasProperties"),"IFCELEMENTQUANTITY"===t._category.value&&(i="Quantities"),!i)continue;const n=t[i];if(Array.isArray(n))for(const i of n){const n=Object.keys(i),r=n.find(t=>/Name/.test(t));if(!r||!("value"in i[r]))continue;const o=i[r];if(!("value"in o))continue;if(!this.evalRequirement(o.value,this.baseName,"BaseName"))continue;if(this.value){const t=n.find(t=>/Value/.test(t));if(!t)continue;const e=i[t];if(!("value"in e))continue;if(!this.evalRequirement(e.value,this.value,"Value"))continue}const a=t.DefinesOcurrence.map(t=>"value"in t._localId&&"number"==typeof t._localId.value?t._localId.value:null).filter(t=>null!==t);jt.append(e,s,...a)}}}}async test(t,e,i={skipIfFails:!0}){const s=this._components.get(qt);for(const[n,r]of Object.entries(t)){const t=s.list.get(n);if(!t)continue;const o=await t.getItemsData([...r],{relations:{IsDefinedBy:{attributes:!0,relations:!0},IsTypedBy:{attributes:!0,relations:!1},HasPropertySets:{attributes:!0,relations:!0},DefinesOcurrence:{attributes:!1,relations:!1}}});for(const t of o){const s=this.getItemChecks(e,n,t,i.skipIfFails);if(!s)continue;const r=(await this.getPsets(t)).filter(t=>{if(!("value"in t.Name))return!1;return!!this.evalRequirement(t.Name.value,this.propertySet,"PropertySet")&&(s.push({currentValue:t.Name.value,parameter:"PropertySet",pass:!0,requiredValue:this.propertySet}),!0)});if(0!==r.length)for(const t of r){const e=this.getPropertyListName(t);if(!e)continue;const i=t[e];if(!Array.isArray(i)){s.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName});continue}const n=i.filter(t=>{if(!("value"in t._category)||!("value"in t.Name))return!1;if(this._unsupportedTypes.includes(t._category.value))return!1;return!!this.evalRequirement(t.Name.value,this.baseName,"BaseName")&&(s.push({currentValue:t.Name.value,parameter:"BaseName",pass:!0,requiredValue:this.baseName}),!0)});if(0!==n.length)for(const t of n)this.evalValue(t,s),this.evalDataType(t,s),this.evalURI();else s.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName})}else s.push({currentValue:null,parameter:"PropertySet",pass:!1,requiredValue:this.propertySet})}}}getPropertyListName(t){let e;return"value"in t._category?("IFCPROPERTYSET"===t._category.value&&(e="HasProperties"),"IFCELEMENTQUANTITY"===t._category.value&&(e="Quantities"),e):e}getValueKey(t){return Object.keys(t).find(t=>/Value/.test(t)||/Values/.test(t))}getTypePsets(t){if(!Array.isArray(t.IsTypedBy))return[];const[e]=t.IsTypedBy;return e&&Array.isArray(e.HasPropertySets)?e.HasPropertySets:[]}async getPsets(t){const e=this.getTypePsets(t);if(!Array.isArray(t.IsDefinedBy))return e;const i=[];for(const s of t.IsDefinedBy){if(!("value"in s.Name))continue;const t=s.Name.value,n=this.getPropertyListName(s);if(!t||!n)continue;const r=e.find(e=>"value"in e.Name&&e.Name.value===t);if(r&&Array.isArray(r.HasProperties)&&Array.isArray(s.HasProperties))for(const t of r.HasProperties){if(!("value"in t.Name))continue;const e=t.Name.value;s.HasProperties.find(t=>"value"in t.Name&&t.Name.value===e)||s.HasProperties.push(t)}i.push(s)}return i}evalValue(t,e){const i=this.getValueKey(t),s=t[i];if(!("value"in s))return!1;if(this.value){if(!i)return null==e||e.push({parameter:"Value",currentValue:null,pass:!1,requiredValue:this.value}),!1;const t=structuredClone(this.value);"IFCLABEL"===s.type&&"simple"===t.type&&(t.parameter=String(t.parameter));return this.evalRequirement(s.value,t,"Value",e)}return!i||("string"!=typeof s.value||""!==s.value.trim()||(null==e||e.push({parameter:"Value",currentValue:"",pass:!1,requiredValue:this.value}),!1))}evalDataType(t,e){if(!this.dataType)return!0;const i=this.getValueKey(t);if(!i||!("value"in t[i]))return null==e||e.push({parameter:"DataType",currentValue:null,pass:!1,requiredValue:this.dataType}),!1;const s=t[i];return this.evalRequirement(s.type??null,{type:"simple",parameter:this.dataType},"DataType",e)}evalURI(){return!0}}class po extends oo{constructor(){super(...arguments),e(this,"_ifcMaterialEntities",[/^IFCMATERIALLAYERSETUSAGE$/,/^IFCMATERIALCONSTITUENTSET$/,/^IFCMATERIAL$/,/^IFCMATERIALLIST$/]),e(this,"facetType","Material"),e(this,"value"),e(this,"uri")}serialize(t){if(!this.value||!this.uri)return"<material />";const e=ao("Value",this.value);let i="";return"requirement"===t&&(i+=`cardinality="${this.cardinality}"`,i+=this.uri?`uri=${this.uri}`:"",i+=this.instructions?`instructions="${this.instructions}"`:""),`<material ${i}>\n ${e}\n</material>`}async getEntities(t,e){const i=this._components.get(qt);for(const[s,n]of i.list){if(!t.find(t=>t.test(s)))continue;const i=await n.getItemsOfCategories(this._ifcMaterialEntities),r=Object.values(i).flat();if(0===r.length)continue;const o=await n.getItemsData(r,{relations:{AssociatedTo:{attributes:!0,relations:!1},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});for(const t of o){if(!("value"in t._localId&&"value"in t._category&&Array.isArray(t.AssociatedTo)))continue;if(!this.hasValidMaterial(t))continue;const i=t.AssociatedTo.map(t=>"value"in t._localId&&t._localId.value?t._localId.value:null).filter(t=>null!==t);jt.append(e,s,...i)}}}async test(t,e,i={skipIfFails:!0}){const s=this._components.get(qt);for(const[n,r]of Object.entries(t)){const t=s.list.get(n);if(!t)continue;const o=await t.getItemsData([[...r][0]],{relations:{AssociatedTo:{attributes:!1,relations:!1},HasAssociations:{attributes:!0,relations:!0},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});for(const t of o){const s=this.getItemChecks(e,n,t,i.skipIfFails);if(s)if(Array.isArray(t.HasAssociations))for(const e of t.HasAssociations){if(!this._ifcMaterialEntities.some(t=>"value"in e._category&&t.test(e._category.value)))continue;if(this.hasValidMaterial(e,s))break}else s.push({parameter:null,currentValue:null,requiredValue:this.value,pass:!1})}}}hasValidMaterial(t,e){let i=!1;if("value"in t._category&&"IFCMATERIAL"===t._category.value){this.evalValue(t,e)&&(i=!0)}else for(const[s,n]of Object.entries(t))if(["ForLayerSet","MaterialLayers","Material","MaterialConstituents","Materials"].includes(s)&&Array.isArray(n))for(const t of n){if("value"in t._category&&"IFCMATERIAL"===t._category.value){if(this.evalValue(t,e)){i=!0;break}}else{if(this.hasValidMaterial(t)){i=!0;break}}}return i}evalValue(t,e){if(!this.value)return null==e||e.push({parameter:null,currentValue:t.Name&&"value"in t.Name?t.Name.value:null,pass:!0}),!0;if(!("value"in t._category)||"IFCMATERIAL"!==t._category.value)return null;let i=!1;return t.Name&&"value"in t.Name&&(i=this.evalRequirement(t.Name.value,this.value,"Value",e)),i||(t.Category&&"value"in t.Category&&(i=this.evalRequirement(t.Category.value,this.value,"Value",e)),i)}}class fo extends oo{constructor(t,i){super(t),e(this,"facetType","PartOf"),e(this,"_entityFacet"),e(this,"_entity"),e(this,"relation"),e(this,"cardinality","required"),this._entity=i,this._entityFacet=new co(t,i.name),this._entityFacet.predefinedType=i.predefinedType}set entity(t){this._entity=t;const{name:e,predefinedType:i}=t;this._entityFacet=new co(this._components,e),this._entityFacet.predefinedType=i}get entity(){return this._entity}serialize(){return""}async getEntities(t,e){}async test(t){}}class mo{constructor(t,i,s){e(this,"name"),e(this,"ifcVersion",new Set),e(this,"identifier",v.create()),e(this,"description"),e(this,"instructions"),e(this,"requirementsDescription"),e(this,"applicability",new o.DataSet),e(this,"requirements",new o.DataSet),e(this,"components"),this.components=t,this.name=i;for(const t of s)this.ifcVersion.add(t)}set(t){const e=t,i=this;for(const s in t){if("identifier"===s)continue;const t=e[s];s in this&&(i[s]=t)}return this.components.get(Co).list.set(this.identifier,this),this}async test(t,e={skipIfFails:!0}){const i=new o.DataMap;if(0===this.requirements.size)return i;const s={},n=[];for(const e of this.applicability)n.push(e.getEntities(t,s));await Promise.all(n);const r=[];for(const t of this.requirements)r.push(t.test(s,i,e));return await Promise.all(r),i}serialize(){const t=`name="${this.name}"`,e=this.identifier?`identifier="${this.identifier}"`:"",i=this.description?`description="${this.description}"`:"",s=this.instructions?`instructions="${this.instructions}"`:"";return`<specification ifcVersion="${[...this.ifcVersion].join(" ")}" ${t} ${e} ${i} ${s}>\n <applicability minOccurs="1" maxOccurs="unbounded">\n ${[...this.applicability].map(t=>t.serialize("applicability")).join("\n")}\n </applicability>\n <requirements>\n ${[...this.requirements].map(t=>t.serialize("requirement")).join("\n")}\n </requirements>\n </specification>`}}const go=t=>{if(!t)return;const e={};if("simpleValue"in t&&(e.type="simple",e.parameter=t.simpleValue),"restriction"in t){const i=t.restriction,s=Object.keys(i);if("pattern"in i&&(e.type="pattern",e.parameter=i.pattern.value),"enumeration"in i){e.type="enumeration";const t=i.enumeration.map(({value:t})=>i.base.includes("string")?String(t):i.base.includes("integer")||i.base.includes("double")?Number(t):t);e.parameter=t}if(s.some(t=>["minInclusive","minExclusive","maxInclusive","maxExclusive"].includes(t))){e.type="bounds";const t={},n=s.find(t=>t.includes("min")),r=s.find(t=>t.includes("max"));n&&(t.minInclusive="minInclusive"===n,t.min=i[n].value),r&&(t.maxInclusive="maxInclusive"===r,t.max=i[r].value),e.parameter=t}if(s.some(t=>["minLength","length","maxLength"].includes(t))){e.type="length";const t={};void 0!==i.length&&(t.length=i.length.value),void 0!==i.minLength&&(t.min=i.minLength.value),void 0!==i.maxLength&&(t.max=i.maxLength.value),e.parameter=t}}return void 0!==e.parameter?e:void 0},_o=(t,e)=>{const i=[];for(const s of e){const e=s.name,n=go(e);if(!n)continue;const r=new co(t,n);s.cardinality&&(r.cardinality=s.cardinality),r.predefinedType=go(s.predefinedType),r.instructions=s.instructions,i.push(r)}return i},yo=(t,e)=>{const i=[];for(const s of e){const e=s.name,n=go(e);if(!n)continue;const r=new lo(t,n);s.cardinality&&(r.cardinality=s.cardinality),r.value=go(s.value),r.instructions=s.instructions,i.push(r)}return i},wo=(t,e)=>{const i=[];for(const s of e){const e=new po(t);s.cardinality&&(e.cardinality=s.cardinality);const n=go(s.value);"enumeration"===(null==n?void 0:n.type)&&Array.isArray(n.parameter)&&(n.parameter=n.parameter.map(String)),e.value=n,e.uri=s.uri,e.instructions=s.instructions,i.push(e)}return i},vo=(t,e)=>{const i=[];for(const s of e){const e=s.propertySet,n=s.baseName,r=go(e),o=go(n);if(!o||!r)continue;const a=new uo(t,r,o);s.cardinality&&(a.cardinality=s.cardinality);const l=go(s.value);a.value=l,a.dataType=s.dataType,a.uri=s.uri,a.instructions=s.instructions,i.push(a)}return i},bo=(t,e)=>{const i=[];for(const s of e){const e=s.system,n=go(e);if(!n)continue;const r=new ho(t,n);s.cardinality&&(r.cardinality=s.cardinality);const o=go(s.value);"simple"===(null==o?void 0:o.type)&&(o.parameter=String(o.parameter)),"enumeration"===(null==o?void 0:o.type)&&Array.isArray(o.parameter)&&(o.parameter=o.parameter.map(String)),r.value=o,r.uri=s.uri,r.instructions=s.instructions,i.push(r)}return i},xo=(t,e)=>{const i=[];for(const s of e){const e=go(s.entity.name);if(!e)continue;const n=go(s.entity.predefinedType),r=new fo(t,{name:e,predefinedType:n});r.relation=s.relation,s.cardinality&&(r.cardinality=s.cardinality),r.instructions=s.instructions,i.push(r)}return i},To=class t extends d{constructor(s){super(s),e(this,"enabled",!0),e(this,"IDSInfo"),e(this,"list",new i.DataMap),s.add(t.uuid,this)}getModelIdMap(t){const e={},i={};for(const[s,n]of t){const t=[...n].filter(([,t])=>t.pass).map(([t])=>t);jt.append(e,s,...t);const r=[...n].filter(([,t])=>!t.pass).map(([t])=>t);jt.append(i,s,...r)}return{pass:e,fail:i}}create(t,e,i){const s=new mo(this.components,t,e);return i&&(s.identifier=i),this.list.set(s.identifier,s),s}load(e){const i=[],s=t.xmlParser.parse(e).ids,{specifications:n,info:r}=s;if(this.IDSInfo={...r},n&&n.specification){const t=Array.isArray(n.specification)?n.specification:[n.specification];for(const e of t){const{name:t,ifcVersion:s,description:n,instructions:r,identifier:o}=e;if(!t||!s)continue;const a=[],l=[],{applicability:h,requirements:c}=e;if(h){const{maxOccurs:t,...e}=h,i=Array.isArray(e)?e:[e];for(const t of i)for(const e in t){const i=Array.isArray(t[e])?t[e]:[t[e]];if("entity"===e){const t=_o(this.components,i);a.push(...t)}if("attribute"===e){const t=yo(this.components,i);a.push(...t)}if("material"===e){const t=wo(this.components,i);a.push(...t)}if("classification"===e){const t=bo(this.components,i);a.push(...t)}if("property"===e){const t=vo(this.components,i);a.push(...t)}if("partOf"===e){const t=xo(this.components,i);a.push(...t)}}}let d;if(c){const{maxOccurs:t,...e}=c;d=c.description;const i=Array.isArray(e)?e:[e];for(const t of i)for(const e in t){const i=Array.isArray(t[e])?t[e]:[t[e]];if("entity"===e){const t=_o(this.components,i);l.push(...t)}if("attribute"===e){const t=yo(this.components,i);l.push(...t)}if("material"===e){const t=wo(this.components,i);l.push(...t)}if("classification"===e){const t=bo(this.components,i);l.push(...t)}if("property"===e){const t=vo(this.components,i);l.push(...t)}if("partOf"===e){const t=xo(this.components,i);l.push(...t)}}}const u=this.create(t,s.split(/\s+/),o);u.description=n,u.instructions=r,u.requirementsDescription=d,u.applicability.add(...a),u.requirements.add(...l),i.push(u)}}return i}export(t,e=this.list.values()){const i=e??this.list;return`<ids xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://standards.buildingsmart.org/IDS http://standards.buildingsmart.org/IDS/1.0/ids.xsd" xmlns:ids="http://standards.buildingsmart.org/IDS">\n \x3c!-- Made with That Open Engine ${Kn.release} (https://github.com/thatopen/engine_components) --\x3e\n <info>\n <title>${t.title}</title>\n ${t.copyright?`<copyright>${t.copyright}</copyright>`:""}\n ${t.version?`<version>${t.version}</version>`:""}\n ${t.description?`<description>${t.description}</description>`:""}\n ${t.author?`<author>${t.author}</author>`:""}\n ${t.date?`<date>${t.date.toISOString().split("T")[0]}</date>`:""}\n ${t.purpose?`<purpose>${t.purpose}</purpose>`:""}\n ${t.milestone?`<milestone>${t.milestone}</milestone>`:""}\n </info>\n <specifications>\n ${[...i].map(t=>t.serialize()).join("\n")}\n </specifications>\n</ids>`}};e(To,"uuid","9f0b9f78-9b2e-481a-b766-2fbfd01f342c"),e(To,"xmlParser",new Ft.XMLParser({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0}));let Co=To;const Eo=class t extends d{constructor(i){super(i),e(this,"enabled",!0),i.add(t.uuid,this)}static distanceFromPointToLine(t,e,i,s=!1){const n=new a.Line3,r=new a.Vector3;return n.set(e,i),n.closestPointToPoint(t,s,r),r.distanceTo(t)}round(t){const e=1e3;t.x=Math.trunc(t.x*e)/e,t.y=Math.trunc(t.y*e)/e,t.z=Math.trunc(t.z*e)/e}async getVolumeFromFragments(t){return console.warn("getVolumeFromFragments is deprecated. Use getItemsVolume instead."),this.getItemsVolume(t)}async getItemsVolume(t){let e=0;const i=this.components.get(qt);for(const[s,n]of Object.entries(t)){const t=i.list.get(s);t&&(e+=await t.getItemsVolume([...n]))}return e}static convertUnits(t,e,i,s=2){const n={m:1,cm:.01,mm:.001,km:1e3,m2:1,cm2:1e-4,mm2:1e-6,km2:1e6,m3:1,cm3:1e-6,mm3:1e-9,km3:1e9};if(!n[e]||!n[i])throw new Error("Invalid units provided for conversion.");if(!Number.isInteger(s)||s<0||s>5)throw new Error("Precision must be an integer between 0 and 5.");const r=t*(n[e]/n[i]),o=10**s;return Math.round(r*o)/o}};e(Eo,"uuid","267ca032-672f-4cb0-afa9-d24e904f39d6");let So=Eo;exports.AsyncEvent=class{constructor(){e(this,"enabled",!0),e(this,"trigger",async t=>{if(!this.enabled)return;const e=this.handlers.slice(0);for(const i of e)await i(t)}),e(this,"handlers",[])}add(t){this.handlers.push(t)}remove(t){this.handlers=this.handlers.filter(e=>e!==t)}reset(){this.handlers.length=0}},exports.BCFTopics=pr,exports.BCFTopicsConfigManager=dr,exports.Base=c,exports.BaseCamera=p,exports.BaseRenderer=f,exports.BaseScene=_,exports.BaseWorldItem=u,exports.BoundingBoxer=se,exports.Classifier=le,exports.Clipper=qr,exports.Comment=ar,exports.Component=d,exports.Components=Kn,exports.ConfigManager=Yt,exports.Configurator=$t,exports.ControlsUtils=Zt,exports.DataMap=Ht,exports.DataSet=y,exports.Disposer=g,exports.Event=h,exports.EventManager=class{constructor(){e(this,"list",new Set)}add(t){for(const e of t)this.list.add(e)}remove(t){for(const e of t)this.list.delete(e)}set(t){for(const e of this.list)e.enabled=t}reset(){for(const t of this.list)t.reset()}},exports.FastModelPicker=he,exports.FastModelPickers=de,exports.FinderQuery=ne,exports.FirstPersonMode=Jn,exports.FragmentsManager=qt,exports.Grids=Ti,exports.Hider=ee,exports.IDSAttribute=lo,exports.IDSClassification=ho,exports.IDSEntity=co,exports.IDSFacet=oo,exports.IDSMaterial=po,exports.IDSPartOf=fo,exports.IDSProperty=uo,exports.IDSSpecification=mo,exports.IDSSpecifications=Co,exports.IfcFragmentSettings=Qt,exports.IfcLoader=Jt,exports.ItemsFinder=oe,exports.MeasurementUtils=So,exports.ModelIdMapUtils=jt,exports.Mouse=Gt,exports.OrbitMode=tr,exports.OrthoPerspectiveCamera=sr,exports.PlanMode=er,exports.ProjectionManager=ir,exports.Raycasters=fe,exports.RendererMode=ve,exports.ShadowedScene=class extends we{constructor(){super(...arguments),e(this,"_distanceRenderer"),e(this,"autoBias",!0),e(this,"_defaultShadowConfig",{cascade:1,resolution:512}),e(this,"_lightsWithShadow",new Map),e(this,"_isComputingShadows",!1),e(this,"_shadowsEnabled",!0),e(this,"_bias",0),e(this,"recomputeShadows",t=>{if(!this._shadowsEnabled)return;this.autoBias&&(this.bias=-.005);if(t*=1.5,!this.currentWorld)throw new Error("A world needs to be assigned to the scene before computing shadows!");if(!this._lightsWithShadow.size)throw new Error("No shadows found!");const e=this.currentWorld.camera.three;if(!(e instanceof a.PerspectiveCamera||e instanceof a.OrthographicCamera))throw new Error("Invalid camera type!");const i=new a.Vector3;e.getWorldDirection(i);let s=t;const n=new a.Vector3;n.copy(this.config.directionalLight.position),n.normalize();for(const[t,r]of this._lightsWithShadow){const o=this.directionalLights.get(r);if(!o)throw new Error("Light not found.");const l=new a.Vector3;l.copy(i);const h=t===this._lightsWithShadow.size-1,c=h?s/2:2*s/3;l.multiplyScalar(c),l.add(e.position);const d=s-c,u=new a.Vector3;u.copy(n),u.multiplyScalar(d),o.target.position.copy(l),o.position.copy(l),o.position.add(u),o.shadow.camera.right=d,o.shadow.camera.left=-d,o.shadow.camera.top=d,o.shadow.camera.bottom=-d,o.shadow.camera.far=2*d,o.shadow.camera.updateProjectionMatrix(),o.shadow.camera.updateMatrix(),h||(s/=3)}this._isComputingShadows=!1})}get bias(){return this._bias}set bias(t){this._bias=t;for(const[,e]of this._lightsWithShadow){const i=this.directionalLights.get(e);i&&(i.shadow.bias=t)}}get shadowsEnabled(){return this._shadowsEnabled}set shadowsEnabled(t){this._shadowsEnabled=t;for(const[,e]of this.directionalLights)e.castShadow=t}get distanceRenderer(){if(!this._distanceRenderer)throw new Error("You must set up this component before accessing the distance renderer!");return this._distanceRenderer}setup(t){super.setup(t);const e={...this._defaultConfig,...this._defaultShadowConfig,...t};if(e.cascade<=0)throw new Error("Config.shadows.cascade must be a natural number greater than 0!");if(e.cascade>1)throw new Error("Multiple shadows not supported yet!");if(!this.currentWorld)throw new Error("A world needs to be assigned to the scene before setting it up!");for(const[,t]of this.directionalLights)t.target.removeFromParent(),t.removeFromParent(),t.dispose();this.directionalLights.clear(),this._distanceRenderer||(this._distanceRenderer=new ro(this.components,this.currentWorld),this._distanceRenderer.onDistanceComputed.add(this.recomputeShadows)),this._lightsWithShadow.clear();for(let t=0;t<e.cascade;t++){const i=new a.DirectionalLight;i.intensity=this.config.directionalLight.intensity,i.color=this.config.directionalLight.color,i.position.copy(this.config.directionalLight.position),i.shadow.mapSize.width=e.resolution,i.shadow.mapSize.height=e.resolution,this.three.add(i,i.target),this.directionalLights.set(i.uuid,i),this._lightsWithShadow.set(t,i.uuid),i.castShadow=!0,i.shadow.bias=this._bias}}dispose(){super.dispose(),this._distanceRenderer&&this._distanceRenderer.dispose(),this._lightsWithShadow.clear()}async updateShadows(){!this._isComputingShadows&&this._shadowsEnabled&&(this._isComputingShadows=!0,await this.distanceRenderer.compute())}},exports.SimpleCamera=_i,exports.SimpleGrid=bi,exports.SimpleGridConfigManager=vi,exports.SimplePlane=Yr,exports.SimpleRaycaster=ue,exports.SimpleRenderer=class extends f{constructor(t,i,s){super(t),e(this,"enabled",!0),e(this,"container"),e(this,"three"),e(this,"mode",1),e(this,"needsUpdate",!1),e(this,"_canvas"),e(this,"_parameters"),e(this,"_resizeObserver",null),e(this,"onContainerUpdated",new h),e(this,"_resizing",!1),e(this,"resize",t=>{if(this._resizing)return;this._resizing=!0,this.onContainerUpdated.trigger();const e=t?t.x:this.container.clientWidth,i=t?t.y:this.container.clientHeight;this.three.setSize(e,i),this.onResize.trigger(new a.Vector2(e,i)),this._resizing=!1}),e(this,"resizeEvent",()=>{this.resize()}),e(this,"onContextLost",t=>{t.preventDefault(),this.enabled=!1}),e(this,"onContextBack",()=>{this.three.setRenderTarget(null),this.three.dispose(),this.three=new a.WebGLRenderer({canvas:this._canvas,antialias:!0,alpha:!0,...this._parameters}),this.enabled=!0}),this.container=i,this._parameters=s,this.three=new a.WebGLRenderer({antialias:!0,alpha:!0,...s}),this.three.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.setupRenderer(),this.setupEvents(!0),this.resize(),this._canvas=this.three.domElement;const n=this.three.getContext(),{canvas:r}=n;r.addEventListener("webglcontextlost",this.onContextLost,!1),r.addEventListener("webglcontextrestored",this.onContextBack,!1)}update(){if(!this.enabled||!this.currentWorld)return;if(0===this.mode&&!this.needsUpdate)return;this.needsUpdate=!1,this.onBeforeUpdate.trigger(this);const t=this.currentWorld.scene.three,e=this.currentWorld.camera.three;this.three.render(t,e),this.onAfterUpdate.trigger(this)}dispose(){this.enabled=!1,this.setupEvents(!1),this.three.domElement.remove(),this.three.forceContextLoss(),this.three.dispose(),this.onResize.reset(),this.onAfterUpdate.reset(),this.onBeforeUpdate.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}getSize(){return new a.Vector2(this.three.domElement.clientWidth,this.three.domElement.clientHeight)}setupEvents(t){const e=this.three.domElement.parentElement;if(!e)throw new Error("This renderer needs to have an HTML container!");this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),window.removeEventListener("resize",this.resizeEvent),t&&(this._resizeObserver=new ResizeObserver(this.resizeEvent),this._resizeObserver.observe(e),window.addEventListener("resize",this.resizeEvent))}setupRenderer(){this.three.localClippingEnabled=!0,this.container&&this.container.appendChild(this.three.domElement),this.onContainerUpdated.trigger()}},exports.SimpleScene=we,exports.SimpleSceneConfigManager=ye,exports.SimpleWorld=me,exports.Topic=hr,exports.UUID=v,exports.VertexPicker=class extends d{constructor(t,i){super(t),e(this,"onDisposed",new h),e(this,"onVertexFound",new h),e(this,"onVertexLost",new h),e(this,"onEnabled",new h),e(this,"components"),e(this,"workingPlane",null),e(this,"_pickedPoint",null),e(this,"_config"),e(this,"_enabled",!1),this.components=t,this.config={snapDistance:.25,showOnlyVertex:!1,...i},this.enabled=!1}set enabled(t){this._enabled=t,t||(this._pickedPoint=null),this.onEnabled.trigger(t)}get enabled(){return this._enabled}set config(t){this._config={...this._config,...t}}get config(){return this._config}dispose(){this.onVertexFound.reset(),this.onVertexLost.reset(),this.components=null,this.onDisposed.trigger(),this.onDisposed.reset()}async get(t){if(!this.enabled)return this._pickedPoint;const e=this.components.get(fe).get(t),i=await e.castRay();if(!i)return null!==this._pickedPoint&&(this.onVertexLost.trigger(),this._pickedPoint=null),this._pickedPoint;const s=i.point;return null!==this._pickedPoint&&this._pickedPoint.equals(s)||(this._pickedPoint=s.clone(),this.onVertexFound.trigger(this._pickedPoint)),this._pickedPoint}},exports.View=eo,exports.Viewpoint=Qr,exports.Viewpoints=to,exports.Views=so,exports.Worlds=wi,exports.XML=Vt,exports.extensionsImporter=cr;
27
+ */const OO=DO(FO.exports=function e(t,s,i){function r(o,a){if(!s[o]){if(!t[o]){if(!a&&LO)return LO(o);if(n)return n(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var h=s[o]={exports:{}};t[o][0].call(h.exports,function(e){return r(t[o][1][e]||e)},h,h.exports,e,t,s,i)}return s[o].exports}for(var n=LO,o=0;o<i.length;o++)r(i[o]);return r}({1:[function(e,t,s){var i=e("./utils"),r=e("./support"),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";s.encode=function(e){for(var t,s,r,o,a,l,h,u=[],c=0,d=e.length,p=d,m="string"!==i.getTypeOf(e);c<e.length;)p=d-c,r=m?(t=e[c++],s=c<d?e[c++]:0,c<d?e[c++]:0):(t=e.charCodeAt(c++),s=c<d?e.charCodeAt(c++):0,c<d?e.charCodeAt(c++):0),o=t>>2,a=(3&t)<<4|s>>4,l=1<p?(15&s)<<2|r>>6:64,h=2<p?63&r:64,u.push(n.charAt(o)+n.charAt(a)+n.charAt(l)+n.charAt(h));return u.join("")},s.decode=function(e){var t,s,i,o,a,l,h=0,u=0,c="data:";if(e.substr(0,c.length)===c)throw new Error("Invalid base64 input, it looks like a data url.");var d,p=3*(e=e.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(e.charAt(e.length-1)===n.charAt(64)&&p--,e.charAt(e.length-2)===n.charAt(64)&&p--,p%1!=0)throw new Error("Invalid base64 input, bad content length.");for(d=r.uint8array?new Uint8Array(0|p):new Array(0|p);h<e.length;)t=n.indexOf(e.charAt(h++))<<2|(o=n.indexOf(e.charAt(h++)))>>4,s=(15&o)<<4|(a=n.indexOf(e.charAt(h++)))>>2,i=(3&a)<<6|(l=n.indexOf(e.charAt(h++))),d[u++]=t,64!==a&&(d[u++]=s),64!==l&&(d[u++]=i);return d}},{"./support":30,"./utils":32}],2:[function(e,t,s){var i=e("./external"),r=e("./stream/DataWorker"),n=e("./stream/Crc32Probe"),o=e("./stream/DataLengthProbe");function a(e,t,s,i,r){this.compressedSize=e,this.uncompressedSize=t,this.crc32=s,this.compression=i,this.compressedContent=r}a.prototype={getContentWorker:function(){var e=new r(i.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new o("data_length")),t=this;return e.on("end",function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),e},getCompressedWorker:function(){return new r(i.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},a.createWorkerFrom=function(e,t,s){return e.pipe(new n).pipe(new o("uncompressedSize")).pipe(t.compressWorker(s)).pipe(new o("compressedSize")).withStreamInfo("compression",t)},t.exports=a},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,t,s){var i=e("./stream/GenericWorker");s.STORE={magic:"\0\0",compressWorker:function(){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},s.DEFLATE=e("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,t,s){var i=e("./utils"),r=function(){for(var e,t=[],s=0;s<256;s++){e=s;for(var i=0;i<8;i++)e=1&e?3988292384^e>>>1:e>>>1;t[s]=e}return t}();t.exports=function(e,t){return void 0!==e&&e.length?"string"!==i.getTypeOf(e)?function(e,t,s,i){var n=r,o=i+s;e^=-1;for(var a=i;a<o;a++)e=e>>>8^n[255&(e^t[a])];return-1^e}(0|t,e,e.length,0):function(e,t,s,i){var n=r,o=i+s;e^=-1;for(var a=i;a<o;a++)e=e>>>8^n[255&(e^t.charCodeAt(a))];return-1^e}(0|t,e,e.length,0):0}},{"./utils":32}],5:[function(e,t,s){s.base64=!1,s.binary=!1,s.dir=!1,s.createFolders=!0,s.date=null,s.compression=null,s.compressionOptions=null,s.comment=null,s.unixPermissions=null,s.dosPermissions=null},{}],6:[function(e,t,s){var i=null;i="undefined"!=typeof Promise?Promise:e("lie"),t.exports={Promise:i}},{lie:37}],7:[function(e,t,s){var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,r=e("pako"),n=e("./utils"),o=e("./stream/GenericWorker"),a=i?"uint8array":"array";function l(e,t){o.call(this,"FlateWorker/"+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={}}s.magic="\b\0",n.inherits(l,o),l.prototype.processChunk=function(e){this.meta=e.meta,null===this._pako&&this._createPako(),this._pako.push(n.transformTo(a,e.data),!1)},l.prototype.flush=function(){o.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},l.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this._pako=null},l.prototype._createPako=function(){this._pako=new r[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var e=this;this._pako.onData=function(t){e.push({data:t,meta:e.meta})}},s.compressWorker=function(e){return new l("Deflate",e)},s.uncompressWorker=function(){return new l("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(e,t,s){function i(e,t){var s,i="";for(s=0;s<t;s++)i+=String.fromCharCode(255&e),e>>>=8;return i}function r(e,t,s,r,o,u){var c,d,p=e.file,m=e.compression,f=u!==a.utf8encode,g=n.transformTo("string",u(p.name)),y=n.transformTo("string",a.utf8encode(p.name)),x=p.comment,b=n.transformTo("string",u(x)),_=n.transformTo("string",a.utf8encode(x)),w=y.length!==p.name.length,v=_.length!==x.length,T="",S="",M="",A=p.dir,N=p.date,E={crc32:0,compressedSize:0,uncompressedSize:0};t&&!s||(E.crc32=e.crc32,E.compressedSize=e.compressedSize,E.uncompressedSize=e.uncompressedSize);var C=0;t&&(C|=8),f||!w&&!v||(C|=2048);var R,P,B,I=0,D=0;A&&(I|=16),"UNIX"===o?(D=798,I|=(R=p.unixPermissions,P=A,B=R,R||(B=P?16893:33204),(65535&B)<<16)):(D=20,I|=function(e){return 63&(e||0)}(p.dosPermissions)),c=N.getUTCHours(),c<<=6,c|=N.getUTCMinutes(),c<<=5,c|=N.getUTCSeconds()/2,d=N.getUTCFullYear()-1980,d<<=4,d|=N.getUTCMonth()+1,d<<=5,d|=N.getUTCDate(),w&&(S=i(1,1)+i(l(g),4)+y,T+="up"+i(S.length,2)+S),v&&(M=i(1,1)+i(l(b),4)+_,T+="uc"+i(M.length,2)+M);var L="";return L+="\n\0",L+=i(C,2),L+=m.magic,L+=i(c,2),L+=i(d,2),L+=i(E.crc32,4),L+=i(E.compressedSize,4),L+=i(E.uncompressedSize,4),L+=i(g.length,2),L+=i(T.length,2),{fileRecord:h.LOCAL_FILE_HEADER+L+g+T,dirRecord:h.CENTRAL_FILE_HEADER+i(D,2)+L+i(b.length,2)+"\0\0\0\0"+i(I,4)+i(r,4)+g+T+b}}var n=e("../utils"),o=e("../stream/GenericWorker"),a=e("../utf8"),l=e("../crc32"),h=e("../signature");function u(e,t,s,i){o.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=t,this.zipPlatform=s,this.encodeFileName=i,this.streamFiles=e,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}n.inherits(u,o),u.prototype.push=function(e){var t=e.meta.percent||0,s=this.entriesCount,i=this._sources.length;this.accumulate?this.contentBuffer.push(e):(this.bytesWritten+=e.data.length,o.prototype.push.call(this,{data:e.data,meta:{currentFile:this.currentFile,percent:s?(t+100*(s-i-1))/s:100}}))},u.prototype.openedSource=function(e){this.currentSourceOffset=this.bytesWritten,this.currentFile=e.file.name;var t=this.streamFiles&&!e.file.dir;if(t){var s=r(e,t,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:s.fileRecord,meta:{percent:0}})}else this.accumulate=!0},u.prototype.closedSource=function(e){this.accumulate=!1;var t,s=this.streamFiles&&!e.file.dir,n=r(e,s,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(n.dirRecord),s)this.push({data:(t=e,h.DATA_DESCRIPTOR+i(t.crc32,4)+i(t.compressedSize,4)+i(t.uncompressedSize,4)),meta:{percent:100}});else for(this.push({data:n.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},u.prototype.flush=function(){for(var e=this.bytesWritten,t=0;t<this.dirRecords.length;t++)this.push({data:this.dirRecords[t],meta:{percent:100}});var s,r,o,a,l,u,c=this.bytesWritten-e,d=(s=this.dirRecords.length,r=c,o=e,a=this.zipComment,l=this.encodeFileName,u=n.transformTo("string",l(a)),h.CENTRAL_DIRECTORY_END+"\0\0\0\0"+i(s,2)+i(s,2)+i(r,4)+i(o,4)+i(u.length,2)+u);this.push({data:d,meta:{percent:100}})},u.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},u.prototype.registerPrevious=function(e){this._sources.push(e);var t=this;return e.on("data",function(e){t.processChunk(e)}),e.on("end",function(){t.closedSource(t.previous.streamInfo),t._sources.length?t.prepareNextSource():t.end()}),e.on("error",function(e){t.error(e)}),this},u.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},u.prototype.error=function(e){var t=this._sources;if(!o.prototype.error.call(this,e))return!1;for(var s=0;s<t.length;s++)try{t[s].error(e)}catch(e){}return!0},u.prototype.lock=function(){o.prototype.lock.call(this);for(var e=this._sources,t=0;t<e.length;t++)e[t].lock()},t.exports=u},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(e,t,s){var i=e("../compressions"),r=e("./ZipFileWorker");s.generateWorker=function(e,t,s){var n=new r(t.streamFiles,s,t.platform,t.encodeFileName),o=0;try{e.forEach(function(e,s){o++;var r=function(e,t){var s=e||t,r=i[s];if(!r)throw new Error(s+" is not a valid compression method !");return r}(s.options.compression,t.compression),a=s.options.compressionOptions||t.compressionOptions||{},l=s.dir,h=s.date;s._compressWorker(r,a).withStreamInfo("file",{name:e,dir:l,date:h,comment:s.comment||"",unixPermissions:s.unixPermissions,dosPermissions:s.dosPermissions}).pipe(n)}),n.entriesCount=o}catch(e){n.error(e)}return n}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(e,t,s){function i(){if(!(this instanceof i))return new i;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var e=new i;for(var t in this)"function"!=typeof this[t]&&(e[t]=this[t]);return e}}(i.prototype=e("./object")).loadAsync=e("./load"),i.support=e("./support"),i.defaults=e("./defaults"),i.version="3.10.1",i.loadAsync=function(e,t){return(new i).loadAsync(e,t)},i.external=e("./external"),t.exports=i},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(e,t,s){var i=e("./utils"),r=e("./external"),n=e("./utf8"),o=e("./zipEntries"),a=e("./stream/Crc32Probe"),l=e("./nodejsUtils");function h(e){return new r.Promise(function(t,s){var i=e.decompressed.getContentWorker().pipe(new a);i.on("error",function(e){s(e)}).on("end",function(){i.streamInfo.crc32!==e.decompressed.crc32?s(new Error("Corrupted zip : CRC32 mismatch")):t()}).resume()})}t.exports=function(e,t){var s=this;return t=i.extend(t||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:n.utf8decode}),l.isNode&&l.isStream(e)?r.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):i.prepareContent("the loaded zip file",e,!0,t.optimizedBinaryString,t.base64).then(function(e){var s=new o(t);return s.load(e),s}).then(function(e){var s=[r.Promise.resolve(e)],i=e.files;if(t.checkCRC32)for(var n=0;n<i.length;n++)s.push(h(i[n]));return r.Promise.all(s)}).then(function(e){for(var r=e.shift(),n=r.files,o=0;o<n.length;o++){var a=n[o],l=a.fileNameStr,h=i.resolve(a.fileNameStr);s.file(h,a.decompressed,{binary:!0,optimizedBinaryString:!0,date:a.date,dir:a.dir,comment:a.fileCommentStr.length?a.fileCommentStr:null,unixPermissions:a.unixPermissions,dosPermissions:a.dosPermissions,createFolders:t.createFolders}),a.dir||(s.file(h).unsafeOriginalName=l)}return r.zipComment.length&&(s.comment=r.zipComment),s})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(e,t,s){var i=e("../utils"),r=e("../stream/GenericWorker");function n(e,t){r.call(this,"Nodejs stream input adapter for "+e),this._upstreamEnded=!1,this._bindStream(t)}i.inherits(n,r),n.prototype._bindStream=function(e){var t=this;(this._stream=e).pause(),e.on("data",function(e){t.push({data:e,meta:{percent:0}})}).on("error",function(e){t.isPaused?this.generatedError=e:t.error(e)}).on("end",function(){t.isPaused?t._upstreamEnded=!0:t.end()})},n.prototype.pause=function(){return!!r.prototype.pause.call(this)&&(this._stream.pause(),!0)},n.prototype.resume=function(){return!!r.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},t.exports=n},{"../stream/GenericWorker":28,"../utils":32}],13:[function(e,t,s){var i=e("readable-stream").Readable;function r(e,t,s){i.call(this,t),this._helper=e;var r=this;e.on("data",function(e,t){r.push(e)||r._helper.pause(),s&&s(t)}).on("error",function(e){r.emit("error",e)}).on("end",function(){r.push(null)})}e("../utils").inherits(r,i),r.prototype._read=function(){this._helper.resume()},t.exports=r},{"../utils":32,"readable-stream":16}],14:[function(e,t,s){t.exports={isNode:"undefined"!=typeof Buffer,newBufferFrom:function(e,t){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(e,t);if("number"==typeof e)throw new Error('The "data" argument must not be a number');return new Buffer(e,t)},allocBuffer:function(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t},isBuffer:function(e){return Buffer.isBuffer(e)},isStream:function(e){return e&&"function"==typeof e.on&&"function"==typeof e.pause&&"function"==typeof e.resume}}},{}],15:[function(e,t,s){function i(e,t,s){var i,r=n.getTypeOf(t),a=n.extend(s||{},l);a.date=a.date||new Date,null!==a.compression&&(a.compression=a.compression.toUpperCase()),"string"==typeof a.unixPermissions&&(a.unixPermissions=parseInt(a.unixPermissions,8)),a.unixPermissions&&16384&a.unixPermissions&&(a.dir=!0),a.dosPermissions&&16&a.dosPermissions&&(a.dir=!0),a.dir&&(e=f(e)),a.createFolders&&(i=m(e))&&g.call(this,i,!0);var c="string"===r&&!1===a.binary&&!1===a.base64;s&&void 0!==s.binary||(a.binary=!c),(t instanceof h&&0===t.uncompressedSize||a.dir||!t||0===t.length)&&(a.base64=!1,a.binary=!0,t="",a.compression="STORE",r="string");var y=null;y=t instanceof h||t instanceof o?t:d.isNode&&d.isStream(t)?new p(e,t):n.prepareContent(e,t,a.binary,a.optimizedBinaryString,a.base64);var x=new u(e,y,a);this.files[e]=x}var r=e("./utf8"),n=e("./utils"),o=e("./stream/GenericWorker"),a=e("./stream/StreamHelper"),l=e("./defaults"),h=e("./compressedObject"),u=e("./zipObject"),c=e("./generate"),d=e("./nodejsUtils"),p=e("./nodejs/NodejsStreamInputAdapter"),m=function(e){"/"===e.slice(-1)&&(e=e.substring(0,e.length-1));var t=e.lastIndexOf("/");return 0<t?e.substring(0,t):""},f=function(e){return"/"!==e.slice(-1)&&(e+="/"),e},g=function(e,t){return t=void 0!==t?t:l.createFolders,e=f(e),this.files[e]||i.call(this,e,null,{dir:!0,createFolders:t}),this.files[e]};function y(e){return"[object RegExp]"===Object.prototype.toString.call(e)}var x={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(e){var t,s,i;for(t in this.files)i=this.files[t],(s=t.slice(this.root.length,t.length))&&t.slice(0,this.root.length)===this.root&&e(s,i)},filter:function(e){var t=[];return this.forEach(function(s,i){e(s,i)&&t.push(i)}),t},file:function(e,t,s){if(1!==arguments.length)return e=this.root+e,i.call(this,e,t,s),this;if(y(e)){var r=e;return this.filter(function(e,t){return!t.dir&&r.test(e)})}var n=this.files[this.root+e];return n&&!n.dir?n:null},folder:function(e){if(!e)return this;if(y(e))return this.filter(function(t,s){return s.dir&&e.test(t)});var t=this.root+e,s=g.call(this,t),i=this.clone();return i.root=s.name,i},remove:function(e){e=this.root+e;var t=this.files[e];if(t||("/"!==e.slice(-1)&&(e+="/"),t=this.files[e]),t&&!t.dir)delete this.files[e];else for(var s=this.filter(function(t,s){return s.name.slice(0,e.length)===e}),i=0;i<s.length;i++)delete this.files[s[i].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(e){var t,s={};try{if((s=n.extend(e||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:r.utf8encode})).type=s.type.toLowerCase(),s.compression=s.compression.toUpperCase(),"binarystring"===s.type&&(s.type="string"),!s.type)throw new Error("No output type specified.");n.checkSupport(s.type),"darwin"!==s.platform&&"freebsd"!==s.platform&&"linux"!==s.platform&&"sunos"!==s.platform||(s.platform="UNIX"),"win32"===s.platform&&(s.platform="DOS");var i=s.comment||this.comment||"";t=c.generateWorker(this,s,i)}catch(e){(t=new o("error")).error(e)}return new a(t,s.type||"string",s.mimeType)},generateAsync:function(e,t){return this.generateInternalStream(e).accumulate(t)},generateNodeStream:function(e,t){return(e=e||{}).type||(e.type="nodebuffer"),this.generateInternalStream(e).toNodejsStream(t)}};t.exports=x},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(e,t,s){t.exports=e("stream")},{stream:void 0}],17:[function(e,t,s){var i=e("./DataReader");function r(e){i.call(this,e);for(var t=0;t<this.data.length;t++)e[t]=255&e[t]}e("../utils").inherits(r,i),r.prototype.byteAt=function(e){return this.data[this.zero+e]},r.prototype.lastIndexOfSignature=function(e){for(var t=e.charCodeAt(0),s=e.charCodeAt(1),i=e.charCodeAt(2),r=e.charCodeAt(3),n=this.length-4;0<=n;--n)if(this.data[n]===t&&this.data[n+1]===s&&this.data[n+2]===i&&this.data[n+3]===r)return n-this.zero;return-1},r.prototype.readAndCheckSignature=function(e){var t=e.charCodeAt(0),s=e.charCodeAt(1),i=e.charCodeAt(2),r=e.charCodeAt(3),n=this.readData(4);return t===n[0]&&s===n[1]&&i===n[2]&&r===n[3]},r.prototype.readData=function(e){if(this.checkOffset(e),0===e)return[];var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=r},{"../utils":32,"./DataReader":18}],18:[function(e,t,s){var i=e("../utils");function r(e){this.data=e,this.length=e.length,this.index=0,this.zero=0}r.prototype={checkOffset:function(e){this.checkIndex(this.index+e)},checkIndex:function(e){if(this.length<this.zero+e||e<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+e+"). Corrupted zip ?")},setIndex:function(e){this.checkIndex(e),this.index=e},skip:function(e){this.setIndex(this.index+e)},byteAt:function(){},readInt:function(e){var t,s=0;for(this.checkOffset(e),t=this.index+e-1;t>=this.index;t--)s=(s<<8)+this.byteAt(t);return this.index+=e,s},readString:function(e){return i.transformTo("string",this.readData(e))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC(1980+(e>>25&127),(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(31&e)<<1))}},t.exports=r},{"../utils":32}],19:[function(e,t,s){var i=e("./Uint8ArrayReader");function r(e){i.call(this,e)}e("../utils").inherits(r,i),r.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=r},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(e,t,s){var i=e("./DataReader");function r(e){i.call(this,e)}e("../utils").inherits(r,i),r.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)},r.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero},r.prototype.readAndCheckSignature=function(e){return e===this.readData(4)},r.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=r},{"../utils":32,"./DataReader":18}],21:[function(e,t,s){var i=e("./ArrayReader");function r(e){i.call(this,e)}e("../utils").inherits(r,i),r.prototype.readData=function(e){if(this.checkOffset(e),0===e)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=r},{"../utils":32,"./ArrayReader":17}],22:[function(e,t,s){var i=e("../utils"),r=e("../support"),n=e("./ArrayReader"),o=e("./StringReader"),a=e("./NodeBufferReader"),l=e("./Uint8ArrayReader");t.exports=function(e){var t=i.getTypeOf(e);return i.checkSupport(t),"string"!==t||r.uint8array?"nodebuffer"===t?new a(e):r.uint8array?new l(i.transformTo("uint8array",e)):new n(i.transformTo("array",e)):new o(e)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(e,t,s){s.LOCAL_FILE_HEADER="PK",s.CENTRAL_FILE_HEADER="PK",s.CENTRAL_DIRECTORY_END="PK",s.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",s.ZIP64_CENTRAL_DIRECTORY_END="PK",s.DATA_DESCRIPTOR="PK\b"},{}],24:[function(e,t,s){var i=e("./GenericWorker"),r=e("../utils");function n(e){i.call(this,"ConvertWorker to "+e),this.destType=e}r.inherits(n,i),n.prototype.processChunk=function(e){this.push({data:r.transformTo(this.destType,e.data),meta:e.meta})},t.exports=n},{"../utils":32,"./GenericWorker":28}],25:[function(e,t,s){var i=e("./GenericWorker"),r=e("../crc32");function n(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}e("../utils").inherits(n,i),n.prototype.processChunk=function(e){this.streamInfo.crc32=r(e.data,this.streamInfo.crc32||0),this.push(e)},t.exports=n},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(e,t,s){var i=e("../utils"),r=e("./GenericWorker");function n(e){r.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0)}i.inherits(n,r),n.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length}r.prototype.processChunk.call(this,e)},t.exports=n},{"../utils":32,"./GenericWorker":28}],27:[function(e,t,s){var i=e("../utils"),r=e("./GenericWorker");function n(e){r.call(this,"DataWorker");var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,e.then(function(e){t.dataIsReady=!0,t.data=e,t.max=e&&e.length||0,t.type=i.getTypeOf(e),t.isPaused||t._tickAndRepeat()},function(e){t.error(e)})}i.inherits(n,r),n.prototype.cleanUp=function(){r.prototype.cleanUp.call(this),this.data=null},n.prototype.resume=function(){return!!r.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,i.delay(this._tickAndRepeat,[],this)),!0)},n.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(i.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},n.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var e=null,t=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":e=this.data.substring(this.index,t);break;case"uint8array":e=this.data.subarray(this.index,t);break;case"array":case"nodebuffer":e=this.data.slice(this.index,t)}return this.index=t,this.push({data:e,meta:{percent:this.max?this.index/this.max*100:0}})},t.exports=n},{"../utils":32,"./GenericWorker":28}],28:[function(e,t,s){function i(e){this.name=e||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}i.prototype={push:function(e){this.emit("data",e)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(e){this.emit("error",e)}return!0},error:function(e){return!this.isFinished&&(this.isPaused?this.generatedError=e:(this.isFinished=!0,this.emit("error",e),this.previous&&this.previous.error(e),this.cleanUp()),!0)},on:function(e,t){return this._listeners[e].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(e,t){if(this._listeners[e])for(var s=0;s<this._listeners[e].length;s++)this._listeners[e][s].call(this,t)},pipe:function(e){return e.registerPrevious(this)},registerPrevious:function(e){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=e.streamInfo,this.mergeStreamInfo(),this.previous=e;var t=this;return e.on("data",function(e){t.processChunk(e)}),e.on("end",function(){t.end()}),e.on("error",function(e){t.error(e)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var e=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),e=!0),this.previous&&this.previous.resume(),!e},flush:function(){},processChunk:function(e){this.push(e)},withStreamInfo:function(e,t){return this.extraStreamInfo[e]=t,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var e in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,e)&&(this.streamInfo[e]=this.extraStreamInfo[e])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var e="Worker "+this.name;return this.previous?this.previous+" -> "+e:e}},t.exports=i},{}],29:[function(e,t,s){var i=e("../utils"),r=e("./ConvertWorker"),n=e("./GenericWorker"),o=e("../base64"),a=e("../support"),l=e("../external"),h=null;if(a.nodestream)try{h=e("../nodejs/NodejsStreamOutputAdapter")}catch(e){}function u(e,t){return new l.Promise(function(s,r){var n=[],a=e._internalType,l=e._outputType,h=e._mimeType;e.on("data",function(e,s){n.push(e),t&&t(s)}).on("error",function(e){n=[],r(e)}).on("end",function(){try{var e=function(e,t,s){switch(e){case"blob":return i.newBlob(i.transformTo("arraybuffer",t),s);case"base64":return o.encode(t);default:return i.transformTo(e,t)}}(l,function(e,t){var s,i=0,r=null,n=0;for(s=0;s<t.length;s++)n+=t[s].length;switch(e){case"string":return t.join("");case"array":return Array.prototype.concat.apply([],t);case"uint8array":for(r=new Uint8Array(n),s=0;s<t.length;s++)r.set(t[s],i),i+=t[s].length;return r;case"nodebuffer":return Buffer.concat(t);default:throw new Error("concat : unsupported type '"+e+"'")}}(a,n),h);s(e)}catch(e){r(e)}n=[]}).resume()})}function c(e,t,s){var o=t;switch(t){case"blob":case"arraybuffer":o="uint8array";break;case"base64":o="string"}try{this._internalType=o,this._outputType=t,this._mimeType=s,i.checkSupport(o),this._worker=e.pipe(new r(o)),e.lock()}catch(e){this._worker=new n("error"),this._worker.error(e)}}c.prototype={accumulate:function(e){return u(this,e)},on:function(e,t){var s=this;return"data"===e?this._worker.on(e,function(e){t.call(s,e.data,e.meta)}):this._worker.on(e,function(){i.delay(t,arguments,s)}),this},resume:function(){return i.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(e){if(i.checkSupport("nodestream"),"nodebuffer"!==this._outputType)throw new Error(this._outputType+" is not supported by this method");return new h(this,{objectMode:"nodebuffer"!==this._outputType},e)}},t.exports=c},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(e,t,s){if(s.base64=!0,s.array=!0,s.string=!0,s.arraybuffer="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array,s.nodebuffer="undefined"!=typeof Buffer,s.uint8array="undefined"!=typeof Uint8Array,"undefined"==typeof ArrayBuffer)s.blob=!1;else{var i=new ArrayBuffer(0);try{s.blob=0===new Blob([i],{type:"application/zip"}).size}catch(e){try{var r=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);r.append(i),s.blob=0===r.getBlob("application/zip").size}catch(e){s.blob=!1}}}try{s.nodestream=!!e("readable-stream").Readable}catch(e){s.nodestream=!1}},{"readable-stream":16}],31:[function(e,t,s){for(var i=e("./utils"),r=e("./support"),n=e("./nodejsUtils"),o=e("./stream/GenericWorker"),a=new Array(256),l=0;l<256;l++)a[l]=252<=l?6:248<=l?5:240<=l?4:224<=l?3:192<=l?2:1;function h(){o.call(this,"utf-8 decode"),this.leftOver=null}function u(){o.call(this,"utf-8 encode")}a[254]=a[254]=1,s.utf8encode=function(e){return r.nodebuffer?n.newBufferFrom(e,"utf-8"):function(e){var t,s,i,n,o,a=e.length,l=0;for(n=0;n<a;n++)55296==(64512&(s=e.charCodeAt(n)))&&n+1<a&&56320==(64512&(i=e.charCodeAt(n+1)))&&(s=65536+(s-55296<<10)+(i-56320),n++),l+=s<128?1:s<2048?2:s<65536?3:4;for(t=r.uint8array?new Uint8Array(l):new Array(l),n=o=0;o<l;n++)55296==(64512&(s=e.charCodeAt(n)))&&n+1<a&&56320==(64512&(i=e.charCodeAt(n+1)))&&(s=65536+(s-55296<<10)+(i-56320),n++),s<128?t[o++]=s:(s<2048?t[o++]=192|s>>>6:(s<65536?t[o++]=224|s>>>12:(t[o++]=240|s>>>18,t[o++]=128|s>>>12&63),t[o++]=128|s>>>6&63),t[o++]=128|63&s);return t}(e)},s.utf8decode=function(e){return r.nodebuffer?i.transformTo("nodebuffer",e).toString("utf-8"):function(e){var t,s,r,n,o=e.length,l=new Array(2*o);for(t=s=0;t<o;)if((r=e[t++])<128)l[s++]=r;else if(4<(n=a[r]))l[s++]=65533,t+=n-1;else{for(r&=2===n?31:3===n?15:7;1<n&&t<o;)r=r<<6|63&e[t++],n--;1<n?l[s++]=65533:r<65536?l[s++]=r:(r-=65536,l[s++]=55296|r>>10&1023,l[s++]=56320|1023&r)}return l.length!==s&&(l.subarray?l=l.subarray(0,s):l.length=s),i.applyFromCharCode(l)}(e=i.transformTo(r.uint8array?"uint8array":"array",e))},i.inherits(h,o),h.prototype.processChunk=function(e){var t=i.transformTo(r.uint8array?"uint8array":"array",e.data);if(this.leftOver&&this.leftOver.length){if(r.uint8array){var n=t;(t=new Uint8Array(n.length+this.leftOver.length)).set(this.leftOver,0),t.set(n,this.leftOver.length)}else t=this.leftOver.concat(t);this.leftOver=null}var o=function(e,t){var s;for((t=t||e.length)>e.length&&(t=e.length),s=t-1;0<=s&&128==(192&e[s]);)s--;return s<0||0===s?t:s+a[e[s]]>t?s:t}(t),l=t;o!==t.length&&(r.uint8array?(l=t.subarray(0,o),this.leftOver=t.subarray(o,t.length)):(l=t.slice(0,o),this.leftOver=t.slice(o,t.length))),this.push({data:s.utf8decode(l),meta:e.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:s.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},s.Utf8DecodeWorker=h,i.inherits(u,o),u.prototype.processChunk=function(e){this.push({data:s.utf8encode(e.data),meta:e.meta})},s.Utf8EncodeWorker=u},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(e,t,s){var i=e("./support"),r=e("./base64"),n=e("./nodejsUtils"),o=e("./external");function a(e){return e}function l(e,t){for(var s=0;s<e.length;++s)t[s]=255&e.charCodeAt(s);return t}e("setimmediate"),s.newBlob=function(e,t){s.checkSupport("blob");try{return new Blob([e],{type:t})}catch(s){try{var i=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return i.append(e),i.getBlob(t)}catch(e){throw new Error("Bug : can't construct the Blob.")}}};var h={stringifyByChunk:function(e,t,s){var i=[],r=0,n=e.length;if(n<=s)return String.fromCharCode.apply(null,e);for(;r<n;)"array"===t||"nodebuffer"===t?i.push(String.fromCharCode.apply(null,e.slice(r,Math.min(r+s,n)))):i.push(String.fromCharCode.apply(null,e.subarray(r,Math.min(r+s,n)))),r+=s;return i.join("")},stringifyByChar:function(e){for(var t="",s=0;s<e.length;s++)t+=String.fromCharCode(e[s]);return t},applyCanBeUsed:{uint8array:function(){try{return i.uint8array&&1===String.fromCharCode.apply(null,new Uint8Array(1)).length}catch(e){return!1}}(),nodebuffer:function(){try{return i.nodebuffer&&1===String.fromCharCode.apply(null,n.allocBuffer(1)).length}catch(e){return!1}}()}};function u(e){var t=65536,i=s.getTypeOf(e),r=!0;if("uint8array"===i?r=h.applyCanBeUsed.uint8array:"nodebuffer"===i&&(r=h.applyCanBeUsed.nodebuffer),r)for(;1<t;)try{return h.stringifyByChunk(e,i,t)}catch(e){t=Math.floor(t/2)}return h.stringifyByChar(e)}function c(e,t){for(var s=0;s<e.length;s++)t[s]=e[s];return t}s.applyFromCharCode=u;var d={};d.string={string:a,array:function(e){return l(e,new Array(e.length))},arraybuffer:function(e){return d.string.uint8array(e).buffer},uint8array:function(e){return l(e,new Uint8Array(e.length))},nodebuffer:function(e){return l(e,n.allocBuffer(e.length))}},d.array={string:u,array:a,arraybuffer:function(e){return new Uint8Array(e).buffer},uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return n.newBufferFrom(e)}},d.arraybuffer={string:function(e){return u(new Uint8Array(e))},array:function(e){return c(new Uint8Array(e),new Array(e.byteLength))},arraybuffer:a,uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return n.newBufferFrom(new Uint8Array(e))}},d.uint8array={string:u,array:function(e){return c(e,new Array(e.length))},arraybuffer:function(e){return e.buffer},uint8array:a,nodebuffer:function(e){return n.newBufferFrom(e)}},d.nodebuffer={string:u,array:function(e){return c(e,new Array(e.length))},arraybuffer:function(e){return d.nodebuffer.uint8array(e).buffer},uint8array:function(e){return c(e,new Uint8Array(e.length))},nodebuffer:a},s.transformTo=function(e,t){if(t=t||"",!e)return t;s.checkSupport(e);var i=s.getTypeOf(t);return d[i][e](t)},s.resolve=function(e){for(var t=e.split("/"),s=[],i=0;i<t.length;i++){var r=t[i];"."===r||""===r&&0!==i&&i!==t.length-1||(".."===r?s.pop():s.push(r))}return s.join("/")},s.getTypeOf=function(e){return"string"==typeof e?"string":"[object Array]"===Object.prototype.toString.call(e)?"array":i.nodebuffer&&n.isBuffer(e)?"nodebuffer":i.uint8array&&e instanceof Uint8Array?"uint8array":i.arraybuffer&&e instanceof ArrayBuffer?"arraybuffer":void 0},s.checkSupport=function(e){if(!i[e.toLowerCase()])throw new Error(e+" is not supported by this platform")},s.MAX_VALUE_16BITS=65535,s.MAX_VALUE_32BITS=-1,s.pretty=function(e){var t,s,i="";for(s=0;s<(e||"").length;s++)i+="\\x"+((t=e.charCodeAt(s))<16?"0":"")+t.toString(16).toUpperCase();return i},s.delay=function(e,t,s){setImmediate(function(){e.apply(s||null,t||[])})},s.inherits=function(e,t){function s(){}s.prototype=t.prototype,e.prototype=new s},s.extend=function(){var e,t,s={};for(e=0;e<arguments.length;e++)for(t in arguments[e])Object.prototype.hasOwnProperty.call(arguments[e],t)&&void 0===s[t]&&(s[t]=arguments[e][t]);return s},s.prepareContent=function(e,t,n,a,h){return o.Promise.resolve(t).then(function(e){return i.blob&&(e instanceof Blob||-1!==["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(e)))&&"undefined"!=typeof FileReader?new o.Promise(function(t,s){var i=new FileReader;i.onload=function(e){t(e.target.result)},i.onerror=function(e){s(e.target.error)},i.readAsArrayBuffer(e)}):e}).then(function(t){var u,c=s.getTypeOf(t);return c?("arraybuffer"===c?t=s.transformTo("uint8array",t):"string"===c&&(h?t=r.decode(t):n&&!0!==a&&(t=l(u=t,i.uint8array?new Uint8Array(u.length):new Array(u.length)))),t):o.Promise.reject(new Error("Can't read the data of '"+e+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(e,t,s){var i=e("./reader/readerFor"),r=e("./utils"),n=e("./signature"),o=e("./zipEntry"),a=e("./support");function l(e){this.files=[],this.loadOptions=e}l.prototype={checkSignature:function(e){if(!this.reader.readAndCheckSignature(e)){this.reader.index-=4;var t=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+r.pretty(t)+", expected "+r.pretty(e)+")")}},isSignature:function(e,t){var s=this.reader.index;this.reader.setIndex(e);var i=this.reader.readString(4)===t;return this.reader.setIndex(s),i},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var e=this.reader.readData(this.zipCommentLength),t=a.uint8array?"uint8array":"array",s=r.transformTo(t,e);this.zipComment=this.loadOptions.decodeFileName(s)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var e,t,s,i=this.zip64EndOfCentralSize-44;0<i;)e=this.reader.readInt(2),t=this.reader.readInt(4),s=this.reader.readData(t),this.zip64ExtensibleData[e]={id:e,length:t,value:s}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var e,t;for(e=0;e<this.files.length;e++)t=this.files[e],this.reader.setIndex(t.localHeaderOffset),this.checkSignature(n.LOCAL_FILE_HEADER),t.readLocalPart(this.reader),t.handleUTF8(),t.processAttributes()},readCentralDir:function(){var e;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(n.CENTRAL_FILE_HEADER);)(e=new o({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(e);if(this.centralDirRecords!==this.files.length&&0!==this.centralDirRecords&&0===this.files.length)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var e=this.reader.lastIndexOfSignature(n.CENTRAL_DIRECTORY_END);if(e<0)throw this.isSignature(0,n.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(e);var t=e;if(this.checkSignature(n.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===r.MAX_VALUE_16BITS||this.diskWithCentralDirStart===r.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===r.MAX_VALUE_16BITS||this.centralDirRecords===r.MAX_VALUE_16BITS||this.centralDirSize===r.MAX_VALUE_32BITS||this.centralDirOffset===r.MAX_VALUE_32BITS){if(this.zip64=!0,(e=this.reader.lastIndexOfSignature(n.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(e),this.checkSignature(n.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,n.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(n.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(n.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var s=this.centralDirOffset+this.centralDirSize;this.zip64&&(s+=20,s+=12+this.zip64EndOfCentralSize);var i=t-s;if(0<i)this.isSignature(t,n.CENTRAL_FILE_HEADER)||(this.reader.zero=i);else if(i<0)throw new Error("Corrupted zip: missing "+Math.abs(i)+" bytes.")},prepareReader:function(e){this.reader=i(e)},load:function(e){this.prepareReader(e),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},t.exports=l},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(e,t,s){var i=e("./reader/readerFor"),r=e("./utils"),n=e("./compressedObject"),o=e("./crc32"),a=e("./utf8"),l=e("./compressions"),h=e("./support");function u(e,t){this.options=e,this.loadOptions=t}u.prototype={isEncrypted:function(){return!(1&~this.bitFlag)},useUTF8:function(){return!(2048&~this.bitFlag)},readLocalPart:function(e){var t,s;if(e.skip(22),this.fileNameLength=e.readInt(2),s=e.readInt(2),this.fileName=e.readData(this.fileNameLength),e.skip(s),-1===this.compressedSize||-1===this.uncompressedSize)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(null===(t=function(e){for(var t in l)if(Object.prototype.hasOwnProperty.call(l,t)&&l[t].magic===e)return l[t];return null}(this.compressionMethod)))throw new Error("Corrupted zip : compression "+r.pretty(this.compressionMethod)+" unknown (inner file : "+r.transformTo("string",this.fileName)+")");this.decompressed=new n(this.compressedSize,this.uncompressedSize,this.crc32,t,e.readData(this.compressedSize))},readCentralPart:function(e){this.versionMadeBy=e.readInt(2),e.skip(2),this.bitFlag=e.readInt(2),this.compressionMethod=e.readString(2),this.date=e.readDate(),this.crc32=e.readInt(4),this.compressedSize=e.readInt(4),this.uncompressedSize=e.readInt(4);var t=e.readInt(2);if(this.extraFieldsLength=e.readInt(2),this.fileCommentLength=e.readInt(2),this.diskNumberStart=e.readInt(2),this.internalFileAttributes=e.readInt(2),this.externalFileAttributes=e.readInt(4),this.localHeaderOffset=e.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");e.skip(t),this.readExtraFields(e),this.parseZIP64ExtraField(e),this.fileComment=e.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var e=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),0==e&&(this.dosPermissions=63&this.externalFileAttributes),3==e&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var e=i(this.extraFields[1].value);this.uncompressedSize===r.MAX_VALUE_32BITS&&(this.uncompressedSize=e.readInt(8)),this.compressedSize===r.MAX_VALUE_32BITS&&(this.compressedSize=e.readInt(8)),this.localHeaderOffset===r.MAX_VALUE_32BITS&&(this.localHeaderOffset=e.readInt(8)),this.diskNumberStart===r.MAX_VALUE_32BITS&&(this.diskNumberStart=e.readInt(4))}},readExtraFields:function(e){var t,s,i,r=e.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});e.index+4<r;)t=e.readInt(2),s=e.readInt(2),i=e.readData(s),this.extraFields[t]={id:t,length:s,value:i};e.setIndex(r)},handleUTF8:function(){var e=h.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=a.utf8decode(this.fileName),this.fileCommentStr=a.utf8decode(this.fileComment);else{var t=this.findExtraFieldUnicodePath();if(null!==t)this.fileNameStr=t;else{var s=r.transformTo(e,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(s)}var i=this.findExtraFieldUnicodeComment();if(null!==i)this.fileCommentStr=i;else{var n=r.transformTo(e,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(n)}}},findExtraFieldUnicodePath:function(){var e=this.extraFields[28789];if(e){var t=i(e.value);return 1!==t.readInt(1)||o(this.fileName)!==t.readInt(4)?null:a.utf8decode(t.readData(e.length-5))}return null},findExtraFieldUnicodeComment:function(){var e=this.extraFields[25461];if(e){var t=i(e.value);return 1!==t.readInt(1)||o(this.fileComment)!==t.readInt(4)?null:a.utf8decode(t.readData(e.length-5))}return null}},t.exports=u},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(e,t,s){function i(e,t,s){this.name=e,this.dir=s.dir,this.date=s.date,this.comment=s.comment,this.unixPermissions=s.unixPermissions,this.dosPermissions=s.dosPermissions,this._data=t,this._dataBinary=s.binary,this.options={compression:s.compression,compressionOptions:s.compressionOptions}}var r=e("./stream/StreamHelper"),n=e("./stream/DataWorker"),o=e("./utf8"),a=e("./compressedObject"),l=e("./stream/GenericWorker");i.prototype={internalStream:function(e){var t=null,s="string";try{if(!e)throw new Error("No output type specified.");var i="string"===(s=e.toLowerCase())||"text"===s;"binarystring"!==s&&"text"!==s||(s="string"),t=this._decompressWorker();var n=!this._dataBinary;n&&!i&&(t=t.pipe(new o.Utf8EncodeWorker)),!n&&i&&(t=t.pipe(new o.Utf8DecodeWorker))}catch(e){(t=new l("error")).error(e)}return new r(t,s,"")},async:function(e,t){return this.internalStream(e).accumulate(t)},nodeStream:function(e,t){return this.internalStream(e||"nodebuffer").toNodejsStream(t)},_compressWorker:function(e,t){if(this._data instanceof a&&this._data.compression.magic===e.magic)return this._data.getCompressedWorker();var s=this._decompressWorker();return this._dataBinary||(s=s.pipe(new o.Utf8EncodeWorker)),a.createWorkerFrom(s,e,t)},_decompressWorker:function(){return this._data instanceof a?this._data.getContentWorker():this._data instanceof l?this._data:new n(this._data)}};for(var h=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],u=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},c=0;c<h.length;c++)i.prototype[h[c]]=u;t.exports=i},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(e,t,s){(function(e){var s,i,r=e.MutationObserver||e.WebKitMutationObserver;if(r){var n=0,o=new r(u),a=e.document.createTextNode("");o.observe(a,{characterData:!0}),s=function(){a.data=n=++n%2}}else if(e.setImmediate||void 0===e.MessageChannel)s="document"in e&&"onreadystatechange"in e.document.createElement("script")?function(){var t=e.document.createElement("script");t.onreadystatechange=function(){u(),t.onreadystatechange=null,t.parentNode.removeChild(t),t=null},e.document.documentElement.appendChild(t)}:function(){setTimeout(u,0)};else{var l=new e.MessageChannel;l.port1.onmessage=u,s=function(){l.port2.postMessage(0)}}var h=[];function u(){var e,t;i=!0;for(var s=h.length;s;){for(t=h,h=[],e=-1;++e<s;)t[e]();s=h.length}i=!1}t.exports=function(e){1!==h.push(e)||i||s()}}).call(this,void 0!==IO?IO:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],37:[function(e,t,s){var i=e("immediate");function r(){}var n={},o=["REJECTED"],a=["FULFILLED"],l=["PENDING"];function h(e){if("function"!=typeof e)throw new TypeError("resolver must be a function");this.state=l,this.queue=[],this.outcome=void 0,e!==r&&p(this,e)}function u(e,t,s){this.promise=e,"function"==typeof t&&(this.onFulfilled=t,this.callFulfilled=this.otherCallFulfilled),"function"==typeof s&&(this.onRejected=s,this.callRejected=this.otherCallRejected)}function c(e,t,s){i(function(){var i;try{i=t(s)}catch(t){return n.reject(e,t)}i===e?n.reject(e,new TypeError("Cannot resolve promise with itself")):n.resolve(e,i)})}function d(e){var t=e&&e.then;if(e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof t)return function(){t.apply(e,arguments)}}function p(e,t){var s=!1;function i(t){s||(s=!0,n.reject(e,t))}function r(t){s||(s=!0,n.resolve(e,t))}var o=m(function(){t(r,i)});"error"===o.status&&i(o.value)}function m(e,t){var s={};try{s.value=e(t),s.status="success"}catch(e){s.status="error",s.value=e}return s}(t.exports=h).prototype.finally=function(e){if("function"!=typeof e)return this;var t=this.constructor;return this.then(function(s){return t.resolve(e()).then(function(){return s})},function(s){return t.resolve(e()).then(function(){throw s})})},h.prototype.catch=function(e){return this.then(null,e)},h.prototype.then=function(e,t){if("function"!=typeof e&&this.state===a||"function"!=typeof t&&this.state===o)return this;var s=new this.constructor(r);return this.state!==l?c(s,this.state===a?e:t,this.outcome):this.queue.push(new u(s,e,t)),s},u.prototype.callFulfilled=function(e){n.resolve(this.promise,e)},u.prototype.otherCallFulfilled=function(e){c(this.promise,this.onFulfilled,e)},u.prototype.callRejected=function(e){n.reject(this.promise,e)},u.prototype.otherCallRejected=function(e){c(this.promise,this.onRejected,e)},n.resolve=function(e,t){var s=m(d,t);if("error"===s.status)return n.reject(e,s.value);var i=s.value;if(i)p(e,i);else{e.state=a,e.outcome=t;for(var r=-1,o=e.queue.length;++r<o;)e.queue[r].callFulfilled(t)}return e},n.reject=function(e,t){e.state=o,e.outcome=t;for(var s=-1,i=e.queue.length;++s<i;)e.queue[s].callRejected(t);return e},h.resolve=function(e){return e instanceof this?e:n.resolve(new this(r),e)},h.reject=function(e){var t=new this(r);return n.reject(t,e)},h.all=function(e){var t=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var s=e.length,i=!1;if(!s)return this.resolve([]);for(var o=new Array(s),a=0,l=-1,h=new this(r);++l<s;)u(e[l],l);return h;function u(e,r){t.resolve(e).then(function(e){o[r]=e,++a!==s||i||(i=!0,n.resolve(h,o))},function(e){i||(i=!0,n.reject(h,e))})}},h.race=function(e){var t=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var s=e.length,i=!1;if(!s)return this.resolve([]);for(var o,a=-1,l=new this(r);++a<s;)o=e[a],t.resolve(o).then(function(e){i||(i=!0,n.resolve(l,e))},function(e){i||(i=!0,n.reject(l,e))});return l}},{immediate:36}],38:[function(e,t,s){var i={};(0,e("./lib/utils/common").assign)(i,e("./lib/deflate"),e("./lib/inflate"),e("./lib/zlib/constants")),t.exports=i},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(e,t,s){var i=e("./zlib/deflate"),r=e("./utils/common"),n=e("./utils/strings"),o=e("./zlib/messages"),a=e("./zlib/zstream"),l=Object.prototype.toString,h=0,u=-1,c=0,d=8;function p(e){if(!(this instanceof p))return new p(e);this.options=r.assign({level:u,method:d,chunkSize:16384,windowBits:15,memLevel:8,strategy:c,to:""},e||{});var t=this.options;t.raw&&0<t.windowBits?t.windowBits=-t.windowBits:t.gzip&&0<t.windowBits&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var s=i.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(s!==h)throw new Error(o[s]);if(t.header&&i.deflateSetHeader(this.strm,t.header),t.dictionary){var m;if(m="string"==typeof t.dictionary?n.string2buf(t.dictionary):"[object ArrayBuffer]"===l.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(s=i.deflateSetDictionary(this.strm,m))!==h)throw new Error(o[s]);this._dict_set=!0}}function m(e,t){var s=new p(t);if(s.push(e,!0),s.err)throw s.msg||o[s.err];return s.result}p.prototype.push=function(e,t){var s,o,a=this.strm,u=this.options.chunkSize;if(this.ended)return!1;o=t===~~t?t:!0===t?4:0,"string"==typeof e?a.input=n.string2buf(e):"[object ArrayBuffer]"===l.call(e)?a.input=new Uint8Array(e):a.input=e,a.next_in=0,a.avail_in=a.input.length;do{if(0===a.avail_out&&(a.output=new r.Buf8(u),a.next_out=0,a.avail_out=u),1!==(s=i.deflate(a,o))&&s!==h)return this.onEnd(s),!(this.ended=!0);0!==a.avail_out&&(0!==a.avail_in||4!==o&&2!==o)||("string"===this.options.to?this.onData(n.buf2binstring(r.shrinkBuf(a.output,a.next_out))):this.onData(r.shrinkBuf(a.output,a.next_out)))}while((0<a.avail_in||0===a.avail_out)&&1!==s);return 4===o?(s=i.deflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===h):2!==o||(this.onEnd(h),!(a.avail_out=0))},p.prototype.onData=function(e){this.chunks.push(e)},p.prototype.onEnd=function(e){e===h&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=r.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},s.Deflate=p,s.deflate=m,s.deflateRaw=function(e,t){return(t=t||{}).raw=!0,m(e,t)},s.gzip=function(e,t){return(t=t||{}).gzip=!0,m(e,t)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(e,t,s){var i=e("./zlib/inflate"),r=e("./utils/common"),n=e("./utils/strings"),o=e("./zlib/constants"),a=e("./zlib/messages"),l=e("./zlib/zstream"),h=e("./zlib/gzheader"),u=Object.prototype.toString;function c(e){if(!(this instanceof c))return new c(e);this.options=r.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&!(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var s=i.inflateInit2(this.strm,t.windowBits);if(s!==o.Z_OK)throw new Error(a[s]);this.header=new h,i.inflateGetHeader(this.strm,this.header)}function d(e,t){var s=new c(t);if(s.push(e,!0),s.err)throw s.msg||a[s.err];return s.result}c.prototype.push=function(e,t){var s,a,l,h,c,d,p=this.strm,m=this.options.chunkSize,f=this.options.dictionary,g=!1;if(this.ended)return!1;a=t===~~t?t:!0===t?o.Z_FINISH:o.Z_NO_FLUSH,"string"==typeof e?p.input=n.binstring2buf(e):"[object ArrayBuffer]"===u.call(e)?p.input=new Uint8Array(e):p.input=e,p.next_in=0,p.avail_in=p.input.length;do{if(0===p.avail_out&&(p.output=new r.Buf8(m),p.next_out=0,p.avail_out=m),(s=i.inflate(p,o.Z_NO_FLUSH))===o.Z_NEED_DICT&&f&&(d="string"==typeof f?n.string2buf(f):"[object ArrayBuffer]"===u.call(f)?new Uint8Array(f):f,s=i.inflateSetDictionary(this.strm,d)),s===o.Z_BUF_ERROR&&!0===g&&(s=o.Z_OK,g=!1),s!==o.Z_STREAM_END&&s!==o.Z_OK)return this.onEnd(s),!(this.ended=!0);p.next_out&&(0!==p.avail_out&&s!==o.Z_STREAM_END&&(0!==p.avail_in||a!==o.Z_FINISH&&a!==o.Z_SYNC_FLUSH)||("string"===this.options.to?(l=n.utf8border(p.output,p.next_out),h=p.next_out-l,c=n.buf2string(p.output,l),p.next_out=h,p.avail_out=m-h,h&&r.arraySet(p.output,p.output,l,h,0),this.onData(c)):this.onData(r.shrinkBuf(p.output,p.next_out)))),0===p.avail_in&&0===p.avail_out&&(g=!0)}while((0<p.avail_in||0===p.avail_out)&&s!==o.Z_STREAM_END);return s===o.Z_STREAM_END&&(a=o.Z_FINISH),a===o.Z_FINISH?(s=i.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===o.Z_OK):a!==o.Z_SYNC_FLUSH||(this.onEnd(o.Z_OK),!(p.avail_out=0))},c.prototype.onData=function(e){this.chunks.push(e)},c.prototype.onEnd=function(e){e===o.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=r.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},s.Inflate=c,s.inflate=d,s.inflateRaw=function(e,t){return(t=t||{}).raw=!0,d(e,t)},s.ungzip=d},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(e,t,s){var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;s.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var s=t.shift();if(s){if("object"!=typeof s)throw new TypeError(s+"must be non-object");for(var i in s)s.hasOwnProperty(i)&&(e[i]=s[i])}}return e},s.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var r={arraySet:function(e,t,s,i,r){if(t.subarray&&e.subarray)e.set(t.subarray(s,s+i),r);else for(var n=0;n<i;n++)e[r+n]=t[s+n]},flattenChunks:function(e){var t,s,i,r,n,o;for(t=i=0,s=e.length;t<s;t++)i+=e[t].length;for(o=new Uint8Array(i),t=r=0,s=e.length;t<s;t++)n=e[t],o.set(n,r),r+=n.length;return o}},n={arraySet:function(e,t,s,i,r){for(var n=0;n<i;n++)e[r+n]=t[s+n]},flattenChunks:function(e){return[].concat.apply([],e)}};s.setTyped=function(e){e?(s.Buf8=Uint8Array,s.Buf16=Uint16Array,s.Buf32=Int32Array,s.assign(s,r)):(s.Buf8=Array,s.Buf16=Array,s.Buf32=Array,s.assign(s,n))},s.setTyped(i)},{}],42:[function(e,t,s){var i=e("./common"),r=!0,n=!0;try{String.fromCharCode.apply(null,[0])}catch(e){r=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){n=!1}for(var o=new i.Buf8(256),a=0;a<256;a++)o[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function l(e,t){if(t<65537&&(e.subarray&&n||!e.subarray&&r))return String.fromCharCode.apply(null,i.shrinkBuf(e,t));for(var s="",o=0;o<t;o++)s+=String.fromCharCode(e[o]);return s}o[254]=o[254]=1,s.string2buf=function(e){var t,s,r,n,o,a=e.length,l=0;for(n=0;n<a;n++)55296==(64512&(s=e.charCodeAt(n)))&&n+1<a&&56320==(64512&(r=e.charCodeAt(n+1)))&&(s=65536+(s-55296<<10)+(r-56320),n++),l+=s<128?1:s<2048?2:s<65536?3:4;for(t=new i.Buf8(l),n=o=0;o<l;n++)55296==(64512&(s=e.charCodeAt(n)))&&n+1<a&&56320==(64512&(r=e.charCodeAt(n+1)))&&(s=65536+(s-55296<<10)+(r-56320),n++),s<128?t[o++]=s:(s<2048?t[o++]=192|s>>>6:(s<65536?t[o++]=224|s>>>12:(t[o++]=240|s>>>18,t[o++]=128|s>>>12&63),t[o++]=128|s>>>6&63),t[o++]=128|63&s);return t},s.buf2binstring=function(e){return l(e,e.length)},s.binstring2buf=function(e){for(var t=new i.Buf8(e.length),s=0,r=t.length;s<r;s++)t[s]=e.charCodeAt(s);return t},s.buf2string=function(e,t){var s,i,r,n,a=t||e.length,h=new Array(2*a);for(s=i=0;s<a;)if((r=e[s++])<128)h[i++]=r;else if(4<(n=o[r]))h[i++]=65533,s+=n-1;else{for(r&=2===n?31:3===n?15:7;1<n&&s<a;)r=r<<6|63&e[s++],n--;1<n?h[i++]=65533:r<65536?h[i++]=r:(r-=65536,h[i++]=55296|r>>10&1023,h[i++]=56320|1023&r)}return l(h,i)},s.utf8border=function(e,t){var s;for((t=t||e.length)>e.length&&(t=e.length),s=t-1;0<=s&&128==(192&e[s]);)s--;return s<0||0===s?t:s+o[e[s]]>t?s:t}},{"./common":41}],43:[function(e,t,s){t.exports=function(e,t,s,i){for(var r=65535&e,n=e>>>16&65535,o=0;0!==s;){for(s-=o=2e3<s?2e3:s;n=n+(r=r+t[i++]|0)|0,--o;);r%=65521,n%=65521}return r|n<<16}},{}],44:[function(e,t,s){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(e,t,s){var i=function(){for(var e,t=[],s=0;s<256;s++){e=s;for(var i=0;i<8;i++)e=1&e?3988292384^e>>>1:e>>>1;t[s]=e}return t}();t.exports=function(e,t,s,r){var n=i,o=r+s;e^=-1;for(var a=r;a<o;a++)e=e>>>8^n[255&(e^t[a])];return-1^e}},{}],46:[function(e,t,s){var i,r=e("../utils/common"),n=e("./trees"),o=e("./adler32"),a=e("./crc32"),l=e("./messages"),h=0,u=4,c=0,d=-2,p=-1,m=4,f=2,g=8,y=9,x=286,b=30,_=19,w=2*x+1,v=15,T=3,S=258,M=S+T+1,A=42,N=113,E=1,C=2,R=3,P=4;function B(e,t){return e.msg=l[t],t}function I(e){return(e<<1)-(4<e?9:0)}function D(e){for(var t=e.length;0<=--t;)e[t]=0}function L(e){var t=e.state,s=t.pending;s>e.avail_out&&(s=e.avail_out),0!==s&&(r.arraySet(e.output,t.pending_buf,t.pending_out,s,e.next_out),e.next_out+=s,t.pending_out+=s,e.total_out+=s,e.avail_out-=s,t.pending-=s,0===t.pending&&(t.pending_out=0))}function F(e,t){n._tr_flush_block(e,0<=e.block_start?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,L(e.strm)}function O(e,t){e.pending_buf[e.pending++]=t}function V(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function z(e,t){var s,i,r=e.max_chain_length,n=e.strstart,o=e.prev_length,a=e.nice_match,l=e.strstart>e.w_size-M?e.strstart-(e.w_size-M):0,h=e.window,u=e.w_mask,c=e.prev,d=e.strstart+S,p=h[n+o-1],m=h[n+o];e.prev_length>=e.good_match&&(r>>=2),a>e.lookahead&&(a=e.lookahead);do{if(h[(s=t)+o]===m&&h[s+o-1]===p&&h[s]===h[n]&&h[++s]===h[n+1]){n+=2,s++;do{}while(h[++n]===h[++s]&&h[++n]===h[++s]&&h[++n]===h[++s]&&h[++n]===h[++s]&&h[++n]===h[++s]&&h[++n]===h[++s]&&h[++n]===h[++s]&&h[++n]===h[++s]&&n<d);if(i=S-(d-n),n=d-S,o<i){if(e.match_start=t,a<=(o=i))break;p=h[n+o-1],m=h[n+o]}}}while((t=c[t&u])>l&&0!=--r);return o<=e.lookahead?o:e.lookahead}function k(e){var t,s,i,n,l,h,u,c,d,p,m=e.w_size;do{if(n=e.window_size-e.lookahead-e.strstart,e.strstart>=m+(m-M)){for(r.arraySet(e.window,e.window,m,m,0),e.match_start-=m,e.strstart-=m,e.block_start-=m,t=s=e.hash_size;i=e.head[--t],e.head[t]=m<=i?i-m:0,--s;);for(t=s=m;i=e.prev[--t],e.prev[t]=m<=i?i-m:0,--s;);n+=m}if(0===e.strm.avail_in)break;if(h=e.strm,u=e.window,c=e.strstart+e.lookahead,p=void 0,(d=n)<(p=h.avail_in)&&(p=d),s=0===p?0:(h.avail_in-=p,r.arraySet(u,h.input,h.next_in,p,c),1===h.state.wrap?h.adler=o(h.adler,u,p,c):2===h.state.wrap&&(h.adler=a(h.adler,u,p,c)),h.next_in+=p,h.total_in+=p,p),e.lookahead+=s,e.lookahead+e.insert>=T)for(l=e.strstart-e.insert,e.ins_h=e.window[l],e.ins_h=(e.ins_h<<e.hash_shift^e.window[l+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[l+T-1])&e.hash_mask,e.prev[l&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=l,l++,e.insert--,!(e.lookahead+e.insert<T)););}while(e.lookahead<M&&0!==e.strm.avail_in)}function U(e,t){for(var s,i;;){if(e.lookahead<M){if(k(e),e.lookahead<M&&t===h)return E;if(0===e.lookahead)break}if(s=0,e.lookahead>=T&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+T-1])&e.hash_mask,s=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==s&&e.strstart-s<=e.w_size-M&&(e.match_length=z(e,s)),e.match_length>=T)if(i=n._tr_tally(e,e.strstart-e.match_start,e.match_length-T),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=T){for(e.match_length--;e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+T-1])&e.hash_mask,s=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart,0!=--e.match_length;);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else i=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(i&&(F(e,!1),0===e.strm.avail_out))return E}return e.insert=e.strstart<T-1?e.strstart:T-1,t===u?(F(e,!0),0===e.strm.avail_out?R:P):e.last_lit&&(F(e,!1),0===e.strm.avail_out)?E:C}function G(e,t){for(var s,i,r;;){if(e.lookahead<M){if(k(e),e.lookahead<M&&t===h)return E;if(0===e.lookahead)break}if(s=0,e.lookahead>=T&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+T-1])&e.hash_mask,s=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=T-1,0!==s&&e.prev_length<e.max_lazy_match&&e.strstart-s<=e.w_size-M&&(e.match_length=z(e,s),e.match_length<=5&&(1===e.strategy||e.match_length===T&&4096<e.strstart-e.match_start)&&(e.match_length=T-1)),e.prev_length>=T&&e.match_length<=e.prev_length){for(r=e.strstart+e.lookahead-T,i=n._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-T),e.lookahead-=e.prev_length-1,e.prev_length-=2;++e.strstart<=r&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+T-1])&e.hash_mask,s=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!=--e.prev_length;);if(e.match_available=0,e.match_length=T-1,e.strstart++,i&&(F(e,!1),0===e.strm.avail_out))return E}else if(e.match_available){if((i=n._tr_tally(e,0,e.window[e.strstart-1]))&&F(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return E}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(i=n._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<T-1?e.strstart:T-1,t===u?(F(e,!0),0===e.strm.avail_out?R:P):e.last_lit&&(F(e,!1),0===e.strm.avail_out)?E:C}function j(e,t,s,i,r){this.good_length=e,this.max_lazy=t,this.nice_length=s,this.max_chain=i,this.func=r}function $(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=g,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new r.Buf16(2*w),this.dyn_dtree=new r.Buf16(2*(2*b+1)),this.bl_tree=new r.Buf16(2*(2*_+1)),D(this.dyn_ltree),D(this.dyn_dtree),D(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new r.Buf16(v+1),this.heap=new r.Buf16(2*x+1),D(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new r.Buf16(2*x+1),D(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function W(e){var t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=f,(t=e.state).pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?A:N,e.adler=2===t.wrap?0:1,t.last_flush=h,n._tr_init(t),c):B(e,d)}function H(e){var t,s=W(e);return s===c&&((t=e.state).window_size=2*t.w_size,D(t.head),t.max_lazy_match=i[t.level].max_lazy,t.good_match=i[t.level].good_length,t.nice_match=i[t.level].nice_length,t.max_chain_length=i[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=T-1,t.match_available=0,t.ins_h=0),s}function q(e,t,s,i,n,o){if(!e)return d;var a=1;if(t===p&&(t=6),i<0?(a=0,i=-i):15<i&&(a=2,i-=16),n<1||y<n||s!==g||i<8||15<i||t<0||9<t||o<0||m<o)return B(e,d);8===i&&(i=9);var l=new $;return(e.state=l).strm=e,l.wrap=a,l.gzhead=null,l.w_bits=i,l.w_size=1<<l.w_bits,l.w_mask=l.w_size-1,l.hash_bits=n+7,l.hash_size=1<<l.hash_bits,l.hash_mask=l.hash_size-1,l.hash_shift=~~((l.hash_bits+T-1)/T),l.window=new r.Buf8(2*l.w_size),l.head=new r.Buf16(l.hash_size),l.prev=new r.Buf16(l.w_size),l.lit_bufsize=1<<n+6,l.pending_buf_size=4*l.lit_bufsize,l.pending_buf=new r.Buf8(l.pending_buf_size),l.d_buf=1*l.lit_bufsize,l.l_buf=3*l.lit_bufsize,l.level=t,l.strategy=o,l.method=s,H(e)}i=[new j(0,0,0,0,function(e,t){var s=65535;for(s>e.pending_buf_size-5&&(s=e.pending_buf_size-5);;){if(e.lookahead<=1){if(k(e),0===e.lookahead&&t===h)return E;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var i=e.block_start+s;if((0===e.strstart||e.strstart>=i)&&(e.lookahead=e.strstart-i,e.strstart=i,F(e,!1),0===e.strm.avail_out))return E;if(e.strstart-e.block_start>=e.w_size-M&&(F(e,!1),0===e.strm.avail_out))return E}return e.insert=0,t===u?(F(e,!0),0===e.strm.avail_out?R:P):(e.strstart>e.block_start&&(F(e,!1),e.strm.avail_out),E)}),new j(4,4,8,4,U),new j(4,5,16,8,U),new j(4,6,32,32,U),new j(4,4,16,16,G),new j(8,16,32,32,G),new j(8,16,128,128,G),new j(8,32,128,256,G),new j(32,128,258,1024,G),new j(32,258,258,4096,G)],s.deflateInit=function(e,t){return q(e,t,g,15,8,0)},s.deflateInit2=q,s.deflateReset=H,s.deflateResetKeep=W,s.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?d:(e.state.gzhead=t,c):d},s.deflate=function(e,t){var s,r,o,l;if(!e||!e.state||5<t||t<0)return e?B(e,d):d;if(r=e.state,!e.output||!e.input&&0!==e.avail_in||666===r.status&&t!==u)return B(e,0===e.avail_out?-5:d);if(r.strm=e,s=r.last_flush,r.last_flush=t,r.status===A)if(2===r.wrap)e.adler=0,O(r,31),O(r,139),O(r,8),r.gzhead?(O(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),O(r,255&r.gzhead.time),O(r,r.gzhead.time>>8&255),O(r,r.gzhead.time>>16&255),O(r,r.gzhead.time>>24&255),O(r,9===r.level?2:2<=r.strategy||r.level<2?4:0),O(r,255&r.gzhead.os),r.gzhead.extra&&r.gzhead.extra.length&&(O(r,255&r.gzhead.extra.length),O(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(e.adler=a(e.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=69):(O(r,0),O(r,0),O(r,0),O(r,0),O(r,0),O(r,9===r.level?2:2<=r.strategy||r.level<2?4:0),O(r,3),r.status=N);else{var p=g+(r.w_bits-8<<4)<<8;p|=(2<=r.strategy||r.level<2?0:r.level<6?1:6===r.level?2:3)<<6,0!==r.strstart&&(p|=32),p+=31-p%31,r.status=N,V(r,p),0!==r.strstart&&(V(r,e.adler>>>16),V(r,65535&e.adler)),e.adler=1}if(69===r.status)if(r.gzhead.extra){for(o=r.pending;r.gzindex<(65535&r.gzhead.extra.length)&&(r.pending!==r.pending_buf_size||(r.gzhead.hcrc&&r.pending>o&&(e.adler=a(e.adler,r.pending_buf,r.pending-o,o)),L(e),o=r.pending,r.pending!==r.pending_buf_size));)O(r,255&r.gzhead.extra[r.gzindex]),r.gzindex++;r.gzhead.hcrc&&r.pending>o&&(e.adler=a(e.adler,r.pending_buf,r.pending-o,o)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=73)}else r.status=73;if(73===r.status)if(r.gzhead.name){o=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>o&&(e.adler=a(e.adler,r.pending_buf,r.pending-o,o)),L(e),o=r.pending,r.pending===r.pending_buf_size)){l=1;break}l=r.gzindex<r.gzhead.name.length?255&r.gzhead.name.charCodeAt(r.gzindex++):0,O(r,l)}while(0!==l);r.gzhead.hcrc&&r.pending>o&&(e.adler=a(e.adler,r.pending_buf,r.pending-o,o)),0===l&&(r.gzindex=0,r.status=91)}else r.status=91;if(91===r.status)if(r.gzhead.comment){o=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>o&&(e.adler=a(e.adler,r.pending_buf,r.pending-o,o)),L(e),o=r.pending,r.pending===r.pending_buf_size)){l=1;break}l=r.gzindex<r.gzhead.comment.length?255&r.gzhead.comment.charCodeAt(r.gzindex++):0,O(r,l)}while(0!==l);r.gzhead.hcrc&&r.pending>o&&(e.adler=a(e.adler,r.pending_buf,r.pending-o,o)),0===l&&(r.status=103)}else r.status=103;if(103===r.status&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&L(e),r.pending+2<=r.pending_buf_size&&(O(r,255&e.adler),O(r,e.adler>>8&255),e.adler=0,r.status=N)):r.status=N),0!==r.pending){if(L(e),0===e.avail_out)return r.last_flush=-1,c}else if(0===e.avail_in&&I(t)<=I(s)&&t!==u)return B(e,-5);if(666===r.status&&0!==e.avail_in)return B(e,-5);if(0!==e.avail_in||0!==r.lookahead||t!==h&&666!==r.status){var m=2===r.strategy?function(e,t){for(var s;;){if(0===e.lookahead&&(k(e),0===e.lookahead)){if(t===h)return E;break}if(e.match_length=0,s=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,s&&(F(e,!1),0===e.strm.avail_out))return E}return e.insert=0,t===u?(F(e,!0),0===e.strm.avail_out?R:P):e.last_lit&&(F(e,!1),0===e.strm.avail_out)?E:C}(r,t):3===r.strategy?function(e,t){for(var s,i,r,o,a=e.window;;){if(e.lookahead<=S){if(k(e),e.lookahead<=S&&t===h)return E;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=T&&0<e.strstart&&(i=a[r=e.strstart-1])===a[++r]&&i===a[++r]&&i===a[++r]){o=e.strstart+S;do{}while(i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&r<o);e.match_length=S-(o-r),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=T?(s=n._tr_tally(e,1,e.match_length-T),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(s=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),s&&(F(e,!1),0===e.strm.avail_out))return E}return e.insert=0,t===u?(F(e,!0),0===e.strm.avail_out?R:P):e.last_lit&&(F(e,!1),0===e.strm.avail_out)?E:C}(r,t):i[r.level].func(r,t);if(m!==R&&m!==P||(r.status=666),m===E||m===R)return 0===e.avail_out&&(r.last_flush=-1),c;if(m===C&&(1===t?n._tr_align(r):5!==t&&(n._tr_stored_block(r,0,0,!1),3===t&&(D(r.head),0===r.lookahead&&(r.strstart=0,r.block_start=0,r.insert=0))),L(e),0===e.avail_out))return r.last_flush=-1,c}return t!==u?c:r.wrap<=0?1:(2===r.wrap?(O(r,255&e.adler),O(r,e.adler>>8&255),O(r,e.adler>>16&255),O(r,e.adler>>24&255),O(r,255&e.total_in),O(r,e.total_in>>8&255),O(r,e.total_in>>16&255),O(r,e.total_in>>24&255)):(V(r,e.adler>>>16),V(r,65535&e.adler)),L(e),0<r.wrap&&(r.wrap=-r.wrap),0!==r.pending?c:1)},s.deflateEnd=function(e){var t;return e&&e.state?(t=e.state.status)!==A&&69!==t&&73!==t&&91!==t&&103!==t&&t!==N&&666!==t?B(e,d):(e.state=null,t===N?B(e,-3):c):d},s.deflateSetDictionary=function(e,t){var s,i,n,a,l,h,u,p,m=t.length;if(!e||!e.state)return d;if(2===(a=(s=e.state).wrap)||1===a&&s.status!==A||s.lookahead)return d;for(1===a&&(e.adler=o(e.adler,t,m,0)),s.wrap=0,m>=s.w_size&&(0===a&&(D(s.head),s.strstart=0,s.block_start=0,s.insert=0),p=new r.Buf8(s.w_size),r.arraySet(p,t,m-s.w_size,s.w_size,0),t=p,m=s.w_size),l=e.avail_in,h=e.next_in,u=e.input,e.avail_in=m,e.next_in=0,e.input=t,k(s);s.lookahead>=T;){for(i=s.strstart,n=s.lookahead-(T-1);s.ins_h=(s.ins_h<<s.hash_shift^s.window[i+T-1])&s.hash_mask,s.prev[i&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=i,i++,--n;);s.strstart=i,s.lookahead=T-1,k(s)}return s.strstart+=s.lookahead,s.block_start=s.strstart,s.insert=s.lookahead,s.lookahead=0,s.match_length=s.prev_length=T-1,s.match_available=0,e.next_in=h,e.input=u,e.avail_in=l,s.wrap=a,c},s.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(e,t,s){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(e,t,s){t.exports=function(e,t){var s,i,r,n,o,a,l,h,u,c,d,p,m,f,g,y,x,b,_,w,v,T,S,M,A;s=e.state,i=e.next_in,M=e.input,r=i+(e.avail_in-5),n=e.next_out,A=e.output,o=n-(t-e.avail_out),a=n+(e.avail_out-257),l=s.dmax,h=s.wsize,u=s.whave,c=s.wnext,d=s.window,p=s.hold,m=s.bits,f=s.lencode,g=s.distcode,y=(1<<s.lenbits)-1,x=(1<<s.distbits)-1;e:do{m<15&&(p+=M[i++]<<m,m+=8,p+=M[i++]<<m,m+=8),b=f[p&y];t:for(;;){if(p>>>=_=b>>>24,m-=_,0==(_=b>>>16&255))A[n++]=65535&b;else{if(!(16&_)){if(!(64&_)){b=f[(65535&b)+(p&(1<<_)-1)];continue t}if(32&_){s.mode=12;break e}e.msg="invalid literal/length code",s.mode=30;break e}w=65535&b,(_&=15)&&(m<_&&(p+=M[i++]<<m,m+=8),w+=p&(1<<_)-1,p>>>=_,m-=_),m<15&&(p+=M[i++]<<m,m+=8,p+=M[i++]<<m,m+=8),b=g[p&x];s:for(;;){if(p>>>=_=b>>>24,m-=_,!(16&(_=b>>>16&255))){if(!(64&_)){b=g[(65535&b)+(p&(1<<_)-1)];continue s}e.msg="invalid distance code",s.mode=30;break e}if(v=65535&b,m<(_&=15)&&(p+=M[i++]<<m,(m+=8)<_&&(p+=M[i++]<<m,m+=8)),l<(v+=p&(1<<_)-1)){e.msg="invalid distance too far back",s.mode=30;break e}if(p>>>=_,m-=_,(_=n-o)<v){if(u<(_=v-_)&&s.sane){e.msg="invalid distance too far back",s.mode=30;break e}if(S=d,(T=0)===c){if(T+=h-_,_<w){for(w-=_;A[n++]=d[T++],--_;);T=n-v,S=A}}else if(c<_){if(T+=h+c-_,(_-=c)<w){for(w-=_;A[n++]=d[T++],--_;);if(T=0,c<w){for(w-=_=c;A[n++]=d[T++],--_;);T=n-v,S=A}}}else if(T+=c-_,_<w){for(w-=_;A[n++]=d[T++],--_;);T=n-v,S=A}for(;2<w;)A[n++]=S[T++],A[n++]=S[T++],A[n++]=S[T++],w-=3;w&&(A[n++]=S[T++],1<w&&(A[n++]=S[T++]))}else{for(T=n-v;A[n++]=A[T++],A[n++]=A[T++],A[n++]=A[T++],2<(w-=3););w&&(A[n++]=A[T++],1<w&&(A[n++]=A[T++]))}break}}break}}while(i<r&&n<a);i-=w=m>>3,p&=(1<<(m-=w<<3))-1,e.next_in=i,e.next_out=n,e.avail_in=i<r?r-i+5:5-(i-r),e.avail_out=n<a?a-n+257:257-(n-a),s.hold=p,s.bits=m}},{}],49:[function(e,t,s){var i=e("../utils/common"),r=e("./adler32"),n=e("./crc32"),o=e("./inffast"),a=e("./inftrees"),l=1,h=2,u=0,c=-2,d=1,p=852,m=592;function f(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function g(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new i.Buf16(320),this.work=new i.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function y(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=d,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new i.Buf32(p),t.distcode=t.distdyn=new i.Buf32(m),t.sane=1,t.back=-1,u):c}function x(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,y(e)):c}function b(e,t){var s,i;return e&&e.state?(i=e.state,t<0?(s=0,t=-t):(s=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t)?c:(null!==i.window&&i.wbits!==t&&(i.window=null),i.wrap=s,i.wbits=t,x(e))):c}function _(e,t){var s,i;return e?(i=new g,(e.state=i).window=null,(s=b(e,t))!==u&&(e.state=null),s):c}var w,v,T=!0;function S(e){if(T){var t;for(w=new i.Buf32(512),v=new i.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(a(l,e.lens,0,288,w,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;a(h,e.lens,0,32,v,0,e.work,{bits:5}),T=!1}e.lencode=w,e.lenbits=9,e.distcode=v,e.distbits=5}function M(e,t,s,r){var n,o=e.state;return null===o.window&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new i.Buf8(o.wsize)),r>=o.wsize?(i.arraySet(o.window,t,s-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(r<(n=o.wsize-o.wnext)&&(n=r),i.arraySet(o.window,t,s-r,n,o.wnext),(r-=n)?(i.arraySet(o.window,t,s-r,r,0),o.wnext=r,o.whave=o.wsize):(o.wnext+=n,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=n))),0}s.inflateReset=x,s.inflateReset2=b,s.inflateResetKeep=y,s.inflateInit=function(e){return _(e,15)},s.inflateInit2=_,s.inflate=function(e,t){var s,p,m,g,y,x,b,_,w,v,T,A,N,E,C,R,P,B,I,D,L,F,O,V,z=0,k=new i.Buf8(4),U=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return c;12===(s=e.state).mode&&(s.mode=13),y=e.next_out,m=e.output,b=e.avail_out,g=e.next_in,p=e.input,x=e.avail_in,_=s.hold,w=s.bits,v=x,T=b,F=u;e:for(;;)switch(s.mode){case d:if(0===s.wrap){s.mode=13;break}for(;w<16;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}if(2&s.wrap&&35615===_){k[s.check=0]=255&_,k[1]=_>>>8&255,s.check=n(s.check,k,2,0),w=_=0,s.mode=2;break}if(s.flags=0,s.head&&(s.head.done=!1),!(1&s.wrap)||(((255&_)<<8)+(_>>8))%31){e.msg="incorrect header check",s.mode=30;break}if(8!=(15&_)){e.msg="unknown compression method",s.mode=30;break}if(w-=4,L=8+(15&(_>>>=4)),0===s.wbits)s.wbits=L;else if(L>s.wbits){e.msg="invalid window size",s.mode=30;break}s.dmax=1<<L,e.adler=s.check=1,s.mode=512&_?10:12,w=_=0;break;case 2:for(;w<16;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}if(s.flags=_,8!=(255&s.flags)){e.msg="unknown compression method",s.mode=30;break}if(57344&s.flags){e.msg="unknown header flags set",s.mode=30;break}s.head&&(s.head.text=_>>8&1),512&s.flags&&(k[0]=255&_,k[1]=_>>>8&255,s.check=n(s.check,k,2,0)),w=_=0,s.mode=3;case 3:for(;w<32;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}s.head&&(s.head.time=_),512&s.flags&&(k[0]=255&_,k[1]=_>>>8&255,k[2]=_>>>16&255,k[3]=_>>>24&255,s.check=n(s.check,k,4,0)),w=_=0,s.mode=4;case 4:for(;w<16;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}s.head&&(s.head.xflags=255&_,s.head.os=_>>8),512&s.flags&&(k[0]=255&_,k[1]=_>>>8&255,s.check=n(s.check,k,2,0)),w=_=0,s.mode=5;case 5:if(1024&s.flags){for(;w<16;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}s.length=_,s.head&&(s.head.extra_len=_),512&s.flags&&(k[0]=255&_,k[1]=_>>>8&255,s.check=n(s.check,k,2,0)),w=_=0}else s.head&&(s.head.extra=null);s.mode=6;case 6:if(1024&s.flags&&(x<(A=s.length)&&(A=x),A&&(s.head&&(L=s.head.extra_len-s.length,s.head.extra||(s.head.extra=new Array(s.head.extra_len)),i.arraySet(s.head.extra,p,g,A,L)),512&s.flags&&(s.check=n(s.check,p,A,g)),x-=A,g+=A,s.length-=A),s.length))break e;s.length=0,s.mode=7;case 7:if(2048&s.flags){if(0===x)break e;for(A=0;L=p[g+A++],s.head&&L&&s.length<65536&&(s.head.name+=String.fromCharCode(L)),L&&A<x;);if(512&s.flags&&(s.check=n(s.check,p,A,g)),x-=A,g+=A,L)break e}else s.head&&(s.head.name=null);s.length=0,s.mode=8;case 8:if(4096&s.flags){if(0===x)break e;for(A=0;L=p[g+A++],s.head&&L&&s.length<65536&&(s.head.comment+=String.fromCharCode(L)),L&&A<x;);if(512&s.flags&&(s.check=n(s.check,p,A,g)),x-=A,g+=A,L)break e}else s.head&&(s.head.comment=null);s.mode=9;case 9:if(512&s.flags){for(;w<16;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}if(_!==(65535&s.check)){e.msg="header crc mismatch",s.mode=30;break}w=_=0}s.head&&(s.head.hcrc=s.flags>>9&1,s.head.done=!0),e.adler=s.check=0,s.mode=12;break;case 10:for(;w<32;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}e.adler=s.check=f(_),w=_=0,s.mode=11;case 11:if(0===s.havedict)return e.next_out=y,e.avail_out=b,e.next_in=g,e.avail_in=x,s.hold=_,s.bits=w,2;e.adler=s.check=1,s.mode=12;case 12:if(5===t||6===t)break e;case 13:if(s.last){_>>>=7&w,w-=7&w,s.mode=27;break}for(;w<3;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}switch(s.last=1&_,w-=1,3&(_>>>=1)){case 0:s.mode=14;break;case 1:if(S(s),s.mode=20,6!==t)break;_>>>=2,w-=2;break e;case 2:s.mode=17;break;case 3:e.msg="invalid block type",s.mode=30}_>>>=2,w-=2;break;case 14:for(_>>>=7&w,w-=7&w;w<32;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}if((65535&_)!=(_>>>16^65535)){e.msg="invalid stored block lengths",s.mode=30;break}if(s.length=65535&_,w=_=0,s.mode=15,6===t)break e;case 15:s.mode=16;case 16:if(A=s.length){if(x<A&&(A=x),b<A&&(A=b),0===A)break e;i.arraySet(m,p,g,A,y),x-=A,g+=A,b-=A,y+=A,s.length-=A;break}s.mode=12;break;case 17:for(;w<14;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}if(s.nlen=257+(31&_),_>>>=5,w-=5,s.ndist=1+(31&_),_>>>=5,w-=5,s.ncode=4+(15&_),_>>>=4,w-=4,286<s.nlen||30<s.ndist){e.msg="too many length or distance symbols",s.mode=30;break}s.have=0,s.mode=18;case 18:for(;s.have<s.ncode;){for(;w<3;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}s.lens[U[s.have++]]=7&_,_>>>=3,w-=3}for(;s.have<19;)s.lens[U[s.have++]]=0;if(s.lencode=s.lendyn,s.lenbits=7,O={bits:s.lenbits},F=a(0,s.lens,0,19,s.lencode,0,s.work,O),s.lenbits=O.bits,F){e.msg="invalid code lengths set",s.mode=30;break}s.have=0,s.mode=19;case 19:for(;s.have<s.nlen+s.ndist;){for(;R=(z=s.lencode[_&(1<<s.lenbits)-1])>>>16&255,P=65535&z,!((C=z>>>24)<=w);){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}if(P<16)_>>>=C,w-=C,s.lens[s.have++]=P;else{if(16===P){for(V=C+2;w<V;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}if(_>>>=C,w-=C,0===s.have){e.msg="invalid bit length repeat",s.mode=30;break}L=s.lens[s.have-1],A=3+(3&_),_>>>=2,w-=2}else if(17===P){for(V=C+3;w<V;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}w-=C,L=0,A=3+(7&(_>>>=C)),_>>>=3,w-=3}else{for(V=C+7;w<V;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}w-=C,L=0,A=11+(127&(_>>>=C)),_>>>=7,w-=7}if(s.have+A>s.nlen+s.ndist){e.msg="invalid bit length repeat",s.mode=30;break}for(;A--;)s.lens[s.have++]=L}}if(30===s.mode)break;if(0===s.lens[256]){e.msg="invalid code -- missing end-of-block",s.mode=30;break}if(s.lenbits=9,O={bits:s.lenbits},F=a(l,s.lens,0,s.nlen,s.lencode,0,s.work,O),s.lenbits=O.bits,F){e.msg="invalid literal/lengths set",s.mode=30;break}if(s.distbits=6,s.distcode=s.distdyn,O={bits:s.distbits},F=a(h,s.lens,s.nlen,s.ndist,s.distcode,0,s.work,O),s.distbits=O.bits,F){e.msg="invalid distances set",s.mode=30;break}if(s.mode=20,6===t)break e;case 20:s.mode=21;case 21:if(6<=x&&258<=b){e.next_out=y,e.avail_out=b,e.next_in=g,e.avail_in=x,s.hold=_,s.bits=w,o(e,T),y=e.next_out,m=e.output,b=e.avail_out,g=e.next_in,p=e.input,x=e.avail_in,_=s.hold,w=s.bits,12===s.mode&&(s.back=-1);break}for(s.back=0;R=(z=s.lencode[_&(1<<s.lenbits)-1])>>>16&255,P=65535&z,!((C=z>>>24)<=w);){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}if(R&&!(240&R)){for(B=C,I=R,D=P;R=(z=s.lencode[D+((_&(1<<B+I)-1)>>B)])>>>16&255,P=65535&z,!(B+(C=z>>>24)<=w);){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}_>>>=B,w-=B,s.back+=B}if(_>>>=C,w-=C,s.back+=C,s.length=P,0===R){s.mode=26;break}if(32&R){s.back=-1,s.mode=12;break}if(64&R){e.msg="invalid literal/length code",s.mode=30;break}s.extra=15&R,s.mode=22;case 22:if(s.extra){for(V=s.extra;w<V;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}s.length+=_&(1<<s.extra)-1,_>>>=s.extra,w-=s.extra,s.back+=s.extra}s.was=s.length,s.mode=23;case 23:for(;R=(z=s.distcode[_&(1<<s.distbits)-1])>>>16&255,P=65535&z,!((C=z>>>24)<=w);){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}if(!(240&R)){for(B=C,I=R,D=P;R=(z=s.distcode[D+((_&(1<<B+I)-1)>>B)])>>>16&255,P=65535&z,!(B+(C=z>>>24)<=w);){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}_>>>=B,w-=B,s.back+=B}if(_>>>=C,w-=C,s.back+=C,64&R){e.msg="invalid distance code",s.mode=30;break}s.offset=P,s.extra=15&R,s.mode=24;case 24:if(s.extra){for(V=s.extra;w<V;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}s.offset+=_&(1<<s.extra)-1,_>>>=s.extra,w-=s.extra,s.back+=s.extra}if(s.offset>s.dmax){e.msg="invalid distance too far back",s.mode=30;break}s.mode=25;case 25:if(0===b)break e;if(A=T-b,s.offset>A){if((A=s.offset-A)>s.whave&&s.sane){e.msg="invalid distance too far back",s.mode=30;break}N=A>s.wnext?(A-=s.wnext,s.wsize-A):s.wnext-A,A>s.length&&(A=s.length),E=s.window}else E=m,N=y-s.offset,A=s.length;for(b<A&&(A=b),b-=A,s.length-=A;m[y++]=E[N++],--A;);0===s.length&&(s.mode=21);break;case 26:if(0===b)break e;m[y++]=s.length,b--,s.mode=21;break;case 27:if(s.wrap){for(;w<32;){if(0===x)break e;x--,_|=p[g++]<<w,w+=8}if(T-=b,e.total_out+=T,s.total+=T,T&&(e.adler=s.check=s.flags?n(s.check,m,T,y-T):r(s.check,m,T,y-T)),T=b,(s.flags?_:f(_))!==s.check){e.msg="incorrect data check",s.mode=30;break}w=_=0}s.mode=28;case 28:if(s.wrap&&s.flags){for(;w<32;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}if(_!==(4294967295&s.total)){e.msg="incorrect length check",s.mode=30;break}w=_=0}s.mode=29;case 29:F=1;break e;case 30:F=-3;break e;case 31:return-4;default:return c}return e.next_out=y,e.avail_out=b,e.next_in=g,e.avail_in=x,s.hold=_,s.bits=w,(s.wsize||T!==e.avail_out&&s.mode<30&&(s.mode<27||4!==t))&&M(e,e.output,e.next_out,T-e.avail_out)?(s.mode=31,-4):(v-=e.avail_in,T-=e.avail_out,e.total_in+=v,e.total_out+=T,s.total+=T,s.wrap&&T&&(e.adler=s.check=s.flags?n(s.check,m,T,e.next_out-T):r(s.check,m,T,e.next_out-T)),e.data_type=s.bits+(s.last?64:0)+(12===s.mode?128:0)+(20===s.mode||15===s.mode?256:0),(0==v&&0===T||4===t)&&F===u&&(F=-5),F)},s.inflateEnd=function(e){if(!e||!e.state)return c;var t=e.state;return t.window&&(t.window=null),e.state=null,u},s.inflateGetHeader=function(e,t){var s;return e&&e.state&&2&(s=e.state).wrap?((s.head=t).done=!1,u):c},s.inflateSetDictionary=function(e,t){var s,i=t.length;return e&&e.state?0!==(s=e.state).wrap&&11!==s.mode?c:11===s.mode&&r(1,t,i,0)!==s.check?-3:M(e,t,i,i)?(s.mode=31,-4):(s.havedict=1,u):c},s.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(e,t,s){var i=e("../utils/common"),r=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],n=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],o=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,s,l,h,u,c,d){var p,m,f,g,y,x,b,_,w,v=d.bits,T=0,S=0,M=0,A=0,N=0,E=0,C=0,R=0,P=0,B=0,I=null,D=0,L=new i.Buf16(16),F=new i.Buf16(16),O=null,V=0;for(T=0;T<=15;T++)L[T]=0;for(S=0;S<l;S++)L[t[s+S]]++;for(N=v,A=15;1<=A&&0===L[A];A--);if(A<N&&(N=A),0===A)return h[u++]=20971520,h[u++]=20971520,d.bits=1,0;for(M=1;M<A&&0===L[M];M++);for(N<M&&(N=M),T=R=1;T<=15;T++)if(R<<=1,(R-=L[T])<0)return-1;if(0<R&&(0===e||1!==A))return-1;for(F[1]=0,T=1;T<15;T++)F[T+1]=F[T]+L[T];for(S=0;S<l;S++)0!==t[s+S]&&(c[F[t[s+S]]++]=S);if(x=0===e?(I=O=c,19):1===e?(I=r,D-=257,O=n,V-=257,256):(I=o,O=a,-1),T=M,y=u,C=S=B=0,f=-1,g=(P=1<<(E=N))-1,1===e&&852<P||2===e&&592<P)return 1;for(;;){for(b=T-C,w=c[S]<x?(_=0,c[S]):c[S]>x?(_=O[V+c[S]],I[D+c[S]]):(_=96,0),p=1<<T-C,M=m=1<<E;h[y+(B>>C)+(m-=p)]=b<<24|_<<16|w,0!==m;);for(p=1<<T-1;B&p;)p>>=1;if(0!==p?(B&=p-1,B+=p):B=0,S++,0==--L[T]){if(T===A)break;T=t[s+c[S]]}if(N<T&&(B&g)!==f){for(0===C&&(C=N),y+=M,R=1<<(E=T-C);E+C<A&&!((R-=L[E+C])<=0);)E++,R<<=1;if(P+=1<<E,1===e&&852<P||2===e&&592<P)return 1;h[f=B&g]=N<<24|E<<16|y-u}}return 0!==B&&(h[y+B]=T-C<<24|64<<16),d.bits=N,0}},{"../utils/common":41}],51:[function(e,t,s){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(e,t,s){var i=e("../utils/common"),r=0,n=1;function o(e){for(var t=e.length;0<=--t;)e[t]=0}var a=0,l=29,h=256,u=h+1+l,c=30,d=19,p=2*u+1,m=15,f=16,g=7,y=256,x=16,b=17,_=18,w=[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],v=[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],T=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],S=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],M=new Array(2*(u+2));o(M);var A=new Array(2*c);o(A);var N=new Array(512);o(N);var E=new Array(256);o(E);var C=new Array(l);o(C);var R,P,B,I=new Array(c);function D(e,t,s,i,r){this.static_tree=e,this.extra_bits=t,this.extra_base=s,this.elems=i,this.max_length=r,this.has_stree=e&&e.length}function L(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function F(e){return e<256?N[e]:N[256+(e>>>7)]}function O(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function V(e,t,s){e.bi_valid>f-s?(e.bi_buf|=t<<e.bi_valid&65535,O(e,e.bi_buf),e.bi_buf=t>>f-e.bi_valid,e.bi_valid+=s-f):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=s)}function z(e,t,s){V(e,s[2*t],s[2*t+1])}function k(e,t){for(var s=0;s|=1&e,e>>>=1,s<<=1,0<--t;);return s>>>1}function U(e,t,s){var i,r,n=new Array(m+1),o=0;for(i=1;i<=m;i++)n[i]=o=o+s[i-1]<<1;for(r=0;r<=t;r++){var a=e[2*r+1];0!==a&&(e[2*r]=k(n[a]++,a))}}function G(e){var t;for(t=0;t<u;t++)e.dyn_ltree[2*t]=0;for(t=0;t<c;t++)e.dyn_dtree[2*t]=0;for(t=0;t<d;t++)e.bl_tree[2*t]=0;e.dyn_ltree[2*y]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function j(e){8<e.bi_valid?O(e,e.bi_buf):0<e.bi_valid&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function $(e,t,s,i){var r=2*t,n=2*s;return e[r]<e[n]||e[r]===e[n]&&i[t]<=i[s]}function W(e,t,s){for(var i=e.heap[s],r=s<<1;r<=e.heap_len&&(r<e.heap_len&&$(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!$(t,i,e.heap[r],e.depth));)e.heap[s]=e.heap[r],s=r,r<<=1;e.heap[s]=i}function H(e,t,s){var i,r,n,o,a=0;if(0!==e.last_lit)for(;i=e.pending_buf[e.d_buf+2*a]<<8|e.pending_buf[e.d_buf+2*a+1],r=e.pending_buf[e.l_buf+a],a++,0===i?z(e,r,t):(z(e,(n=E[r])+h+1,t),0!==(o=w[n])&&V(e,r-=C[n],o),z(e,n=F(--i),s),0!==(o=v[n])&&V(e,i-=I[n],o)),a<e.last_lit;);z(e,y,t)}function q(e,t){var s,i,r,n=t.dyn_tree,o=t.stat_desc.static_tree,a=t.stat_desc.has_stree,l=t.stat_desc.elems,h=-1;for(e.heap_len=0,e.heap_max=p,s=0;s<l;s++)0!==n[2*s]?(e.heap[++e.heap_len]=h=s,e.depth[s]=0):n[2*s+1]=0;for(;e.heap_len<2;)n[2*(r=e.heap[++e.heap_len]=h<2?++h:0)]=1,e.depth[r]=0,e.opt_len--,a&&(e.static_len-=o[2*r+1]);for(t.max_code=h,s=e.heap_len>>1;1<=s;s--)W(e,n,s);for(r=l;s=e.heap[1],e.heap[1]=e.heap[e.heap_len--],W(e,n,1),i=e.heap[1],e.heap[--e.heap_max]=s,e.heap[--e.heap_max]=i,n[2*r]=n[2*s]+n[2*i],e.depth[r]=(e.depth[s]>=e.depth[i]?e.depth[s]:e.depth[i])+1,n[2*s+1]=n[2*i+1]=r,e.heap[1]=r++,W(e,n,1),2<=e.heap_len;);e.heap[--e.heap_max]=e.heap[1],function(e,t){var s,i,r,n,o,a,l=t.dyn_tree,h=t.max_code,u=t.stat_desc.static_tree,c=t.stat_desc.has_stree,d=t.stat_desc.extra_bits,f=t.stat_desc.extra_base,g=t.stat_desc.max_length,y=0;for(n=0;n<=m;n++)e.bl_count[n]=0;for(l[2*e.heap[e.heap_max]+1]=0,s=e.heap_max+1;s<p;s++)g<(n=l[2*l[2*(i=e.heap[s])+1]+1]+1)&&(n=g,y++),l[2*i+1]=n,h<i||(e.bl_count[n]++,o=0,f<=i&&(o=d[i-f]),a=l[2*i],e.opt_len+=a*(n+o),c&&(e.static_len+=a*(u[2*i+1]+o)));if(0!==y){do{for(n=g-1;0===e.bl_count[n];)n--;e.bl_count[n]--,e.bl_count[n+1]+=2,e.bl_count[g]--,y-=2}while(0<y);for(n=g;0!==n;n--)for(i=e.bl_count[n];0!==i;)h<(r=e.heap[--s])||(l[2*r+1]!==n&&(e.opt_len+=(n-l[2*r+1])*l[2*r],l[2*r+1]=n),i--)}}(e,t),U(n,h,e.bl_count)}function X(e,t,s){var i,r,n=-1,o=t[1],a=0,l=7,h=4;for(0===o&&(l=138,h=3),t[2*(s+1)+1]=65535,i=0;i<=s;i++)r=o,o=t[2*(i+1)+1],++a<l&&r===o||(a<h?e.bl_tree[2*r]+=a:0!==r?(r!==n&&e.bl_tree[2*r]++,e.bl_tree[2*x]++):a<=10?e.bl_tree[2*b]++:e.bl_tree[2*_]++,n=r,h=(a=0)===o?(l=138,3):r===o?(l=6,3):(l=7,4))}function Y(e,t,s){var i,r,n=-1,o=t[1],a=0,l=7,h=4;for(0===o&&(l=138,h=3),i=0;i<=s;i++)if(r=o,o=t[2*(i+1)+1],!(++a<l&&r===o)){if(a<h)for(;z(e,r,e.bl_tree),0!=--a;);else 0!==r?(r!==n&&(z(e,r,e.bl_tree),a--),z(e,x,e.bl_tree),V(e,a-3,2)):a<=10?(z(e,b,e.bl_tree),V(e,a-3,3)):(z(e,_,e.bl_tree),V(e,a-11,7));n=r,h=(a=0)===o?(l=138,3):r===o?(l=6,3):(l=7,4)}}o(I);var Z=!1;function Q(e,t,s,r){var n,o,l;V(e,(a<<1)+(r?1:0),3),o=t,l=s,j(n=e),O(n,l),O(n,~l),i.arraySet(n.pending_buf,n.window,o,l,n.pending),n.pending+=l}s._tr_init=function(e){Z||(function(){var e,t,s,i,r,n=new Array(m+1);for(i=s=0;i<l-1;i++)for(C[i]=s,e=0;e<1<<w[i];e++)E[s++]=i;for(E[s-1]=i,i=r=0;i<16;i++)for(I[i]=r,e=0;e<1<<v[i];e++)N[r++]=i;for(r>>=7;i<c;i++)for(I[i]=r<<7,e=0;e<1<<v[i]-7;e++)N[256+r++]=i;for(t=0;t<=m;t++)n[t]=0;for(e=0;e<=143;)M[2*e+1]=8,e++,n[8]++;for(;e<=255;)M[2*e+1]=9,e++,n[9]++;for(;e<=279;)M[2*e+1]=7,e++,n[7]++;for(;e<=287;)M[2*e+1]=8,e++,n[8]++;for(U(M,u+1,n),e=0;e<c;e++)A[2*e+1]=5,A[2*e]=k(e,5);R=new D(M,w,h+1,u,m),P=new D(A,v,0,c,m),B=new D(new Array(0),T,0,d,g)}(),Z=!0),e.l_desc=new L(e.dyn_ltree,R),e.d_desc=new L(e.dyn_dtree,P),e.bl_desc=new L(e.bl_tree,B),e.bi_buf=0,e.bi_valid=0,G(e)},s._tr_stored_block=Q,s._tr_flush_block=function(e,t,s,i){var o,a,l=0;0<e.level?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,s=4093624447;for(t=0;t<=31;t++,s>>>=1)if(1&s&&0!==e.dyn_ltree[2*t])return r;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return n;for(t=32;t<h;t++)if(0!==e.dyn_ltree[2*t])return n;return r}(e)),q(e,e.l_desc),q(e,e.d_desc),l=function(e){var t;for(X(e,e.dyn_ltree,e.l_desc.max_code),X(e,e.dyn_dtree,e.d_desc.max_code),q(e,e.bl_desc),t=d-1;3<=t&&0===e.bl_tree[2*S[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),o=e.opt_len+3+7>>>3,(a=e.static_len+3+7>>>3)<=o&&(o=a)):o=a=s+5,s+4<=o&&-1!==t?Q(e,t,s,i):4===e.strategy||a===o?(V(e,2+(i?1:0),3),H(e,M,A)):(V(e,4+(i?1:0),3),function(e,t,s,i){var r;for(V(e,t-257,5),V(e,s-1,5),V(e,i-4,4),r=0;r<i;r++)V(e,e.bl_tree[2*S[r]+1],3);Y(e,e.dyn_ltree,t-1),Y(e,e.dyn_dtree,s-1)}(e,e.l_desc.max_code+1,e.d_desc.max_code+1,l+1),H(e,e.dyn_ltree,e.dyn_dtree)),G(e),i&&j(e)},s._tr_tally=function(e,t,s){return e.pending_buf[e.d_buf+2*e.last_lit]=t>>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&s,e.last_lit++,0===t?e.dyn_ltree[2*s]++:(e.matches++,t--,e.dyn_ltree[2*(E[s]+h+1)]++,e.dyn_dtree[2*F(t)]++),e.last_lit===e.lit_bufsize-1},s._tr_align=function(e){var t;V(e,2,3),z(e,y,M),16===(t=e).bi_valid?(O(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):8<=t.bi_valid&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}},{"../utils/common":41}],53:[function(e,t,s){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(e,t,s){(function(e){!function(e,t){if(!e.setImmediate){var s,i,r,n,o=1,a={},l=!1,h=e.document,u=Object.getPrototypeOf&&Object.getPrototypeOf(e);u=u&&u.setTimeout?u:e,s="[object process]"==={}.toString.call(e.process)?function(e){process.nextTick(function(){d(e)})}:function(){if(e.postMessage&&!e.importScripts){var t=!0,s=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=s,t}}()?(n="setImmediate$"+Math.random()+"$",e.addEventListener?e.addEventListener("message",p,!1):e.attachEvent("onmessage",p),function(t){e.postMessage(n+t,"*")}):e.MessageChannel?((r=new MessageChannel).port1.onmessage=function(e){d(e.data)},function(e){r.port2.postMessage(e)}):h&&"onreadystatechange"in h.createElement("script")?(i=h.documentElement,function(e){var t=h.createElement("script");t.onreadystatechange=function(){d(e),t.onreadystatechange=null,i.removeChild(t),t=null},i.appendChild(t)}):function(e){setTimeout(d,0,e)},u.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),i=0;i<t.length;i++)t[i]=arguments[i+1];var r={callback:e,args:t};return a[o]=r,s(o),o++},u.clearImmediate=c}function c(e){delete a[e]}function d(e){if(l)setTimeout(d,0,e);else{var s=a[e];if(s){l=!0;try{!function(e){var s=e.callback,i=e.args;switch(i.length){case 0:s();break;case 1:s(i[0]);break;case 2:s(i[0],i[1]);break;case 3:s(i[0],i[1],i[2]);break;default:s.apply(t,i)}}(s)}finally{c(e),l=!1}}}}function p(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(n)&&d(+t.data.slice(n.length))}}("undefined"==typeof self?void 0===e?this:e:self)}).call(this,void 0!==IO?IO:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[10])(10));class VO{constructor(e,s){t(this,"date",new Date),t(this,"author"),t(this,"guid",w.create()),t(this,"viewpoint"),t(this,"modifiedAuthor"),t(this,"modifiedDate"),t(this,"topic"),t(this,"_components"),t(this,"_comment",""),this._components=e,this._comment=s;const i=this._components.get($O);this.author=i.config.author}set comment(e){var t;const s=this._components.get($O);this._comment=e,this.modifiedDate=new Date,this.modifiedAuthor=s.config.author,null==(t=this.topic)||t.comments.set(this.guid,this)}get comment(){return this._comment}toJSON(){var e,t;const s={guid:this.guid,date:this.date.toISOString(),author:this.author,comment:this.comment,topic_guid:null==(e=this.topic)?void 0:e.guid,viewpoint_guid:this.viewpoint,modified_date:null==(t=this.modifiedDate)?void 0:t.toISOString(),modified_author:this.modifiedAuthor};for(const[e,t]of Object.entries(s))void 0===t&&delete s[e];return s}}const zO=class e{constructor(i){t(this,"guid",w.create()),t(this,"title",e.default.title),t(this,"creationDate",new Date),t(this,"creationAuthor",""),t(this,"viewpoints",new s.DataSet),t(this,"relatedTopics",new s.DataSet),t(this,"comments",new s.DataMap),t(this,"documentReferences",new s.DataSet),t(this,"customData",{}),t(this,"description"),t(this,"serverAssignedId"),t(this,"dueDate"),t(this,"modifiedAuthor"),t(this,"modifiedDate"),t(this,"index"),t(this,"_type",e.default.type),t(this,"_status",e.default.status),t(this,"_priority",e.default.priority),t(this,"_stage",e.default.stage),t(this,"_assignedTo",e.default.assignedTo),t(this,"_labels",e.default.labels??new Set),t(this,"_components"),this._components=i;const r=i.get($O);this.creationAuthor=r.config.author,this.relatedTopics.guard=e=>e!==this.guid}set type(e){const t=this._components.get($O),{strict:s,types:i}=t.config;(!s||i.has(e))&&(this._type=e)}get type(){return this._type}set status(e){const t=this._components.get($O),{strict:s,statuses:i}=t.config;(!s||i.has(e))&&(this._status=e)}get status(){return this._status}set priority(e){const t=this._components.get($O);if(e){const{strict:s,priorities:i}=t.config;if(!(!s||i.has(e)))return;this._priority=e}else this._priority=e}get priority(){return this._priority}set stage(e){const t=this._components.get($O);if(e){const{strict:s,stages:i}=t.config;if(!(!s||i.has(e)))return;this._stage=e}else this._stage=e}get stage(){return this._stage}set assignedTo(e){const t=this._components.get($O);if(e){const{strict:s,users:i}=t.config;if(!(!s||i.has(e)))return;this._assignedTo=e}else this._assignedTo=e}get assignedTo(){return this._assignedTo}set labels(e){const t=this._components.get($O),{strict:s,labels:i}=t.config;if(s){const t=new Set;for(const r of e){(!s||i.has(r))&&t.add(r)}this._labels=t}else this._labels=e}get labels(){return this._labels}get _managerVersion(){return this._components.get($O).config.version}set(e){const t=e,s=this;for(const i in e){if("guid"===i)continue;const e=t[i];i in this&&(s[i]=e)}return this._components.get($O).list.set(this.guid,this),this}createComment(e,t){const s=new VO(this._components,e);return s.viewpoint=t,s.topic=this,this.comments.set(s.guid,s),s}createLabelTags(){const e=[...this.labels];if(this._components.get($O).config.exportCustomDataAsLabels)for(const t in this.customData){const s=this.customData[t];"string"==typeof s&&e.push(s)}return e}createCommentTags(){return[...this.comments.values()].map(e=>{var t;return{$Guid:e.guid,Date:e.date.toISOString(),Author:e.author,Comment:e.comment,ModifiedAuthor:e.modifiedAuthor,ModifiedDate:null==(t=e.modifiedDate)?void 0:t.toISOString(),Viewpoint:e.viewpoint?{$Guid:e.viewpoint}:void 0}})}createViewpointTags(){const e=this._components.get(PV);return[...this.viewpoints].map(t=>e.list.get(t)).filter(e=>e).map(t=>{const s={$Guid:t.guid,Viewpoint:`${t.title??t.guid}.bcfv`};if(e.snapshots.get(t.snapshot)){const i=e.getSnapshotExtension(t.snapshot);s.Snapshot=`${t.snapshot}.${i}`}return s})}createRelatedTopicTags(){return[...this.relatedTopics].map(e=>({$Guid:e}))}createDocumentReferencesTag(e=this._managerVersion){const t=[];if("3"!==e&&"2.1"!==e)return t;const s=this._components.get($O);for(const i of this.documentReferences){const r=s.documents.get(i);if(!r)continue;let n={$Guid:w.create(),Description:r.description};"2.1"===e&&(n={...n,$isExternal:"external"===r.type||void 0,ReferencedDocument:"external"===r.type?r.url:`../${r.fileName}`}),"3"===e&&(n={...n,DocumentGuid:"internal"===r.type?i:void 0,Url:"external"===r.type?r.url:void 0}),Object.keys(n).length>0&&t.push(n)}return t}toJSON(){var e,t;const s={guid:this.guid,server_assigned_id:this.serverAssignedId,topic_type:this.type,topic_status:this.status,title:this.title,priority:this.priority,index:this.index,labels:[...this.labels],creation_date:this.creationDate.toISOString(),creation_author:this.creationAuthor,modified_date:null==(e=this.modifiedDate)?void 0:e.toISOString(),modified_author:this.modifiedAuthor,assigned_to:this.assignedTo,stage:this.stage,description:this.description,due_date:null==(t=this.dueDate)?void 0:t.toISOString(),comments:[...this.comments].map(([e,t])=>t.toJSON()),relatedTopics:[...this.relatedTopics].map(e=>({related_topic_guid:e}))},i=this._components.get(PV);for(const e of this.viewpoints){const t=i.list.get(e);t&&(s.viewpoints||(s.viewpoints=[]),s.viewpoints.push(t.toJSON()))}const r=this._components.get($O);for(const e of this.documentReferences){const t=r.documents.get(e);t&&(s.document_references||(s.document_references=[]),"external"===t.type?s.document_references.push({guid:w.create(),description:t.description,url:t.url}):s.document_references.push({guid:w.create(),description:t.description,document_guid:e}))}for(const[e,t]of Object.entries(s))(void 0===t||Array.isArray(t)&&0===t.length)&&delete s[e];return s}serialize(){var e,t;const s=this._managerVersion,i={$Guid:this.guid,$TopicType:this.type,$TopicStatus:this.status,$ServerAssignedId:this.serverAssignedId,Title:this.title,CreationAuthor:this.creationAuthor,CreationDate:this.creationDate.toISOString(),Priority:this.priority,Index:"2.1"===s?this.index:void 0,ModifiedDate:null==(e=this.modifiedDate)?void 0:e.toISOString(),ModifiedAuthor:this.modifiedAuthor,DueDate:null==(t=this.dueDate)?void 0:t.toISOString(),AssignedTo:this.assignedTo,Description:this.description,Stage:this.stage,DocumentReferences:"3"===s?{DocumentReference:this.createDocumentReferencesTag(s)}:void 0,RelatedTopics:"3"===s?{RelatedTopic:this.createRelatedTopicTags()}:void 0,RelatedTopic:"2.1"===s?this.createRelatedTopicTags():void 0,Labels:"3"===s?{Label:this.createLabelTags()}:void 0,Viewpoints:"3"===s?{ViewPoint:this.createViewpointTags()}:void 0,Comments:"3"===s?{Comment:this.createCommentTags()}:void 0};"2.1"===s&&(i.Labels=this.createLabelTags(),i.DocumentReference=this.createDocumentReferencesTag(s));const r={Markup:{Topic:i}};return"2.1"===s&&(r.Markup.Viewpoints=this.createViewpointTags(),r.Markup.Comment=this.createCommentTags()),`<?xml version="1.0" encoding="UTF-8"?>\n ${Fe.builder.build(r)}`}};t(zO,"default",{title:"BCF Topic",type:"Issue",status:"Active"});let kO=zO;const UO=(e,t)=>{if(""===t.trim())return;const s=$O.xmlParser.parse(t).Extensions;if(!s)return;const{Priorities:i,TopicStatuses:r,TopicTypes:n,Users:o}=s;if(i&&i.Priority){const t=Array.isArray(i.Priority)?i.Priority:[i.Priority];for(const s of t)e.config.priorities.add(s)}if(r&&r.TopicStatus){const t=Array.isArray(r.TopicStatus)?r.TopicStatus:[r.TopicStatus];for(const s of t)e.config.statuses.add(s)}if(n&&n.TopicType){const t=Array.isArray(n.TopicType)?n.TopicType:[n.TopicType];for(const s of t)e.config.types.add(s)}if(o&&o.User){const t=Array.isArray(o.User)?o.User:[o.User];for(const s of t)e.config.users.add(s)}};class GO extends ke{constructor(){super(...arguments),t(this,"_config",{version:{type:"Select",options:new Set(["2.1","3"]),multiple:!1,value:""},author:{type:"Text",value:""},types:{type:"TextSet",value:new Set},statuses:{type:"TextSet",value:new Set},priorities:{type:"TextSet",value:new Set},labels:{type:"TextSet",value:new Set},stages:{type:"TextSet",value:new Set},users:{type:"TextSet",value:new Set},includeSelectionTag:{type:"Boolean",value:!1},updateExtensionsOnImport:{type:"Boolean",value:!1},strict:{type:"Boolean",value:!1},includeAllExtensionsOnExport:{type:"Boolean",value:!1},fallbackVersionOnImport:{type:"Select",multiple:!1,options:new Set(["2.1","3"]),value:""},ignoreIncompleteTopicsOnImport:{type:"Boolean",value:!1},exportCustomDataAsLabels:{type:"Boolean",value:!1}})}get version(){return this._config.version.value}set version(e){this._config.version.value=e}get author(){return this._config.author.value}set author(e){this._config.author.value=e}get types(){return this._config.types.value}set types(e){this._config.types.value=e}get statuses(){return this._config.statuses.value}set statuses(e){this._config.statuses.value=e}get priorities(){return this._config.priorities.value}set priorities(e){this._config.priorities.value=e}get labels(){return this._config.labels.value}set labels(e){this._config.labels.value=e}get stages(){return this._config.stages.value}set stages(e){this._config.stages.value=e}get users(){return this._config.users.value}set users(e){this._config.users.value=e}get includeSelectionTag(){return this._config.includeSelectionTag.value}set includeSelectionTag(e){this._config.includeSelectionTag.value=e}get updateExtensionsOnImport(){return this._config.updateExtensionsOnImport.value}set updateExtensionsOnImport(e){this._config.updateExtensionsOnImport.value=e}get strict(){return this._config.strict.value}set strict(e){this._config.strict.value=e}get includeAllExtensionsOnExport(){return this._config.includeAllExtensionsOnExport.value}set includeAllExtensionsOnExport(e){this._config.includeAllExtensionsOnExport.value=e}get fallbackVersionOnImport(){return this._config.fallbackVersionOnImport.value}set fallbackVersionOnImport(e){this._config.fallbackVersionOnImport.value=e}get ignoreIncompleteTopicsOnImport(){return this._config.ignoreIncompleteTopicsOnImport.value}set ignoreIncompleteTopicsOnImport(e){this._config.ignoreIncompleteTopicsOnImport.value=e}get exportCustomDataAsLabels(){return this._config.exportCustomDataAsLabels.value}set exportCustomDataAsLabels(e){this._config.exportCustomDataAsLabels.value=e}}const jO=class e extends d{constructor(){super(...arguments),t(this,"enabled",!1),t(this,"_defaultConfig",{author:"jhon.doe@example.com",version:"2.1",types:new Set(["Clash","Failure","Fault","Inquiry","Issue","Remark","Request"]),statuses:new Set(["Active","In Progress","Done","In Review","Closed"]),priorities:new Set(["On hold","Minor","Normal","Major","Critical"]),labels:new Set,stages:new Set,users:new Set,includeSelectionTag:!1,updateExtensionsOnImport:!0,strict:!1,includeAllExtensionsOnExport:!0,fallbackVersionOnImport:"2.1",ignoreIncompleteTopicsOnImport:!1,exportCustomDataAsLabels:!1}),t(this,"config",new GO(this,this.components,"BCF Topics",e.uuid)),t(this,"list",new s.DataMap),t(this,"documents",new s.DataMap),t(this,"onSetup",new u),t(this,"isSetup",!1),t(this,"onBCFImported",new u),t(this,"onDisposed",new u)}setup(e){if(this.isSetup)return;const t={...this._defaultConfig,...e};this.config.version=t.version,this.config.author=t.author,this.config.types=t.types,this.config.statuses=t.statuses,this.config.priorities=t.priorities,this.config.labels=t.labels,this.config.stages=t.stages,this.config.users=t.users,this.config.includeSelectionTag=t.includeSelectionTag,this.config.updateExtensionsOnImport=t.updateExtensionsOnImport,this.config.strict=t.strict,this.config.includeAllExtensionsOnExport=t.includeAllExtensionsOnExport,this.config.fallbackVersionOnImport=t.fallbackVersionOnImport||"",this.config.ignoreIncompleteTopicsOnImport=t.ignoreIncompleteTopicsOnImport,this.isSetup=!0,this.enabled=!0,this.onSetup.trigger()}create(e){const t=new kO(this.components);return e?(t.guid=e.guid??t.guid,t.set(e)):this.list.set(t.guid,t),t}dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}get usedTypes(){const e=[...this.list].map(([e,t])=>t.type);return new Set(e)}get usedStatuses(){const e=[...this.list].map(([e,t])=>t.status);return new Set(e)}get usedPriorities(){const e=[...this.list].map(([e,t])=>t.priority).filter(e=>e);return new Set(e)}get usedStages(){const e=[...this.list].map(([e,t])=>t.stage).filter(e=>e);return new Set(e)}get usedUsers(){const e=[];for(const[t,s]of this.list){e.push(s.creationAuthor),s.assignedTo&&e.push(s.assignedTo),s.modifiedAuthor&&e.push(s.modifiedAuthor);for(const[t,i]of s.comments)e.push(i.author),i.modifiedAuthor&&e.push(i.modifiedAuthor)}return new Set(e)}get usedLabels(){const e=[];for(const[t,s]of this.list)e.push(...s.labels);return new Set(e)}updateExtensions(){for(const[e,t]of this.list){for(const e of t.labels)this.config.labels.add(e);this.config.types.add(t.type),t.priority&&this.config.priorities.add(t.priority),t.stage&&this.config.stages.add(t.stage),this.config.statuses.add(t.status),this.config.users.add(t.creationAuthor),t.assignedTo&&this.config.users.add(t.assignedTo),t.modifiedAuthor&&this.config.users.add(t.modifiedAuthor);for(const[e,s]of t.comments)this.config.users.add(s.author),s.modifiedAuthor&&this.config.users.add(s.modifiedAuthor)}}updateViewpointReferences(){const e=this.components.get(PV);for(const[t,s]of this.list)for(const t of s.viewpoints){e.list.has(t)||s.viewpoints.delete(t)}}async export(e=this.list.values()){const t=new OO;t.file("bcf.version",`<?xml version="1.0" encoding="UTF-8"?>\n <Version VersionId="${this.config.version}" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/buildingSMART/BCF-XML/release_3_0/Schemas/version.xsd"\n xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n </Version>`);for(const[e,s]of this.documents.entries())"external"!==s.type&&t.file("2.1"===this.config.version?s.fileName:`documents/${e}`,s.data);if("3"===this.config.version){const e=[];for(const[t,s]of this.documents.entries()){const{type:i,description:r}=s;"external"!==i&&e.push(`<Document Guid="${t}">\n <Filename>${s.fileName}</Filename>\n ${r?`<Description>${r}</Description>`:""}\n </Document>`)}e.length>0&&t.file("documents.xml",`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n <DocumentInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="documents.xsd">\n <Documents>\n ${e.join("\n")}\n </Documents>\n </DocumentInfo>`)}t.file("bcf.extensions",this.serializeExtensions());const s=this.components.get(PV);for(const i of e){const e=t.folder(i.guid);e.file("markup.bcf",i.serialize());for(const t of i.viewpoints){const i=s.list.get(t);if(!i)continue;const r=i.title??i.guid;e.file(`${r}.bcfv`,await i.serialize());const n=s.snapshots.get(i.snapshot);if(!n)continue;const o=n?i.snapshot:i.guid,a=s.getSnapshotExtension(i.snapshot);e.file(`${o}.${a}`,n,{binary:!0})}}return await t.generateAsync({type:"blob"})}serializeExtensions(){const e=[...this.config.types].map(e=>`<TopicType>${e}</TopicType>`).join("\n"),t=[...this.config.statuses].map(e=>`<TopicStatus>${e}</TopicStatus>`).join("\n"),s=[...this.config.priorities].map(e=>`<Priority>${e}</Priority>`).join("\n"),i=[...this.config.labels].map(e=>`<TopicLabel>${e}</TopicLabel>`).join("\n"),r=[...this.config.stages].map(e=>`<Stage>${e}</Stage>`).join("\n"),n=[...this.config.users].map(e=>`<User>${e}</User>`).join("\n");return`\n <?xml version="1.0" encoding="UTF-8"?>\n <Extensions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="your-schema-location.xsd">\n ${0!==e.length?`<TopicTypes>\n${e}\n</TopicTypes>`:""}\n ${0!==t.length?`<TopicStatuses>\n${t}\n</TopicStatuses>`:""}\n ${0!==s.length?`<Priorities>\n${s}\n</Priorities>`:""}\n ${0!==i.length?`<TopicLabels>\n${i}\n</TopicLabels>`:""}\n ${0!==r.length?`<Stages>\n${r}\n</Stages>`:""}\n ${0!==n.length?`<Users>\n${n}\n</Users>`:""}\n </Extensions>\n `}processMarkupComment(e){const{Guid:t,Date:s,Author:i,Comment:r,Viewpoint:n}=e;if(!(t&&s&&i&&(VO||n)))return null;const o=new VO(this.components,r??"");return o.guid=t,o.date=new Date(s),o.author=i,o.viewpoint=null==n?void 0:n.Guid,o.modifiedAuthor=e.ModifiedAuthor,o.modifiedDate=e.ModifiedDate?new Date(e.ModifiedDate):void 0,o}getMarkupComments(e,t){var s;let i;if("2.1"===t&&(i=e.Comment),"3"===t&&(i=null==(s=e.Topic.Comments)?void 0:s.Comment),!i)return[];i=Array.isArray(i)?i:[i];const r=i.map(e=>this.processMarkupComment(e)).filter(e=>e);return Array.isArray(r)?r:[r]}getMarkupLabels(e,t){var s;let i;if("2.1"===t&&(i=e.Topic.Labels),"3"===t&&(i=null==(s=e.Topic.Labels)?void 0:s.Label),!i)return[];return Array.isArray(i)?i:[i]}getMarkupViewpoints(e,t){var s;let i;return"2.1"===t&&(i=e.Viewpoints),"3"===t&&(i=null==(s=e.Topic.Viewpoints)?void 0:s.ViewPoint),i?(i=Array.isArray(i)?i:[i],i):[]}getMarkupRelatedTopics(e,t){var s;let i;if("2.1"===t&&(i=e.Topic.RelatedTopic),"3"===t&&(i=null==(s=e.Topic.RelatedTopics)?void 0:s.RelatedTopic),!i)return[];return(Array.isArray(i)?i:[i]).map(e=>e.Guid)}getMarkupDocumentReferences(e,t){var s;let i;if("2.1"===t&&(i=e.Topic.DocumentReference),"3"===t&&(i=null==(s=e.Topic.DocumentReferences)?void 0:s.DocumentReference),!i)return[];return Array.isArray(i)?i:[i]}async load(t){var s,i,r;const{fallbackVersionOnImport:n,ignoreIncompleteTopicsOnImport:o,updateExtensionsOnImport:a}=this.config,h=new OO;await h.loadAsync(t);const u=Object.values(h.files);let c=n;const d=u.find(e=>e.name.endsWith(".version"));if(d){const t=await d.async("string"),s=e.xmlParser.parse(t).Version.VersionId;c=String(s)}if(!c||"2.1"!==c&&"3"!==c)throw new Error(`BCFTopics: ${c} is not supported.`);const p=u.find(e=>e.name.endsWith(".extensions"));if(a&&p){const e=await p.async("string");UO(this,e)}const m=[],f=this.components.get(PV),g=u.filter(e=>e.name.endsWith(".bcfv"));for(const t of g){const i=await t.async("string"),r=e.xmlParser.parse(i).VisualizationInfo;if(!r){console.warn("Missing VisualizationInfo in Viewpoint");continue}const n={},{Guid:o,ClippingPlanes:a,Components:h,OrthogonalCamera:u,PerspectiveCamera:d}=r;if(o&&(n.guid=o),h){const e={selection:[],coloring:[],visibility:{default_visibility:!1,exceptions:[],view_setup_hints:{spaces_visible:!1,space_boundaries_visible:!1,openings_visible:!1}}};n.components=e;const{Selection:t,Visibility:i}=h;if(t&&t.Component){const s=Array.isArray(t.Component)?t.Component:[t.Component];e.selection=s.map(e=>e.IfcGuid?{ifc_guid:e.IfcGuid}:null).filter(e=>null!==e)}if(i&&"DefaultVisibility"in i&&(e.visibility.default_visibility=i.DefaultVisibility),i&&i.Exceptions&&"Component"in i.Exceptions){const{Component:t}=i.Exceptions,s=Array.isArray(t)?t:[t];e.visibility.exceptions=s.map(e=>e.IfcGuid?{ifc_guid:e.IfcGuid}:null).filter(e=>null!==e)}let r;"2.1"===c&&(r=h.ViewSetupHints),"3"===c&&(r=null==(s=h.Visibility)?void 0:s.ViewSetupHints),r&&("OpeningsVisible"in r&&(e.visibility.view_setup_hints.openings_visible=r.OpeningsVisible),"SpacesVisible"in r&&(e.visibility.view_setup_hints.spaces_visible=r.SpacesVisible),"SpaceBoundariesVisible"in r&&(e.visibility.view_setup_hints.space_boundaries_visible=r.SpaceBoundariesVisible));const{Coloring:o}=h;if(o&&o.Color){const t=Array.isArray(o.Color)?o.Color:[o.Color];for(const s of t){const{Color:t,Component:i}=s;if(6!==t.length&&8!==t.length)continue;const r=6===t.length?t:t.slice(2),n=(Array.isArray(i)?i:[i]).map(e=>e.IfcGuid?{ifc_guid:e.IfcGuid}:null).filter(e=>null!==e);e.coloring.push({color:r,components:n})}}}if(u||d){const e=r.PerspectiveCamera??r.OrthogonalCamera,{CameraViewPoint:t,CameraDirection:s}=e,i=new l.Vector3(Number(t.X),Number(t.Z),Number(-t.Y)),o=new l.Vector3(Number(s.X),Number(s.Z),Number(-s.Y)),a={camera_view_point:{x:i.x,y:i.y,z:i.z},camera_direction:{x:o.x,y:o.y,z:o.z},aspect_ratio:"AspectRatio"in e?e.AspectRatio:1,camera_up_vector:{x:0,y:0,z:0}};"ViewToWorldScale"in e&&(n.orthogonal_camera={...a,view_to_world_scale:e.ViewToWorldScale}),"FieldOfView"in e&&(n.perspective_camera={...a,field_of_view:e.FieldOfView})}if(a){const e=(Array.isArray(a.ClippingPlane)?a.ClippingPlane:[a.ClippingPlane]).map(({Location:e,Direction:t})=>({location:{x:e.x,y:e.y,z:e.z},direction:{x:t.x,y:t.y,z:t.z}}));n.clipping_planes=e}const p=new EV(this.components,n);m.push(p)}const y={},x=[],b=u.filter(e=>e.name.endsWith(".bcf"));for(const t of b){const s=await t.async("string"),n=e.xmlParser.parse(s).Markup,a=n.Topic,{Guid:l,TopicType:h,TopicStatus:d,Title:p,CreationDate:m,CreationAuthor:g}=a;if(o&&!(l&&h&&d&&p&&m&&g))continue;const b=new kO(this.components);b.guid=l??b.guid;const _=this.getMarkupRelatedTopics(n,c);y[b.guid]=new Set(_),b.type=h??b.type,b.status=d??b.status,b.title=p??b.title,b.creationDate=m?new Date(m):b.creationDate,b.creationAuthor=g??b.creationAuthor,b.serverAssignedId=a.ServerAssignedId,b.priority=a.Priority,b.index=a.Index,b.modifiedDate=a.ModifiedDate?new Date(a.ModifiedDate):void 0,b.modifiedAuthor=a.ModifiedAuthor,b.dueDate=a.DueDate?new Date(a.DueDate):void 0,b.assignedTo=a.AssignedTo,b.description=a.Description,b.stage=a.Stage;const w=this.getMarkupLabels(n,c);for(const e of w)b.labels.add(e);const v=this.getMarkupComments(n,c);for(const e of v)b.comments.set(e.guid,e);const T=this.getMarkupViewpoints(n,c);for(const e of T){if(!e||!e.Guid)continue;const t=f.list.get(e.Guid);if(!t)continue;b.viewpoints.add(t.guid);const s=`${b.guid}/${e.Snapshot}`,i=u.find(({name:e})=>e===s);if(i){const e=await i.async("arraybuffer"),s=new Uint8Array(e);f.snapshots.set(t.guid,s),t.snapshot=t.guid??null}}const S=this.getMarkupDocumentReferences(n,c),M=u.find(e=>"documents.xml"===e.name);let A=[];const N=await(null==M?void 0:M.async("string"));if(N){const e=null==(r=null==(i=Fe.parser.parse(N).DocumentInfo)?void 0:i.Documents)?void 0:r.Document;A=Array.isArray(e)?e:[e]}for(const e of S){const{Description:t,DocumentGuid:s,Url:i,isExternal:r,ReferencedDocument:n}=e;if(s&&A.length>0){const e=A.find(({Guid:e})=>e===s),t=u.find(e=>e.name.endsWith(s)),i=await(null==t?void 0:t.async("uint8array"));if(!e||!i)continue;const{Description:r,Filename:n}=e;this.documents.set(s,{type:"internal",fileName:n,description:r,data:i}),b.documentReferences.add(s)}if(i){const e=this.documents.add({type:"external",url:i,description:t});b.documentReferences.add(e)}if(n){let e=null;if(r)e=this.documents.add({type:"external",url:n,description:t});else{const s=n.split("/"),i=s[s.length-1],r=u.find(e=>e.name.endsWith(i)),o=await(null==r?void 0:r.async("uint8array"));if(!o)continue;e=this.documents.add({type:"internal",fileName:i,data:o,description:t})}b.documentReferences.add(e)}}this.list.set(b.guid,b),x.push(b)}for(const e in y){const t=this.list.get(e);if(!t)continue;const s=y[e];for(const e of s)t.relatedTopics.add(e)}return this.onBCFImported.trigger(x),{viewpoints:m,topics:x}}};t(jO,"uuid","de977976-e4f6-4e4f-a01a-204727839802"),t(jO,"xmlParser",new Se({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0}));let $O=jO;const WO=new i.Raycaster,HO=new i.Vector3,qO=new i.Vector3,XO=new i.Quaternion,YO={X:new i.Vector3(1,0,0),Y:new i.Vector3(0,1,0),Z:new i.Vector3(0,0,1)},ZO={type:"change"},QO={type:"mouseDown",mode:null},KO={type:"mouseUp",mode:null},JO={type:"objectChange"};class eV extends i.Controls{constructor(e,t=null){super(void 0,t);const s=new wV(this);this._root=s;const r=new vV;this._gizmo=r,s.add(r);const n=new TV;this._plane=n,s.add(n);const o=this;function a(e,t){let s=t;Object.defineProperty(o,e,{get:function(){return void 0!==s?s:t},set:function(t){s!==t&&(s=t,n[e]=t,r[e]=t,o.dispatchEvent({type:e+"-changed",value:t}),o.dispatchEvent(ZO))}}),o[e]=t,n[e]=t,r[e]=t}a("camera",e),a("object",void 0),a("enabled",!0),a("axis",null),a("mode","translate"),a("translationSnap",null),a("rotationSnap",null),a("scaleSnap",null),a("space","world"),a("size",1),a("dragging",!1),a("showX",!0),a("showY",!0),a("showZ",!0),a("minX",-1/0),a("maxX",1/0),a("minY",-1/0),a("maxY",1/0),a("minZ",-1/0),a("maxZ",1/0);const l=new i.Vector3,h=new i.Vector3,u=new i.Quaternion,c=new i.Quaternion,d=new i.Vector3,p=new i.Quaternion,m=new i.Vector3,f=new i.Vector3,g=new i.Vector3,y=new i.Vector3;a("worldPosition",l),a("worldPositionStart",h),a("worldQuaternion",u),a("worldQuaternionStart",c),a("cameraPosition",d),a("cameraQuaternion",p),a("pointStart",m),a("pointEnd",f),a("rotationAxis",g),a("rotationAngle",0),a("eye",y),this._offset=new i.Vector3,this._startNorm=new i.Vector3,this._endNorm=new i.Vector3,this._cameraScale=new i.Vector3,this._parentPosition=new i.Vector3,this._parentQuaternion=new i.Quaternion,this._parentQuaternionInv=new i.Quaternion,this._parentScale=new i.Vector3,this._worldScaleStart=new i.Vector3,this._worldQuaternionInv=new i.Quaternion,this._worldScale=new i.Vector3,this._positionStart=new i.Vector3,this._quaternionStart=new i.Quaternion,this._scaleStart=new i.Vector3,this._getPointer=tV.bind(this),this._onPointerDown=iV.bind(this),this._onPointerHover=sV.bind(this),this._onPointerMove=rV.bind(this),this._onPointerUp=nV.bind(this),null!==t&&this.connect(t)}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointermove",this._onPointerHover),this.domElement.addEventListener("pointerup",this._onPointerUp),this.domElement.style.touchAction="none"}disconnect(){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.domElement.style.touchAction="auto"}getHelper(){return this._root}pointerHover(e){if(void 0===this.object||!0===this.dragging)return;null!==e&&WO.setFromCamera(e,this.camera);const t=oV(this._gizmo.picker[this.mode],WO);this.axis=t?t.object.name:null}pointerDown(e){if(void 0!==this.object&&!0!==this.dragging&&(null==e||0===e.button)&&null!==this.axis){null!==e&&WO.setFromCamera(e,this.camera);const t=oV(this._plane,WO,!0);t&&(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(t.point).sub(this.worldPositionStart)),this.dragging=!0,QO.mode=this.mode,this.dispatchEvent(QO)}}pointerMove(e){const t=this.axis,s=this.mode,i=this.object;let r=this.space;if("scale"===s?r="local":"E"!==t&&"XYZE"!==t&&"XYZ"!==t||(r="world"),void 0===i||null===t||!1===this.dragging||null!==e&&-1!==e.button)return;null!==e&&WO.setFromCamera(e,this.camera);const n=oV(this._plane,WO,!0);if(n){if(this.pointEnd.copy(n.point).sub(this.worldPositionStart),"translate"===s)this._offset.copy(this.pointEnd).sub(this.pointStart),"local"===r&&"XYZ"!==t&&this._offset.applyQuaternion(this._worldQuaternionInv),-1===t.indexOf("X")&&(this._offset.x=0),-1===t.indexOf("Y")&&(this._offset.y=0),-1===t.indexOf("Z")&&(this._offset.z=0),"local"===r&&"XYZ"!==t?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),i.position.copy(this._offset).add(this._positionStart),this.translationSnap&&("local"===r&&(i.position.applyQuaternion(XO.copy(this._quaternionStart).invert()),-1!==t.search("X")&&(i.position.x=Math.round(i.position.x/this.translationSnap)*this.translationSnap),-1!==t.search("Y")&&(i.position.y=Math.round(i.position.y/this.translationSnap)*this.translationSnap),-1!==t.search("Z")&&(i.position.z=Math.round(i.position.z/this.translationSnap)*this.translationSnap),i.position.applyQuaternion(this._quaternionStart)),"world"===r&&(i.parent&&i.position.add(HO.setFromMatrixPosition(i.parent.matrixWorld)),-1!==t.search("X")&&(i.position.x=Math.round(i.position.x/this.translationSnap)*this.translationSnap),-1!==t.search("Y")&&(i.position.y=Math.round(i.position.y/this.translationSnap)*this.translationSnap),-1!==t.search("Z")&&(i.position.z=Math.round(i.position.z/this.translationSnap)*this.translationSnap),i.parent&&i.position.sub(HO.setFromMatrixPosition(i.parent.matrixWorld)))),i.position.x=Math.max(this.minX,Math.min(this.maxX,i.position.x)),i.position.y=Math.max(this.minY,Math.min(this.maxY,i.position.y)),i.position.z=Math.max(this.minZ,Math.min(this.maxZ,i.position.z));else if("scale"===s){if(-1!==t.search("XYZ")){let e=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(e*=-1),qO.set(e,e,e)}else HO.copy(this.pointStart),qO.copy(this.pointEnd),HO.applyQuaternion(this._worldQuaternionInv),qO.applyQuaternion(this._worldQuaternionInv),qO.divide(HO),-1===t.search("X")&&(qO.x=1),-1===t.search("Y")&&(qO.y=1),-1===t.search("Z")&&(qO.z=1);i.scale.copy(this._scaleStart).multiply(qO),this.scaleSnap&&(-1!==t.search("X")&&(i.scale.x=Math.round(i.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),-1!==t.search("Y")&&(i.scale.y=Math.round(i.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),-1!==t.search("Z")&&(i.scale.z=Math.round(i.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if("rotate"===s){this._offset.copy(this.pointEnd).sub(this.pointStart);const e=20/this.worldPosition.distanceTo(HO.setFromMatrixPosition(this.camera.matrixWorld));let s=!1;"XYZE"===t?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(HO.copy(this.rotationAxis).cross(this.eye))*e):"X"!==t&&"Y"!==t&&"Z"!==t||(this.rotationAxis.copy(YO[t]),HO.copy(YO[t]),"local"===r&&HO.applyQuaternion(this.worldQuaternion),HO.cross(this.eye),0===HO.length()?s=!0:this.rotationAngle=this._offset.dot(HO.normalize())*e),("E"===t||s)&&(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),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),"local"===r&&"E"!==t&&"XYZE"!==t?(i.quaternion.copy(this._quaternionStart),i.quaternion.multiply(XO.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),i.quaternion.copy(XO.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),i.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(ZO),this.dispatchEvent(JO)}}pointerUp(e){null!==e&&0!==e.button||(this.dragging&&null!==this.axis&&(KO.mode=this.mode,this.dispatchEvent(KO)),this.dragging=!1,this.axis=null)}dispose(){this.disconnect(),this._root.dispose()}attach(e){return this.object=e,this._root.visible=!0,this}detach(){return this.object=void 0,this.axis=null,this._root.visible=!1,this}reset(){this.enabled&&this.dragging&&(this.object.position.copy(this._positionStart),this.object.quaternion.copy(this._quaternionStart),this.object.scale.copy(this._scaleStart),this.dispatchEvent(ZO),this.dispatchEvent(JO),this.pointStart.copy(this.pointEnd))}getRaycaster(){return WO}getMode(){return this.mode}setMode(e){this.mode=e}setTranslationSnap(e){this.translationSnap=e}setRotationSnap(e){this.rotationSnap=e}setScaleSnap(e){this.scaleSnap=e}setSize(e){this.size=e}setSpace(e){this.space=e}setColors(e,t,s,i){const r=this._gizmo.materialLib;r.xAxis.color.set(e),r.yAxis.color.set(t),r.zAxis.color.set(s),r.active.color.set(i),r.xAxisTransparent.color.set(e),r.yAxisTransparent.color.set(t),r.zAxisTransparent.color.set(s),r.activeTransparent.color.set(i),r.xAxis._color&&r.xAxis._color.set(e),r.yAxis._color&&r.yAxis._color.set(t),r.zAxis._color&&r.zAxis._color.set(s),r.active._color&&r.active._color.set(i),r.xAxisTransparent._color&&r.xAxisTransparent._color.set(e),r.yAxisTransparent._color&&r.yAxisTransparent._color.set(t),r.zAxisTransparent._color&&r.zAxisTransparent._color.set(s),r.activeTransparent._color&&r.activeTransparent._color.set(i)}}function tV(e){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:e.button};{const t=this.domElement.getBoundingClientRect();return{x:(e.clientX-t.left)/t.width*2-1,y:-(e.clientY-t.top)/t.height*2+1,button:e.button}}}function sV(e){if(this.enabled)switch(e.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(e))}}function iV(e){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(e.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(e)),this.pointerDown(this._getPointer(e)))}function rV(e){this.enabled&&this.pointerMove(this._getPointer(e))}function nV(e){this.enabled&&(this.domElement.releasePointerCapture(e.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(e)))}function oV(e,t,s){const i=t.intersectObject(e,!0);for(let e=0;e<i.length;e++)if(i[e].object.visible||s)return i[e];return!1}const aV=new i.Euler,lV=new i.Vector3(0,1,0),hV=new i.Vector3(0,0,0),uV=new i.Matrix4,cV=new i.Quaternion,dV=new i.Quaternion,pV=new i.Vector3,mV=new i.Matrix4,fV=new i.Vector3(1,0,0),gV=new i.Vector3(0,1,0),yV=new i.Vector3(0,0,1),xV=new i.Vector3,bV=new i.Vector3,_V=new i.Vector3;class wV extends i.Object3D{constructor(e){super(),this.isTransformControlsRoot=!0,this.controls=e,this.visible=!1}updateMatrixWorld(e){const t=this.controls;void 0!==t.object&&(t.object.updateMatrixWorld(),null===t.object.parent?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):t.object.parent.matrixWorld.decompose(t._parentPosition,t._parentQuaternion,t._parentScale),t.object.matrixWorld.decompose(t.worldPosition,t.worldQuaternion,t._worldScale),t._parentQuaternionInv.copy(t._parentQuaternion).invert(),t._worldQuaternionInv.copy(t.worldQuaternion).invert()),t.camera.updateMatrixWorld(),t.camera.matrixWorld.decompose(t.cameraPosition,t.cameraQuaternion,t._cameraScale),t.camera.isOrthographicCamera?t.camera.getWorldDirection(t.eye).negate():t.eye.copy(t.cameraPosition).sub(t.worldPosition).normalize(),super.updateMatrixWorld(e)}dispose(){this.traverse(function(e){e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()})}}class vV extends i.Object3D{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const e=new i.MeshBasicMaterial({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=new i.LineBasicMaterial({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),s=e.clone();s.opacity=.15;const r=t.clone();r.opacity=.5;const n=e.clone();n.color.setHex(16711680);const o=e.clone();o.color.setHex(65280);const a=e.clone();a.color.setHex(255);const l=e.clone();l.color.setHex(16711680),l.opacity=.5;const h=e.clone();h.color.setHex(65280),h.opacity=.5;const u=e.clone();u.color.setHex(255),u.opacity=.5;const c=e.clone();c.opacity=.25;const d=e.clone();d.color.setHex(16776960),d.opacity=.25;const p=e.clone();p.color.setHex(16776960);const m=e.clone();m.color.setHex(7895160),this.materialLib={xAxis:n,yAxis:o,zAxis:a,active:p,xAxisTransparent:l,yAxisTransparent:h,zAxisTransparent:u,activeTransparent:d};const f=new i.CylinderGeometry(0,.04,.1,12);f.translate(0,.05,0);const g=new i.BoxGeometry(.08,.08,.08);g.translate(0,.04,0);const y=new i.BufferGeometry;y.setAttribute("position",new i.Float32BufferAttribute([0,0,0,1,0,0],3));const x=new i.CylinderGeometry(.0075,.0075,.5,3);function b(e,t){const s=new i.TorusGeometry(e,.0075,3,64,t*Math.PI*2);return s.rotateY(Math.PI/2),s.rotateX(Math.PI/2),s}x.translate(0,.25,0);const _={X:[[new i.Mesh(f,n),[.5,0,0],[0,0,-Math.PI/2]],[new i.Mesh(f,n),[-.5,0,0],[0,0,Math.PI/2]],[new i.Mesh(x,n),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new i.Mesh(f,o),[0,.5,0]],[new i.Mesh(f,o),[0,-.5,0],[Math.PI,0,0]],[new i.Mesh(x,o)]],Z:[[new i.Mesh(f,a),[0,0,.5],[Math.PI/2,0,0]],[new i.Mesh(f,a),[0,0,-.5],[-Math.PI/2,0,0]],[new i.Mesh(x,a),null,[Math.PI/2,0,0]]],XYZ:[[new i.Mesh(new i.OctahedronGeometry(.1,0),c),[0,0,0]]],XY:[[new i.Mesh(new i.BoxGeometry(.15,.15,.01),u),[.15,.15,0]]],YZ:[[new i.Mesh(new i.BoxGeometry(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new i.Mesh(new i.BoxGeometry(.15,.15,.01),h),[.15,0,.15],[-Math.PI/2,0,0]]]},w={X:[[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[0,.3,0]],[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new i.Mesh(new i.OctahedronGeometry(.2,0),s)]],XY:[[new i.Mesh(new i.BoxGeometry(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new i.Mesh(new i.BoxGeometry(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new i.Mesh(new i.BoxGeometry(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]]},v={START:[[new i.Mesh(new i.OctahedronGeometry(.01,2),r),null,null,null,"helper"]],END:[[new i.Mesh(new i.OctahedronGeometry(.01,2),r),null,null,null,"helper"]],DELTA:[[new i.Line(function(){const e=new i.BufferGeometry;return e.setAttribute("position",new i.Float32BufferAttribute([0,0,0,1,1,1],3)),e}(),r),null,null,null,"helper"]],X:[[new i.Line(y,r),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new i.Line(y,r),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new i.Line(y,r),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},T={XYZE:[[new i.Mesh(b(.5,1),m),null,[0,Math.PI/2,0]]],X:[[new i.Mesh(b(.5,.5),n)]],Y:[[new i.Mesh(b(.5,.5),o),null,[0,0,-Math.PI/2]]],Z:[[new i.Mesh(b(.5,.5),a),null,[0,Math.PI/2,0]]],E:[[new i.Mesh(b(.75,1),d),null,[0,Math.PI/2,0]]]},S={AXIS:[[new i.Line(y,r),[-1e3,0,0],null,[1e6,1,1],"helper"]]},M={XYZE:[[new i.Mesh(new i.SphereGeometry(.25,10,8),s)]],X:[[new i.Mesh(new i.TorusGeometry(.5,.1,4,24),s),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new i.Mesh(new i.TorusGeometry(.5,.1,4,24),s),[0,0,0],[Math.PI/2,0,0]]],Z:[[new i.Mesh(new i.TorusGeometry(.5,.1,4,24),s),[0,0,0],[0,0,-Math.PI/2]]],E:[[new i.Mesh(new i.TorusGeometry(.75,.1,2,24),s)]]},A={X:[[new i.Mesh(g,n),[.5,0,0],[0,0,-Math.PI/2]],[new i.Mesh(x,n),[0,0,0],[0,0,-Math.PI/2]],[new i.Mesh(g,n),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new i.Mesh(g,o),[0,.5,0]],[new i.Mesh(x,o)],[new i.Mesh(g,o),[0,-.5,0],[0,0,Math.PI]]],Z:[[new i.Mesh(g,a),[0,0,.5],[Math.PI/2,0,0]],[new i.Mesh(x,a),[0,0,0],[Math.PI/2,0,0]],[new i.Mesh(g,a),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new i.Mesh(new i.BoxGeometry(.15,.15,.01),u),[.15,.15,0]]],YZ:[[new i.Mesh(new i.BoxGeometry(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new i.Mesh(new i.BoxGeometry(.15,.15,.01),h),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new i.Mesh(new i.BoxGeometry(.1,.1,.1),c)]]},N={X:[[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[0,.3,0]],[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new i.Mesh(new i.BoxGeometry(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new i.Mesh(new i.BoxGeometry(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new i.Mesh(new i.BoxGeometry(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new i.Mesh(new i.BoxGeometry(.2,.2,.2),s),[0,0,0]]]},E={X:[[new i.Line(y,r),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new i.Line(y,r),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new i.Line(y,r),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function C(e){const t=new i.Object3D;for(const s in e)for(let i=e[s].length;i--;){const r=e[s][i][0].clone(),n=e[s][i][1],o=e[s][i][2],a=e[s][i][3],l=e[s][i][4];r.name=s,r.tag=l,n&&r.position.set(n[0],n[1],n[2]),o&&r.rotation.set(o[0],o[1],o[2]),a&&r.scale.set(a[0],a[1],a[2]),r.updateMatrix();const h=r.geometry.clone();h.applyMatrix4(r.matrix),r.geometry=h,r.renderOrder=1/0,r.position.set(0,0,0),r.rotation.set(0,0,0),r.scale.set(1,1,1),t.add(r)}return t}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=C(_)),this.add(this.gizmo.rotate=C(T)),this.add(this.gizmo.scale=C(A)),this.add(this.picker.translate=C(w)),this.add(this.picker.rotate=C(M)),this.add(this.picker.scale=C(N)),this.add(this.helper.translate=C(v)),this.add(this.helper.rotate=C(S)),this.add(this.helper.scale=C(E)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(e){const t="local"===("scale"===this.mode?"local":this.space)?this.worldQuaternion:dV;this.gizmo.translate.visible="translate"===this.mode,this.gizmo.rotate.visible="rotate"===this.mode,this.gizmo.scale.visible="scale"===this.mode,this.helper.translate.visible="translate"===this.mode,this.helper.rotate.visible="rotate"===this.mode,this.helper.scale.visible="scale"===this.mode;let s=[];s=s.concat(this.picker[this.mode].children),s=s.concat(this.gizmo[this.mode].children),s=s.concat(this.helper[this.mode].children);for(let e=0;e<s.length;e++){const i=s[e];let r;if(i.visible=!0,i.rotation.set(0,0,0),i.position.copy(this.worldPosition),r=this.camera.isOrthographicCamera?(this.camera.top-this.camera.bottom)/this.camera.zoom:this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),i.scale.set(1,1,1).multiplyScalar(r*this.size/4),"helper"!==i.tag){if(i.quaternion.copy(t),"translate"===this.mode||"scale"===this.mode){const e=.99,s=.2;"X"===i.name&&Math.abs(lV.copy(fV).applyQuaternion(t).dot(this.eye))>e&&(i.scale.set(1e-10,1e-10,1e-10),i.visible=!1),"Y"===i.name&&Math.abs(lV.copy(gV).applyQuaternion(t).dot(this.eye))>e&&(i.scale.set(1e-10,1e-10,1e-10),i.visible=!1),"Z"===i.name&&Math.abs(lV.copy(yV).applyQuaternion(t).dot(this.eye))>e&&(i.scale.set(1e-10,1e-10,1e-10),i.visible=!1),"XY"===i.name&&Math.abs(lV.copy(yV).applyQuaternion(t).dot(this.eye))<s&&(i.scale.set(1e-10,1e-10,1e-10),i.visible=!1),"YZ"===i.name&&Math.abs(lV.copy(fV).applyQuaternion(t).dot(this.eye))<s&&(i.scale.set(1e-10,1e-10,1e-10),i.visible=!1),"XZ"===i.name&&Math.abs(lV.copy(gV).applyQuaternion(t).dot(this.eye))<s&&(i.scale.set(1e-10,1e-10,1e-10),i.visible=!1)}else"rotate"===this.mode&&(cV.copy(t),lV.copy(this.eye).applyQuaternion(XO.copy(t).invert()),-1!==i.name.search("E")&&i.quaternion.setFromRotationMatrix(uV.lookAt(this.eye,hV,gV)),"X"===i.name&&(XO.setFromAxisAngle(fV,Math.atan2(-lV.y,lV.z)),XO.multiplyQuaternions(cV,XO),i.quaternion.copy(XO)),"Y"===i.name&&(XO.setFromAxisAngle(gV,Math.atan2(lV.x,lV.z)),XO.multiplyQuaternions(cV,XO),i.quaternion.copy(XO)),"Z"===i.name&&(XO.setFromAxisAngle(yV,Math.atan2(lV.y,lV.x)),XO.multiplyQuaternions(cV,XO),i.quaternion.copy(XO)));i.visible=i.visible&&(-1===i.name.indexOf("X")||this.showX),i.visible=i.visible&&(-1===i.name.indexOf("Y")||this.showY),i.visible=i.visible&&(-1===i.name.indexOf("Z")||this.showZ),i.visible=i.visible&&(-1===i.name.indexOf("E")||this.showX&&this.showY&&this.showZ),i.material._color=i.material._color||i.material.color.clone(),i.material._opacity=i.material._opacity||i.material.opacity,i.material.color.copy(i.material._color),i.material.opacity=i.material._opacity,this.enabled&&this.axis&&(i.name===this.axis||this.axis.split("").some(function(e){return i.name===e}))&&(i.material.color.copy(this.materialLib.active.color),i.material.opacity=1)}else i.visible=!1,"AXIS"===i.name?(i.visible=!!this.axis,"X"===this.axis&&(XO.setFromEuler(aV.set(0,0,0)),i.quaternion.copy(t).multiply(XO),Math.abs(lV.copy(fV).applyQuaternion(t).dot(this.eye))>.9&&(i.visible=!1)),"Y"===this.axis&&(XO.setFromEuler(aV.set(0,0,Math.PI/2)),i.quaternion.copy(t).multiply(XO),Math.abs(lV.copy(gV).applyQuaternion(t).dot(this.eye))>.9&&(i.visible=!1)),"Z"===this.axis&&(XO.setFromEuler(aV.set(0,Math.PI/2,0)),i.quaternion.copy(t).multiply(XO),Math.abs(lV.copy(yV).applyQuaternion(t).dot(this.eye))>.9&&(i.visible=!1)),"XYZE"===this.axis&&(XO.setFromEuler(aV.set(0,Math.PI/2,0)),lV.copy(this.rotationAxis),i.quaternion.setFromRotationMatrix(uV.lookAt(hV,lV,gV)),i.quaternion.multiply(XO),i.visible=this.dragging),"E"===this.axis&&(i.visible=!1)):"START"===i.name?(i.position.copy(this.worldPositionStart),i.visible=this.dragging):"END"===i.name?(i.position.copy(this.worldPosition),i.visible=this.dragging):"DELTA"===i.name?(i.position.copy(this.worldPositionStart),i.quaternion.copy(this.worldQuaternionStart),HO.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),HO.applyQuaternion(this.worldQuaternionStart.clone().invert()),i.scale.copy(HO),i.visible=this.dragging):(i.quaternion.copy(t),this.dragging?i.position.copy(this.worldPositionStart):i.position.copy(this.worldPosition),this.axis&&(i.visible=-1!==this.axis.search(i.name)))}super.updateMatrixWorld(e)}}class TV extends i.Mesh{constructor(){super(new i.PlaneGeometry(1e5,1e5,2,2),new i.MeshBasicMaterial({visible:!1,wireframe:!0,side:i.DoubleSide,transparent:!0,opacity:.1,toneMapped:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(e){let t=this.space;switch(this.position.copy(this.worldPosition),"scale"===this.mode&&(t="local"),xV.copy(fV).applyQuaternion("local"===t?this.worldQuaternion:dV),bV.copy(gV).applyQuaternion("local"===t?this.worldQuaternion:dV),_V.copy(yV).applyQuaternion("local"===t?this.worldQuaternion:dV),lV.copy(bV),this.mode){case"translate":case"scale":switch(this.axis){case"X":lV.copy(this.eye).cross(xV),pV.copy(xV).cross(lV);break;case"Y":lV.copy(this.eye).cross(bV),pV.copy(bV).cross(lV);break;case"Z":lV.copy(this.eye).cross(_V),pV.copy(_V).cross(lV);break;case"XY":pV.copy(_V);break;case"YZ":pV.copy(xV);break;case"XZ":lV.copy(_V),pV.copy(bV);break;case"XYZ":case"E":pV.set(0,0,0)}break;default:pV.set(0,0,0)}0===pV.length()?this.quaternion.copy(this.cameraQuaternion):(mV.lookAt(HO.set(0,0,0),pV,lV),this.quaternion.setFromRotationMatrix(mV)),super.updateMatrixWorld(e)}}class SV{constructor(e,s,i,r,n,o=5,a=!0){var h;if(t(this,"onDraggingStarted",new u),t(this,"onDraggingEnded",new u),t(this,"onDisposed",new u),t(this,"normal"),t(this,"origin"),t(this,"three",new l.Plane),t(this,"components"),t(this,"world"),t(this,"type","default"),t(this,"_title","Clipping Plane"),t(this,"_helper"),t(this,"_visible",!0),t(this,"_enabled",!0),t(this,"_controlsActive",!1),t(this,"_arrowBoundBox",new l.Mesh),t(this,"_planeMesh"),t(this,"_controls"),t(this,"_hiddenMaterial",new l.MeshBasicMaterial({visible:!1})),t(this,"_sizeMultiplier",5),t(this,"_autoScale",!0),t(this,"_visibilityBeforeDisabled",!0),t(this,"notifyManager",()=>{const e=this.components.get(NV),t=e.list.getKey(this);t&&e.list.set(t,this)}),t(this,"update",()=>{this._enabled&&(this.three.setFromNormalAndCoplanarPoint(this.normal,this._helper.position),this.updateScale())}),t(this,"updateScale",()=>{var e;if(!this.autoScale)return;const t=null==(e=this.world.camera)?void 0:e.three;if(!t)return;if(!(t instanceof l.PerspectiveCamera))return;const s=new l.Vector3;t.getWorldPosition(s);const i=s.distanceTo(this._helper.position)/7*this._sizeMultiplier;this._planeMesh.scale.set(i,i,i)}),t(this,"changeDrag",e=>{this._visible=!e.value,this.preventCameraMovement(),this.notifyDraggingChanged(e)}),this.components=e,this.world=s,!s.renderer)throw new Error("The given world must have a renderer!");this.normal=r,this.origin=i,this._sizeMultiplier=o,s.renderer.setPlane(!0,this.three),this._planeMesh=SV.newPlaneMesh(o,n),this._helper=this.newHelper(),this._controls=this.newTransformControls(),this.three.setFromNormalAndCoplanarPoint(r,i),a&&this.toggleControls(!0),this.updateScale(),(null==(h=s.camera)?void 0:h.controls)&&s.camera.controls.addEventListener("update",this.updateScale)}set title(e){this._title=e,this.notifyManager()}get title(){return this._title}get autoScale(){return this._autoScale}set autoScale(e){this._autoScale=e,e&&this.updateScale()}get enabled(){return this._enabled}set enabled(e){if(!this.world.isDisposing){if(!this.world.renderer)throw new Error("No renderer found for clipping plane!");this._enabled=e,e?this.visible=this._visibilityBeforeDisabled:(this._visibilityBeforeDisabled=this.visible,this.visible=!1),this.world.renderer.setPlane(e,this.three),this.notifyManager()}}get visible(){return this._visible}set visible(e){this._visible=e,this._controls.getHelper().visible=e,this._helper.visible=e,this.toggleControls(e),this.notifyManager()}get meshes(){return[this._planeMesh,this._arrowBoundBox]}get planeMaterial(){return this._planeMesh.material}set planeMaterial(e){this._planeMesh.material=e}get size(){return this._sizeMultiplier}set size(e){this._sizeMultiplier=e,this.autoScale?this.updateScale():this._planeMesh.scale.set(e,e,e)}get helper(){return this._helper}get controls(){return this._controls}setFromNormalAndCoplanarPoint(e,t){this.reset(),this.normal.equals(e)||(this.normal.copy(e),this._helper.lookAt(e)),this.origin.copy(t),this._helper.position.copy(t),this._helper.updateMatrix(),this.update()}dispose(){var e;this._enabled=!1,(null==(e=this.world.camera)?void 0:e.controls)&&this.world.camera.controls.removeEventListener("update",this.updateScale),this.onDraggingStarted.reset(),this.onDraggingEnded.reset(),this._helper.removeFromParent(),this.world.renderer&&this.world.renderer.setPlane(!1,this.three),this._arrowBoundBox.removeFromParent(),this._arrowBoundBox.geometry.dispose(),this._planeMesh.geometry.dispose(),this._controls.getHelper().removeFromParent(),this._controls.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}reset(){const e=new l.Vector3(1,0,0),t=new l.Vector3;this.normal.equals(e)||(this.normal.copy(e),this._helper.lookAt(e)),this.origin.copy(t),this._helper.position.copy(t),this._helper.updateMatrix()}toggleControls(e){if(e){if(this._controlsActive)return;this._controls.addEventListener("change",this.update),this._controls.addEventListener("dragging-changed",this.changeDrag)}else this._controls.removeEventListener("change",this.update),this._controls.removeEventListener("dragging-changed",this.changeDrag);this._controlsActive=e}newTransformControls(){if(!this.world.renderer)throw new Error("No renderer found for clipping plane!");const e=this.world.camera.three,t=this.world.renderer.three.domElement,s=new eV(e,t);return this.initializeControls(s),this.world.scene.three.add(s.getHelper()),s}initializeControls(e){e.attach(this._helper),e.showX=!1,e.showY=!1,e.setSpace("local"),this.createArrowBoundingBox(),e.getHelper().children[0].children[0].add(this._arrowBoundBox)}createArrowBoundingBox(){this._arrowBoundBox.geometry=new l.CylinderGeometry(.18,.18,1.2),this._arrowBoundBox.material=this._hiddenMaterial,this._arrowBoundBox.rotateX(Math.PI/2),this._arrowBoundBox.updateMatrix(),this._arrowBoundBox.geometry.applyMatrix4(this._arrowBoundBox.matrix)}notifyDraggingChanged(e){e.value?this.onDraggingStarted.trigger():this.onDraggingEnded.trigger()}preventCameraMovement(){this.world.camera.enabled=this._visible}newHelper(){const e=new l.Object3D;return e.lookAt(this.normal),e.position.copy(this.origin),this._planeMesh.position.z+=.01,e.add(this._planeMesh),this.world.scene.three.add(e),e}static newPlaneMesh(e,t){const s=new l.PlaneGeometry(1),i=new l.Mesh(s,t);return i.scale.set(e,e,e),i}}class MV extends ke{constructor(){super(...arguments),t(this,"_config",{enabled:{value:!0,type:"Boolean"},visible:{value:!0,type:"Boolean"},color:{value:new l.Color,type:"Color"},opacity:{type:"Number",interpolable:!0,value:1,min:0,max:1},size:{type:"Number",interpolable:!0,value:2,min:0,max:100}})}get enabled(){return this._config.enabled.value}set enabled(e){this._config.enabled.value=e,this._component.enabled=e}get visible(){return this._config.visible.value}set visible(e){this._config.visible.value=e,this._component.visible=e}get color(){return this._config.color.value}set color(e){this._config.color.value=e,this._component.material.color.copy(e)}get opacity(){return this._config.opacity.value}set opacity(e){this._config.opacity.value=e,this._component.material.opacity=e}get size(){return this._config.size.value}set size(e){this._config.size.value=e,this._component.size=e}}const AV=class e extends d{constructor(s){super(s),t(this,"onSetup",new u),t(this,"onBeforeDrag",new u),t(this,"onAfterDrag",new u),t(this,"onBeforeCreate",new u),t(this,"onBeforeCancel",new u),t(this,"onAfterCancel",new u),t(this,"onBeforeDelete",new u),t(this,"onAfterCreate",new u),t(this,"onAfterDelete",new u),t(this,"onDisposed",new u),t(this,"isSetup",!1),t(this,"orthogonalY",!1),t(this,"toleranceOrthogonalY",.7),t(this,"autoScalePlanes",!0),t(this,"Type",SV),t(this,"list",new a.DataMap),t(this,"config",new MV(this,this.components,"Clipper",e.uuid)),t(this,"_defaultConfig",{color:new l.Color(12255487),opacity:.2,size:2}),t(this,"_material",new l.MeshBasicMaterial({color:12255487,side:l.DoubleSide,transparent:!0,opacity:.2})),t(this,"_size",5),t(this,"_enabled",!1),t(this,"_visible",!0),t(this,"onStateChanged",new u),this.components.add(e.uuid,this),this.setEvents()}get enabled(){return this._enabled}set enabled(e){this._enabled=e,this.onStateChanged.trigger(["enabled"])}get visible(){return this._visible}set visible(e){this._visible=e;for(const[t,s]of this.list)s.visible=e;this.onStateChanged.trigger(["visibility"])}get material(){return this._material}set material(e){this._material=e;for(const[t,s]of this.list)s.planeMaterial=e;this.onStateChanged.trigger(["material"])}get size(){return this._size}set size(e){this._size=e;for(const[t,s]of this.list)s.size=e;this.onStateChanged.trigger(["size"])}setEvents(){this.list.onBeforeDelete.add(({value:e})=>{if(!e.world.renderer)throw new Error("Renderer not found for this plane's world!");e.world.renderer.setPlane(!1,e.three),e.dispose(),this.updateMaterialsAndPlanes(),this.onAfterDelete.trigger(e)})}dispose(){this._enabled=!1;this.components.get(Ge).list.delete(this.config.uuid),this.list.clear(),this._material.dispose(),this.onBeforeCreate.reset(),this.onBeforeCancel.reset(),this.onBeforeDelete.reset(),this.onBeforeDrag.reset(),this.onAfterCreate.reset(),this.onAfterCancel.reset(),this.onAfterDelete.reset(),this.onAfterDrag.reset(),this.onDisposed.trigger(e.uuid),this.onDisposed.reset()}async create(e){const t=this.components.get(dO).get(e),s=await t.castRay();return s?this.createPlaneFromIntersection(e,s):null}createFromNormalAndCoplanarPoint(e,t,s){const i=this.newPlane(e,s,t);return this.updateMaterialsAndPlanes(),i}async delete(e,t){if(!t){const s=await this.pickPlane(e);if(!s)return;t=this.list.getKey(s)}t&&this.list.delete(t)}deleteAll(e){for(const[t,s]of this.list)e&&!e.has(s.type)||this.list.delete(t)}setup(e){const t={...this._defaultConfig,...e};this.config.color=t.color,this.config.opacity=t.opacity,this.config.size=t.size,this.isSetup=!0,this.onSetup.trigger()}pickPlane(e){const t=this.components.get(dO).get(e),s=this.getAllPlaneMeshes(),i=t.castRayToObjects(s);if(i){const e=i.object;return[...this.list.values()].find(t=>t.meshes.includes(e))}}getAllPlaneMeshes(){const e=[];for(const[t,s]of this.list)e.push(...s.meshes);return e}createPlaneFromIntersection(e,t){var s;if(!e.renderer)throw new Error("The given world must have a renderer!");const i=t.point.distanceTo(new l.Vector3(0,0,0)),r=t.normal||(null==(s=t.face)?void 0:s.normal);if(!i||!r)return null;const n=this.getWorldNormal(t,r),o=this.newPlane(e,t.point,n.negate()),a=this.list.get(o);return a.visible=this._visible,a.size=this._size,e.renderer.setPlane(!0,a.three),this.updateMaterialsAndPlanes(),a}getWorldNormal(e,t){const s=e.object;let i=e.object.matrixWorld.clone();if(s instanceof l.InstancedMesh&&void 0!==e.instanceId){const t=new l.Matrix4;s.getMatrixAt(e.instanceId,t),i=t.multiply(i)}const r=(new l.Matrix3).getNormalMatrix(i),n=t.clone().applyMatrix3(r).normalize();return this.normalizePlaneDirectionY(n),n}normalizePlaneDirectionY(e){this.orthogonalY&&(e.y>this.toleranceOrthogonalY&&(e.x=0,e.y=1,e.z=0),e.y<-this.toleranceOrthogonalY&&(e.x=0,e.y=-1,e.z=0))}newPlane(e,t,s){const i=new this.Type(this.components,e,t,s,this._material);i.autoScale=this.autoScalePlanes,i.onDraggingStarted.add(()=>this.onBeforeDrag.trigger(i)),i.onDraggingEnded.add(()=>this.onAfterDrag.trigger(i));const r=w.create();return this.list.set(r,i),this.onAfterCreate.trigger(i),r}updateMaterialsAndPlanes(){const e=this.components.get(wO);for(const[t,s]of e.list){if(!s.renderer)continue;s.renderer.updateClippingPlanes();const{clippingPlanes:e}=s.renderer;for(const t of s.meshes)if(t.material)if(Array.isArray(t.material))for(const s of t.material)s.clippingPlanes=e;else t.material.clippingPlanes=e}}};t(AV,"uuid","66290bc5-18c4-4cd1-9379-2e17a0617611");let NV=AV;class EV{constructor(e,s){t(this,"title"),t(this,"guid",w.create()),t(this,"clippingPlanes",new a.DataSet),t(this,"camera",{aspect_ratio:1,field_of_view:60,camera_direction:{x:0,y:0,z:0},camera_view_point:{x:0,y:0,z:0},camera_up_vector:{x:0,y:1,z:0}}),t(this,"customData",{}),t(this,"exceptionComponents",new a.DataSet),t(this,"selectionComponents",new a.DataSet),t(this,"componentColors",new a.DataMap),t(this,"spacesVisible",!1),t(this,"spaceBoundariesVisible",!1),t(this,"openingsVisible",!1),t(this,"defaultVisibility",!0),t(this,"snapshot",this.guid),t(this,"_components"),t(this,"_world",null),t(this,"notifyUpdate",()=>{this._components.get(PV).list.set(this.guid,this)}),this._components=e,s&&(this.guid=s.guid??this.guid,this.set(s)),this.setEvents()}async getSelectionMap(){const e=this._components.get(ji);return await e.guidsToModelIdMap([...this.selectionComponents])}async getExceptionMap(){const e=this._components.get(ji);return await e.guidsToModelIdMap([...this.exceptionComponents])}get projection(){return"field_of_view"in this.camera?"Perspective":"Orthographic"}get position(){const e=this._components.get(ji),{camera_view_point:t}=this.camera,{x:s,y:i,z:r}=t,n=new l.Vector3(s,i,r);return e.applyBaseCoordinateSystem(n,new l.Matrix4),n}set position(e){const t=e.clone(),s=this._components.get(ji);e.clone().applyMatrix4(s.baseCoordinationMatrix.clone().invert()),this.camera.camera_view_point={x:t.x,y:t.y,z:t.z}}get direction(){const{camera_direction:e}=this.camera,{x:t,y:s,z:i}=e;return new l.Vector3(t,s,i)}set world(e){this._world=e}get world(){return this._world}get _managerVersion(){return this._components.get($O).config.version}get topics(){return[...this._components.get($O).list.values()].filter(e=>e.viewpoints.has(this.guid))}setEvents(){this.selectionComponents.onUpdated.add(this.notifyUpdate),this.exceptionComponents.onUpdated.add(this.notifyUpdate),this.clippingPlanes.onUpdated.add(this.notifyUpdate),this.componentColors.onItemSet.add(this.notifyUpdate),this.componentColors.onItemDeleted.add(this.notifyUpdate),this.componentColors.onItemUpdated.add(this.notifyUpdate),this.componentColors.onCleared.add(this.notifyUpdate)}set(e){this.title=e.title;const{components:t,perspective_camera:s,orthogonal_camera:i,clipping_planes:r}=e;if(t){const{selection:e,visibility:s,coloring:i}=t;if(e){this.selectionComponents.clear();for(const{ifc_guid:t}of e)t&&this.selectionComponents.add(t)}if(s){const{default_visibility:e,exceptions:t,view_setup_hints:i}=s;if(void 0!==e&&(this.defaultVisibility=e),t){this.exceptionComponents.clear();for(const{ifc_guid:e}of t)e&&this.exceptionComponents.add(e)}if(i){const{spaces_visible:e,space_boundaries_visible:t,openings_visible:s}=i;void 0!==e&&(this.spacesVisible=e),void 0!==t&&(this.spaceBoundariesVisible=t),void 0!==s&&(this.openingsVisible=s)}}if(i){this.componentColors.clear();for(const e of i){const{color:t,components:s}=e,i=s.map(e=>e.ifc_guid).filter(e=>null!==e);this.componentColors.set(t,i)}}}if((s||i)&&(this.camera=s??i),r&&this.world){const e=this._components.get(NV);for(const t of r){const{location:s,direction:i}=t,r=new l.Vector3(s.x,s.z,-s.y),n=new l.Vector3(i.x,i.z,-i.y),o=e.createFromNormalAndCoplanarPoint(this.world,n,r);this.clippingPlanes.add(o),e.list.get(o).enabled=!1,e.list.get(o).visible=!1}}this.notifyUpdate()}async go(e){if(!this.world)return;const{camera:t}=this.world;if(!(t instanceof BO))throw new Error("Viewpoint: the world's camera component must be of type OrthoPerspectiveCamera to switch between perspective and orthographic projections.");const{transition:s,applyClippings:i,applyVisibility:r,clippingsVisibility:n}={transition:!0,applyClippings:!0,applyVisibility:!0,clippingsVisibility:!0,...e};t.projection.set(this.projection);const o=new l.Vector3(this.camera.camera_view_point.x,this.camera.camera_view_point.y,this.camera.camera_view_point.z),a=new l.Vector3(this.camera.camera_direction.x,this.camera.camera_direction.y,this.camera.camera_direction.z);if(o.equals(new l.Vector3)&&a.equals(new l.Vector3))return;const h=this.position,u=this.direction,c={x:h.x+80*u.x,y:h.y+80*u.y,z:h.z+80*u.z},d=[];i&&this.setClippingState(!0),r&&d.push(this.applyVisibility()),this.setClippingVisibility(n),d.push(t.controls.setLookAt(h.x,h.y,h.z,c.x,c.y,c.z,s)),await Promise.all(d)}async updateCamera(e=!0){return new Promise(t=>{if(!this.world)return void t(!1);const{camera:s,renderer:i}=this.world;if(!i)throw new Error("Viewpoint: the world needs to have a renderer!");if(!s.hasCameraControls())throw new Error("Viewpoint: world's camera need camera controls!");const r=new l.Vector3;s.controls.getPosition(r);const n=s.three,o=new l.Vector3(0,0,-1).applyEuler(n.rotation),{width:a,height:h}=i.getSize();let u=a/h;Number.isNaN(u)&&(u=1);const c=this._components.get(ji);r.applyMatrix4(c.baseCoordinationMatrix.clone().invert());const d={aspect_ratio:u,camera_view_point:{x:r.x,y:r.y,z:r.z},camera_direction:{x:o.x,y:o.y,z:o.z},camera_up_vector:{x:0,y:1,z:0}};if(n instanceof l.PerspectiveCamera?this.camera={...d,field_of_view:n.fov}:n instanceof l.OrthographicCamera&&(this.camera={...d,view_to_world_scale:n.top-n.bottom}),e){const e=this._components.get(PV),r=i.three.domElement;i.three.render(this.world.scene.three,s.three),r.toBlob(async s=>{if(s){const t=await s.arrayBuffer(),i=new Uint8Array(t);e.snapshots.set(this.guid,i)}this.notifyUpdate(),t(!0)})}else this.notifyUpdate(),t(!0)})}takeSnapshot(){return new Promise(e=>{if(!this.world)return void e(!1);const{camera:t,renderer:s}=this.world;if(!s)throw new Error("Viewpoint: the world needs to have a renderer!");const i=this._components.get(PV),r=s.three.domElement;s.three.render(this.world.scene.three,t.three),r.toBlob(async t=>{if(t){const e=await t.arrayBuffer(),s=new Uint8Array(e);i.snapshots.set(this.guid,s)}this.notifyUpdate(),e(!0)})})}updateClippingPlanes(){this.clippingPlanes.clear();const e=this._components.get(NV);for(const[t,s]of e.list)s.enabled&&this.clippingPlanes.add(t)}async applyVisibility(){const e=this._components.get(JF);e.set(this.defaultVisibility);const t=await this.getExceptionMap();e.set(!this.defaultVisibility,t);const s=await this.getSelectionMap();e.set(!0,s)}async setColorizationState(e){const t=this._components.get(ji),s=[];if(e)for(const[e,i]of this.componentColors){const r=`#${e}`,n=await t.guidsToModelIdMap(i);for(const[e,i]of Object.entries(n)){const n=t.list.get(e);n&&s.push(n.highlight([...i],{customId:r,color:new l.Color(r),renderedFaces:a.RenderedFaces.ONE,opacity:1,transparent:!1}))}}else for(const[e,i]of this.componentColors){const e=await t.guidsToModelIdMap(i);for(const[i,r]of Object.entries(e)){const e=t.list.get(i);e&&s.push(e.resetHighlight([...r]))}}s.push(t.core.update(!0)),await Promise.all(s)}setClippingState(e){const t=this._components.get(NV);for(const[s,i]of t.list)i.enabled=e&&this.clippingPlanes.has(s)}setClippingVisibility(e){const t=this._components.get(NV);for(const s of this.clippingPlanes){const i=t.list.get(s);i&&(i.visible=e)}}async createComponentTags(e){var t;const s=this._components.get(ji);let i="";if(this._components.get($O).config.includeSelectionTag){const r="selection"===e?await this.getSelectionMap():await this.getExceptionMap();for(const e in r){const n=s.list.get(e);if(!n)continue;const o=r[e];for(const e of o){const s=n.getItem(e),r=await s.getGuid();if(!r)continue;const o=null==(t=await s.getAttributes())?void 0:t.getValue("Tag");let a=null;o&&(a=`AuthoringToolId="${o}"`),i+=`\n<Component IfcGuid="${r}" ${a??""} />`}}}else i=[...this.selectionComponents].map(e=>`<Component IfcGuid="${e}" />`).join("\n");return i}createColorTags(){let e="";for(const[t,s]of this.componentColors.entries()){e+=`<Color Color="${t}">\n${s.map(e=>`\n<Component IfcGuid="${e}" />`).join("\n")}\n</Color>`}return 0!==e.length?`<Coloring>\n${e}\n</Coloring>`:"<Coloring />"}toJSON(){const e=this._components.get(NV),t={guid:this.guid,components:{selection:[...this.selectionComponents].map(e=>({ifc_guid:e,authoring_tool_id:null})),coloring:[...this.componentColors].map(([e,t])=>({color:e,components:t.map(e=>({ifc_guid:e,authoring_tool_id:null}))})),visibility:{default_visibility:this.defaultVisibility,exceptions:[...this.exceptionComponents].map(e=>({ifc_guid:e,authoring_tool_id:null})),view_setup_hints:{spaces_visible:this.spacesVisible,space_boundaries_visible:this.spaceBoundariesVisible,openings_visible:this.openingsVisible}}},clipping_planes:[...this.clippingPlanes].map(t=>{const s=e.list.get(t);if(!s)return null;const i=s._controls.worldPosition??s.origin,{normal:r}=s;return{location:{x:i.x,y:-i.z,z:i.y},direction:{x:r.x,y:-r.z,z:r.y}}}).filter(e=>null!==e)};"field_of_view"in this.camera?t.perspective_camera=this.camera:t.orthogonal_camera=this.camera;const s=this._components.get(PV),i=s.snapshots.get(this.snapshot);if(i){const e=i.toString(),r=btoa(e),n=s.getSnapshotExtension(this.snapshot);t.snapshot={snapshot_type:n,snapshot_data:r}}return t}async serialize(e=this._managerVersion){const t=this._components.get(ji),s=this.position;s.applyMatrix4(t.baseCoordinationMatrix.clone().invert());const i=this.direction;i.normalize();const r=(new l.Matrix4).makeRotationX(Math.PI/2),n=i.clone().applyMatrix4(r);n.normalize();const o=`<CameraViewPoint>\n <X>${s.x}</X>\n <Y>${-s.z}</Y>\n <Z>${s.y}</Z>\n </CameraViewPoint>`,a=`<CameraDirection>\n <X>${i.x}</X>\n <Y>${-i.z}</Y>\n <Z>${i.y}</Z>\n </CameraDirection>`,h=`<CameraUpVector>\n <X>${n.x}</X>\n <Y>${-n.z}</Y>\n <Z>${n.y}</Z>\n </CameraUpVector>`,u=`<AspectRatio>${this.camera.aspect_ratio}</AspectRatio>`;let c="";"view_to_world_scale"in this.camera?c=`<OrthogonalCamera>\n ${o}\n ${a}\n ${h}\n ${u}\n <ViewToWorldScale>${this.camera.view_to_world_scale}</ViewToWorldScale>\n </OrthogonalCamera>`:"field_of_view"in this.camera&&(c=`<PerspectiveCamera>\n ${o}\n ${a}\n ${h}\n ${u}\n <FieldOfView>${this.camera.field_of_view}</FieldOfView>\n </PerspectiveCamera>`);const d=`<ViewSetupHints SpacesVisible="${this.spacesVisible??!1}" SpaceBoundariesVisible="${this.spaceBoundariesVisible??!1}" OpeningsVisible="${this.openingsVisible??!1}" />`,p=(await this.createComponentTags("selection")).trim(),m=(await this.createComponentTags("exception")).trim(),f=this.createColorTags();return`<?xml version="1.0" encoding="UTF-8"?>\n <VisualizationInfo Guid="${this.guid}">\n <Components>\n ${"2.1"===e?d:""}\n ${0!==p.length?`<Selection>${p}</Selection>`:""}\n <Visibility DefaultVisibility="${this.defaultVisibility}">\n ${"3"===e?d:""}\n ${0!==m.length?`<Exceptions>${m}</Exceptions>`:""}\n </Visibility>\n ${f}\n </Components>\n ${c}\n </VisualizationInfo>`}}class CV extends ke{constructor(){super(...arguments),t(this,"_config",{overwriteColors:{value:!1,type:"Boolean"}})}get overwriteColors(){return this._config.overwriteColors.value}set overwriteColors(e){this._config.overwriteColors.value=e}}const RV=class e extends d{constructor(i){super(i),t(this,"enabled",!0),t(this,"world",null),t(this,"list",new s.DataMap),t(this,"snapshots",new s.DataMap),t(this,"isSetup",!1),t(this,"onSetup",new u),t(this,"config",new CV(this,this.components,"Viewpoints",e.uuid)),t(this,"onDisposed",new u),i.add(e.uuid,this)}create(e){const t=new EV(this.components,e);return t.world=this.world,e||this.list.set(t.guid,t),t}getSnapshotExtension(e){let t="jpeg";const s=this.snapshots.get(e);if(!s)return t;const i=s.subarray(0,4);let r="";for(let e=0;e<i.length;e++)r+=i[e].toString(16);return r.startsWith("89504e47")&&(t="png"),r.startsWith("ffd8ffe")&&(t="jpeg"),t}setup(){}dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}};t(RV,"uuid","ee867824-a796-408d-8aa0-4e5962a83c66");let PV=RV;class BV{constructor(e,s){t(this,"_components"),t(this,"_cameraOffset",10),t(this,"_planeHelper"),t(this,"_farPlaneHelper"),t(this,"_cameraHelper"),t(this,"onStateChanged",new u),t(this,"onUpdated",new u),t(this,"onDisposed",new u),t(this,"camera"),t(this,"plane",new l.Plane),t(this,"farPlane",new l.Plane),t(this,"id",w.create()),t(this,"_open",!1),t(this,"_range",DV.defaultRange),t(this,"_world",null),t(this,"_helpersVisible",!1),t(this,"_planesEnabled",!1),this._components=e,this.camera=new BO(this._components);const{threeOrtho:i}=this.camera;if((null==s?void 0:s.id)&&(this.id=s.id),(null==s?void 0:s.normal)&&(null==s?void 0:s.point)){const{normal:e,point:t}=s;this.plane.setFromNormalAndCoplanarPoint(e,t)}this._cameraHelper=new l.CameraHelper(i),this._planeHelper=new l.PlaneHelper(this.plane,50),this._farPlaneHelper=new l.PlaneHelper(this.farPlane,50),this.farPlaneHelperColor=new l.Color("blue"),this.update()}get _planeNormalOpposite(){return this.plane.normal.clone().negate()}get _planePosition(){return this.plane.normal.clone().multiplyScalar(-this.plane.constant)}get _cameraPosition(){return this._planePosition.addScaledVector(this._planeNormalOpposite,this._cameraOffset)}set open(e){this._open=e,this.onStateChanged.trigger(["open"])}get open(){return this._open}set planeHelperColor(e){!Array.isArray(this._planeHelper.material)&&"color"in this._planeHelper.material&&this._planeHelper.material.color instanceof l.Color&&(this._planeHelper.material.color=e)}set farPlaneHelperColor(e){!Array.isArray(this._farPlaneHelper.material)&&"color"in this._farPlaneHelper.material&&this._farPlaneHelper.material.color instanceof l.Color&&(this._farPlaneHelper.material.color=e)}set range(e){this._range=e,this.update()}get range(){return this._range}set distance(e){this.plane.constant=e,this.update()}get distance(){return this.plane.constant}set world(e){this._world=e,this.camera.currentWorld=e,e&&(this.camera.projection.set("Orthographic"),this.camera.set("Plan"),this.camera.controls.dollySpeed=6,this.camera.controls.restThreshold=.005,this.update())}get world(){return this._world}set helpersVisible(e){if(!e)return this._helpersVisible=e,this._planeHelper.removeFromParent(),this._farPlaneHelper.removeFromParent(),void this._cameraHelper.removeFromParent();this.world&&(this._helpersVisible=e,this.world.scene.three.add(this._planeHelper,this._farPlaneHelper))}get helpersVisible(){return this._helpersVisible}set planesEnabled(e){const{world:t}=this;if(!t)return;const{renderer:s}=t;s&&(s.setPlane(e,this.plane),s.setPlane(e,this.farPlane),this._planesEnabled=e)}get planesEnabled(){return this._planesEnabled}dispose(){this.helpersVisible=!1;const e=this._components.get(y);e.destroy(this._planeHelper),e.destroy(this._farPlaneHelper),e.destroy(this._cameraHelper),this.camera.dispose(),this.onDisposed.trigger()}update(){if(this.world){const e=this._cameraPosition,t=this._planePosition;this.camera.controls.setLookAt(e.x,e.y,e.z,t.x,t.y,t.z,!1)}this.farPlane.normal.copy(this._planeNormalOpposite),this.farPlane.constant=this.range-this.plane.constant,this.onUpdated.trigger()}flip(){this.plane.normal.negate(),this.update()}}const IV=class e extends d{constructor(i){super(i),t(this,"list",new s.DataMap),t(this,"enabled",!0),t(this,"world",null),t(this,"_fragmentsUpdateEvent",()=>{this.components.get(ji).core.update(!0)}),i.add(e.uuid,this),this.setupEvents()}get hasOpenViews(){return[...this.list.values()].some(e=>e.open)}setupEvents(){this.list.onBeforeDelete.add(({key:e,value:t})=>{t.open&&this.close(e),t.dispose()})}create(e,t,s){const i=new BV(this.components,{id:null==s?void 0:s.id,normal:e,point:t});return i.world=(null==s?void 0:s.world)??this.world,this.list.set(i.id,i),i}createFromPlane(e,t){const s=new BV(this.components,{id:null==t?void 0:t.id});return s.plane.copy(e),s.update(),s.world=(null==t?void 0:t.world)??this.world,this.list.set(s.id,s),s}async createFromIfcStoreys(e){const t=[],s=this.components.get(ji),i=void 0===(null==e?void 0:e.offset)?.25:e.offset;for(const[r,n]of s.list){if(e&&e.modelIds&&!e.modelIds.some(e=>e.test(r)))continue;const s=Object.values(await n.getItemsOfCategories([/BUILDINGSTOREY/])).flat();if(0===s.length)continue;const o=await n.getItemsData(s),[,a]=await n.getCoordinates(),h=new l.Vector3(0,-1,0);for(const s of o){if(!("value"in s.Name)||!("value"in s.Elevation))continue;const{value:r}=s.Name;if((null==e?void 0:e.storeyNames)&&!e.storeyNames.some(e=>e.test(r)))continue;const n=s.Elevation.value+a+i,o=new l.Plane(h,n),u=this.createFromPlane(o,{id:r,world:null==e?void 0:e.world});t.push(u)}}return t}createElevations(e){const t=[],s=this.components.get(ji),i=void 0!==(null==e?void 0:e.combine)&&e.combine,r=(null==e?void 0:e.namingCallback)??(e=>({front:""+(i?"Front":`${e}: Front`),back:""+(i?"Back":`${e}: Back`),left:""+(i?"Left":`${e}: Left`),right:""+(i?"Right":`${e}: Right`)}));let n=[];for(const[t,i]of s.list)e&&e.modelIds&&!e.modelIds.some(e=>e.test(t))||n.push({id:t,box:i.box});if(0===n.length)return t;if(i){const e=this.components.get(tO);e.list.clear(),e.list.add(...n.map(e=>e.box));n=[{id:"combined",box:e.get()}]}for(const{id:s,box:i}of n){const{min:n,max:o}=i,a=Math.abs(o.x-n.x),h=Math.abs(o.z-n.z),u=new l.Vector3;i.getCenter(u);const c=new l.Plane(new l.Vector3(0,0,-1),o.z),d=new l.Plane(new l.Vector3(0,0,1),-n.z),p=new l.Plane(new l.Vector3(-1,0,0),o.x),m=new l.Plane(new l.Vector3(1,0,0),-n.x),{front:f,back:g,left:y,right:x}=r(s),b=this.createFromPlane(c,{id:f,world:null==e?void 0:e.world});b.range=h;const _=this.createFromPlane(d,{id:g,world:null==e?void 0:e.world});_.range=h;const w=this.createFromPlane(p,{id:y,world:null==e?void 0:e.world});w.range=a;const v=this.createFromPlane(m,{id:x,world:null==e?void 0:e.world});v.range=a,t.push(b,_,w,v)}return t}open(e){const t=this.list.get(e);if(!t)throw new Error(`Views: the view with id ${e} doesn't exist.`);if(t.open)return;const{world:s}=t;if(!s)throw new Error(`Views: no world found for view with id ${e}.`);const{renderer:i}=s;if(!i)throw new Error(`Views: no renderer found for world with id ${s.uuid}.`);for(const[,e]of this.list)e.world===s&&this.close(e.id);i.setPlane(!0,t.plane),i.setPlane(!0,t.farPlane),t.camera.controls.addEventListener("rest",this._fragmentsUpdateEvent),s.camera=t.camera,t.open=!0}close(e){let t;if(t=e?this.list.get(e):[...this.list.values()].find(e=>e.open),e&&!t)throw new Error(`Views: the view with id ${e} doesn't exist.`);if(!t)return;if(!t.open)return;const{world:s}=t;if(!s)throw new Error(`Views: no world found for view with id ${e}.`);const{renderer:i}=s;if(!i)throw new Error(`Views: no renderer found for world with id ${s.uuid}.`);i.setPlane(!1,t.plane),i.setPlane(!1,t.farPlane),t.camera.controls.removeEventListener("rest",this._fragmentsUpdateEvent),s.useDefaultCamera(),t.open=!1}};t(IV,"uuid","fb22f1f5-6598-4664-a11d-de8963ae420f"),t(IV,"defaultRange",15);let DV=IV;async function LV(e,t,s,i,r,n,o){const a=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),await function(e,t,s,i){return new Promise((r,n)=>{!function o(){const a=e.clientWaitSync(t,s,0);a!==e.WAIT_FAILED?a!==e.TIMEOUT_EXPIRED?r():setTimeout(o,i):n()}()})}(e,a,0,10),e.deleteSync(a),e.bindBuffer(t,s),e.getBufferSubData(t,i,r,n,o),e.bindBuffer(t,null)}class FV{constructor(e,s){if(t(this,"onDisposed",new u),t(this,"onDistanceComputed",new u),t(this,"excludedObjects",new Set),t(this,"enabled",!0),t(this,"renderDebugFrame",!1),t(this,"components"),t(this,"scene",new l.Scene),t(this,"camera",new l.OrthographicCamera(-1,1,1,-1,0,1)),t(this,"depthMaterial"),t(this,"world"),t(this,"worker"),t(this,"_width",512),t(this,"_height",512),t(this,"_postQuad"),t(this,"tempRT"),t(this,"resultRT"),t(this,"bufferSize"),t(this,"_buffer"),t(this,"_isWorkerBusy",!1),t(this,"compute",async()=>{if(!this.enabled||this.world.isDisposing)return;if(this._isWorkerBusy)return;this._isWorkerBusy=!0,this.world.camera.three.updateMatrix();const e=this.world.renderer.three;e.setRenderTarget(this.tempRT);const t="visibilityBeforeDistanceCheck";for(const e of this.excludedObjects)e.userData[t]=e.visible,e.visible=!1;e.render(this.world.scene.three,this.world.camera.three);for(const e of this.excludedObjects)void 0!==e.userData[t]&&(e.visible=e.userData[t]);this.depthMaterial.uniforms.tDiffuse.value=this.tempRT.texture,this.depthMaterial.uniforms.tDepth.value=this.tempRT.depthTexture,e.setRenderTarget(this.resultRT),e.render(this.scene,this.camera);const s=e.getContext();try{await async function(e,t,s,i,r,n,o,a){const l=e.createBuffer();return e.bindBuffer(e.PIXEL_PACK_BUFFER,l),e.bufferData(e.PIXEL_PACK_BUFFER,a.byteLength,e.STREAM_READ),e.readPixels(t,s,i,r,n,o,0),e.bindBuffer(e.PIXEL_PACK_BUFFER,null),await LV(e,e.PIXEL_PACK_BUFFER,l,0,a),e.deleteBuffer(l),a}(s,0,0,this._width,this._height,s.RGBA,s.UNSIGNED_BYTE,this._buffer)}catch(t){return e.setRenderTarget(null),void(this._isWorkerBusy=!1)}e.setRenderTarget(null),this.renderDebugFrame&&e.render(this.scene,this.camera),this.worker.postMessage({buffer:this._buffer})}),t(this,"handleWorkerMessage",e=>{if(!this.enabled||this.world.isDisposing)return;const t=e.data.colors;let s=Number.MAX_VALUE;for(const e of t)0!==e&&e<s&&(s=e);const i=this.world.camera.three||l.OrthographicCamera,r=-1*(s/255-1)*(i.far-i.near),n=Math.min(r,i.far);this.onDistanceComputed.trigger(n),this._isWorkerBusy=!1}),!s.renderer)throw new Error("The given world must have a renderer!");this.components=e,this.world=s;const i=s.camera.three;this.tempRT=new l.WebGLRenderTarget(this._width,this._height),this.bufferSize=this._width*this._height*4,this._buffer=new Uint8Array(this.bufferSize),this.tempRT.texture.minFilter=l.NearestFilter,this.tempRT.texture.magFilter=l.NearestFilter,this.tempRT.stencilBuffer=!1,this.tempRT.samples=0,this.tempRT.depthTexture=new l.DepthTexture(this._width,this._height),this.tempRT.depthTexture.format=l.DepthFormat,this.tempRT.depthTexture.type=l.UnsignedShortType,this.resultRT=new l.WebGLRenderTarget(this._width,this._height),this.depthMaterial=new l.ShaderMaterial({vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n ",fragmentShader:"\n#include <packing>\n\nvarying vec2 vUv;\nuniform sampler2D tDiffuse;\nuniform sampler2D tDepth;\nuniform float cameraNear;\nuniform float cameraFar;\n\n\nfloat readDepth( sampler2D depthSampler, vec2 coord ) {\n float fragCoordZ = texture2D( depthSampler, coord ).x;\n float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );\n return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );\n}\n\nvoid main() {\n //vec3 diffuse = texture2D( tDiffuse, vUv ).rgb;\n float depth = readDepth( tDepth, vUv );\n\n gl_FragColor.rgb = 1.0 - vec3( depth );\n gl_FragColor.a = 1.0;\n}\n ",uniforms:{cameraNear:{value:i.near},cameraFar:{value:i.far},tDiffuse:{value:null},tDepth:{value:null}}});const r=new l.PlaneGeometry(2,2);this._postQuad=new l.Mesh(r,this.depthMaterial),this.scene.add(this._postQuad);const n=new Blob(['\n addEventListener("message", (event) => {\n const { buffer } = event.data;\n const colors = new Set();\n for (let i = 0; i < buffer.length; i += 4) {\n const r = buffer[i];\n colors.add(r);\n }\n postMessage({ colors });\n });\n '],{type:"application/javascript"});this.worker=new Worker(URL.createObjectURL(n)),this.worker.addEventListener("message",this.handleWorkerMessage)}dispose(){this.enabled=!1,this.onDistanceComputed.reset(),this.worker.terminate(),this.tempRT.dispose(),this.resultRT.dispose();const e=[...this.scene.children];this.excludedObjects.clear();for(const t of e)t.removeFromParent();this._postQuad.geometry.dispose(),this._postQuad.removeFromParent(),this._buffer=null,this.onDisposed.reset()}}class OV{constructor(e){t(this,"cardinality","required"),t(this,"instructions"),t(this,"evalRequirement",(e,t,s,i)=>{const r={parameter:s,currentValue:e,requiredValue:t,pass:!1};i&&this.addCheckResult(r,i);let n=!1;if("simple"===t.type&&(n=e===t.parameter),"enumeration"===t.type&&(n=t.parameter.includes(e)),"pattern"===t.type){n=new RegExp(t.parameter).test(String(e))}if("length"===t.type){const{min:s,length:i,max:r}=t.parameter;void 0!==i&&(n=String(e).length===i),void 0!==s&&(n=String(e).length>=s),void 0!==r&&(n=String(e).length<=r)}if("bounds"===t.type&&"number"==typeof e){const{min:s,minInclusive:i,max:r,maxInclusive:o}=t.parameter;let a=!0,l=!0;void 0!==s&&(a=i?e>=s:e>s),void 0!==r&&(l=o?e<=r:e<r),n=a&&l}return"prohibited"===this.cardinality&&(n=!n),"optional"===this.cardinality&&(n=!0),r.pass=n,r.pass}),this._components=e}addCheckResult(e,t){const s=t.findIndex(({parameter:t})=>t===e.parameter);-1!==s?t[s]=e:t.push(e)}getItemChecks(e,t,s,i){if(!("value"in s._localId)||"number"!=typeof s._localId.value)return null;let r=e.get(t);r||(r=new a.DataMap,e.set(t,r));let n=r.get(s._localId.value);if(n&&i&&!n.pass)return null;if(!n){const e=[];n={guid:Array.isArray(s._guid)?void 0:s._guid.value,pass:!1,checks:e},Object.defineProperty(n,"pass",{get:()=>e.every(({pass:e})=>e)}),r.set(s._localId.value,n)}const o=[],l={facetType:this.facetType,cardinality:this.cardinality,checks:o,pass:!1};return Object.defineProperty(l,"pass",{get:()=>o.every(({pass:e})=>e)}),n.checks.push(l),l.checks}}const VV=(e,t)=>{let s="";if(!t)return s;if("simple"===t.type&&(s=`<simpleValue>${t.parameter}</simpleValue>`),"enumeration"===t.type){s=`<xs:restriction base="xs:string">\n ${t.parameter.map(e=>`<xs:enumeration value="${e}" />`).join("\n")}\n </xs:restriction>`}if("pattern"===t.type){s=`<xs:restriction base="xs:string">\n <xs:pattern value="${t.parameter}" />\n </xs:restriction>`}if("bounds"===t.type){const{min:e,minInclusive:i,max:r,maxInclusive:n}=t.parameter;let o="";void 0!==e&&(o=`<xs:min${i?"Inclusive":"Exclusive"} value="${e}">`);let a="";void 0!==r&&(a=`<xs:max${n?"Inclusive":"Exclusive"} value="${r}">`),s=`<xs:restriction base="xs:double">\n ${o}\n ${a}\n </xs:restriction>`}if("length"===t.type){const{length:e,min:i,max:r}=t.parameter;let n="";void 0!==e&&void 0===i&&void 0===r&&(n=`<xs:length value="${e}" />`);let o="";void 0!==i&&void 0===e&&(o=`<xs:minLength value="${i}" />`);let a="";void 0!==r&&void 0===e&&(a=`<xs:maxLength value="${r}" />`),s=`<xs:restriction base="xs:string">\n ${n}\n ${o}\n ${a}\n </xs:restriction>`}return`<${e[0].toLowerCase()+e.slice(1)}>\n ${s}\n </${e[0].toLowerCase()+e.slice(1)}>`};class zV extends OV{constructor(e,s){super(e),t(this,"facetType","Attribute"),t(this,"name"),t(this,"value"),this.name=s}serialize(e){const t=VV("Name",this.name),s=VV("Value",this.value);let i="";return"requirement"===e&&(i+=`cardinality="${this.cardinality}"`,i+=this.instructions?`instructions="${this.instructions}"`:""),`<attribute ${i}>\n ${t}\n ${s}\n</attribute>`}async getEntities(){}async test(e,t,s={skipIfFails:!0}){const i=this._components.get(ji);for(const[r,n]of Object.entries(e)){const e=i.list.get(r);if(!e)continue;const o=await e.getItemsData([...n]);for(const e of o){const i=this.getItemChecks(t,r,e,s.skipIfFails);if(!i)continue;const n=Object.keys(e).filter(t=>{const s=this.evalRequirement(t,this.name,"Name");if(!s)return!1;const i=e[t];return!!Array.isArray(i)||(null===i||null===i.value?"optional"===this.cardinality||"prohibited"===this.cardinality:(!Array.isArray(i.value)||0!==i.value.length)&&(("string"!=typeof i.value||""!==i.value.trim())&&s))}),o=n.length>0;if(i.push({parameter:"Name",currentValue:o?n[0]:null,requiredValue:this.name,pass:"prohibited"===this.cardinality?!o:o}),this.value)if(n[0]){const t=e[n[0]];if(Array.isArray(t))i.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality});else{Array.isArray(t.value)?i.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality}):this.evalRequirement(t.value,this.value,"Value",i)}}else i.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality})}}}}class kV extends OV{constructor(e,s){super(e),t(this,"facetType","Classification"),t(this,"system"),t(this,"value"),t(this,"uri"),this.system=s}serialize(e){const t=VV("System",this.system),s=VV("Value",this.value);let i="";return"requirement"===e&&(i+=`cardinality="${this.cardinality}"`,i+=this.uri?`uri=${this.uri}`:"",i+=this.instructions?`instructions="${this.instructions}"`:""),`<classification ${i}>\n ${t}\n ${s}\n</classification>`}async getEntities(e,t){}async test(e,t){}}class UV extends OV{constructor(e,s){super(e),t(this,"facetType","Entity"),t(this,"name"),t(this,"predefinedType"),this.name=s}serialize(e){const t=VV("Name",this.name),s=VV("Name",this.predefinedType);let i="";return"requirement"===e&&(i+=`cardinality="${this.cardinality}"`,i+=this.instructions?`instructions="${this.instructions}"`:""),`<entity ${i}>\n ${t}\n ${s}\n</entity>`}async getEntities(e,t){const s=this._components.get(ji),i=new Map;for(const[t,r]of s.list){if(!e.find(e=>e.test(t)))continue;const s=await r.getCategories();for(const e of s){if(!await this.evalName(e))continue;let s=i.get(t);s||(s=[],i.set(t,s)),s.push(e)}}const r={};if(await Promise.all(Array.from(i.entries()).map(async([e,t])=>{const i=s.list.get(e);if(!i)return;const n=t.map(e=>new RegExp(`^${e}$`)),o=await i.getItemsOfCategories(n),a=Object.values(o).flat();r[e]=new Set(a)})),this.predefinedType)for(const[e,i]of Object.entries(r)){const r=s.list.get(e);if(!r)continue;const n=await r.getItemsData([...i]);for(const s of n){if(!("value"in s._localId))continue;await this.evalPredefinedType(e,s)&&Oe.append(t,e,s._localId.value)}}else Oe.add(t,r)}async test(e,t,s){const i=this._components.get(ji);for(const[r,n]of Object.entries(e)){const e=i.list.get(r);if(!e)continue;const o=await e.getItemsData([...n]);for(const e of o){if(!("value"in e._category))continue;const i=this.getItemChecks(t,r,e,s.skipIfFails);i&&(await this.evalName(e._category.value,i),await this.evalPredefinedType(r,e,i))}}}async evalName(e,t){return this.evalRequirement(e,this.name,"Name",t)}async evalPredefinedType(e,t,s){if(!this.predefinedType)return null;if(!("value"in t.PredefinedType))return null;const i="string"==typeof this.predefinedType.parameter&&"USERDEFINED"===this.predefinedType.parameter;let r=t.PredefinedType.value;if("USERDEFINED"===r&&!i){const e=Object.keys(t).find(e=>/^((?!Predefined).)*Type$/.test(e));if(e){const s=t[e];"value"in s&&(r=s.value)}else r="USERDEFINED"}if(!r){const s=this._components.get(ji).list.get(e);if(s&&"value"in t._localId){const[e]=await s.getItemsData([t._localId.value],{relations:{IsTypedBy:{attributes:!0,relations:!1}}});if(Array.isArray(e.IsTypedBy)){const t=e.IsTypedBy[0];if(t&&"value"in t.PredefinedType&&(r=t.PredefinedType.value,"USERDEFINED"===r&&!i)){const e=Object.keys(t).find(e=>/^((?!Predefined).)*Type$/.test(e));if(e){const s=t[e];"value"in s&&(r=s.value)}else r="USERDEFINED"}}}}return this.evalRequirement(r,this.predefinedType,"PredefinedType",s)}}class GV extends OV{constructor(e,s,i){super(e),t(this,"facetType","Property"),t(this,"propertySet"),t(this,"baseName"),t(this,"value"),t(this,"dataType"),t(this,"uri"),t(this,"_unsupportedTypes",["IFCCOMPLEXPROPERTY","IFCPHYSICALCOMPLEXQUANTITY"]),this.propertySet=s,this.baseName=i}serialize(e){const t=VV("PropertySet",this.propertySet),s=VV("BaseName",this.baseName),i=VV("Value",this.value),r=this.dataType?`dataType=${this.dataType}`:"";let n="";return"requirement"===e&&(n+=`cardinality="${this.cardinality}"`,n+=this.uri?`uri=${this.uri}`:"",n+=this.instructions?`instructions="${this.instructions}"`:""),`<property ${r} ${n}>\n ${t}\n ${s}\n ${i}\n</property>`}async getEntities(e,t){const s=this._components.get(ji);for(const[i,r]of s.list){if(!e.find(e=>e.test(i)))continue;const s=await r.getItemsOfCategories([/PROPERTYSET/,/ELEMENTQUANTITY/]),n=Object.values(s).flat();if(0===n.length)continue;const o=await r.getItemsData(n,{relations:{HasProperties:{attributes:!0,relations:!1},DefinesOcurrence:{attributes:!0,relations:!1}}});for(const e of o){if(!("value"in e._localId&&"value"in e._category&&"value"in e.Name&&Array.isArray(e.DefinesOcurrence)))continue;if(!this.evalRequirement(e.Name.value,this.propertySet,"PropertySet"))continue;let s;if("IFCPROPERTYSET"===e._category.value&&(s="HasProperties"),"IFCELEMENTQUANTITY"===e._category.value&&(s="Quantities"),!s)continue;const r=e[s];if(Array.isArray(r))for(const s of r){const r=Object.keys(s),n=r.find(e=>/Name/.test(e));if(!n||!("value"in s[n]))continue;const o=s[n];if(!("value"in o))continue;if(!this.evalRequirement(o.value,this.baseName,"BaseName"))continue;if(this.value){const e=r.find(e=>/Value/.test(e));if(!e)continue;const t=s[e];if(!("value"in t))continue;if(!this.evalRequirement(t.value,this.value,"Value"))continue}const a=e.DefinesOcurrence.map(e=>"value"in e._localId&&"number"==typeof e._localId.value?e._localId.value:null).filter(e=>null!==e);Oe.append(t,i,...a)}}}}async test(e,t,s={skipIfFails:!0}){const i=this._components.get(ji);for(const[r,n]of Object.entries(e)){const e=i.list.get(r);if(!e)continue;const o=await e.getItemsData([...n],{relations:{IsDefinedBy:{attributes:!0,relations:!0},IsTypedBy:{attributes:!0,relations:!1},HasPropertySets:{attributes:!0,relations:!0},DefinesOcurrence:{attributes:!1,relations:!1}}});for(const e of o){const i=this.getItemChecks(t,r,e,s.skipIfFails);if(!i)continue;const n=(await this.getPsets(e)).filter(e=>{if(!("value"in e.Name))return!1;return!!this.evalRequirement(e.Name.value,this.propertySet,"PropertySet")&&(i.push({currentValue:e.Name.value,parameter:"PropertySet",pass:!0,requiredValue:this.propertySet}),!0)});if(0!==n.length)for(const e of n){const t=this.getPropertyListName(e);if(!t)continue;const s=e[t];if(!Array.isArray(s)){i.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName});continue}const r=s.filter(e=>{if(!("value"in e._category)||!("value"in e.Name))return!1;if(this._unsupportedTypes.includes(e._category.value))return!1;return!!this.evalRequirement(e.Name.value,this.baseName,"BaseName")&&(i.push({currentValue:e.Name.value,parameter:"BaseName",pass:!0,requiredValue:this.baseName}),!0)});if(0!==r.length)for(const e of r)this.evalValue(e,i),this.evalDataType(e,i),this.evalURI();else i.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName})}else i.push({currentValue:null,parameter:"PropertySet",pass:!1,requiredValue:this.propertySet})}}}getPropertyListName(e){let t;return"value"in e._category?("IFCPROPERTYSET"===e._category.value&&(t="HasProperties"),"IFCELEMENTQUANTITY"===e._category.value&&(t="Quantities"),t):t}getValueKey(e){return Object.keys(e).find(e=>/Value/.test(e)||/Values/.test(e))}getTypePsets(e){if(!Array.isArray(e.IsTypedBy))return[];const[t]=e.IsTypedBy;return t&&Array.isArray(t.HasPropertySets)?t.HasPropertySets:[]}async getPsets(e){const t=this.getTypePsets(e);if(!Array.isArray(e.IsDefinedBy))return t;const s=[];for(const i of e.IsDefinedBy){if(!("value"in i.Name))continue;const e=i.Name.value,r=this.getPropertyListName(i);if(!e||!r)continue;const n=t.find(t=>"value"in t.Name&&t.Name.value===e);if(n&&Array.isArray(n.HasProperties)&&Array.isArray(i.HasProperties))for(const e of n.HasProperties){if(!("value"in e.Name))continue;const t=e.Name.value;i.HasProperties.find(e=>"value"in e.Name&&e.Name.value===t)||i.HasProperties.push(e)}s.push(i)}return s}evalValue(e,t){const s=this.getValueKey(e),i=e[s];if(!("value"in i))return!1;if(this.value){if(!s)return null==t||t.push({parameter:"Value",currentValue:null,pass:!1,requiredValue:this.value}),!1;const e=structuredClone(this.value);"IFCLABEL"===i.type&&"simple"===e.type&&(e.parameter=String(e.parameter));return this.evalRequirement(i.value,e,"Value",t)}return!s||("string"!=typeof i.value||""!==i.value.trim()||(null==t||t.push({parameter:"Value",currentValue:"",pass:!1,requiredValue:this.value}),!1))}evalDataType(e,t){if(!this.dataType)return!0;const s=this.getValueKey(e);if(!s||!("value"in e[s]))return null==t||t.push({parameter:"DataType",currentValue:null,pass:!1,requiredValue:this.dataType}),!1;const i=e[s];return this.evalRequirement(i.type??null,{type:"simple",parameter:this.dataType},"DataType",t)}evalURI(){return!0}}class jV extends OV{constructor(){super(...arguments),t(this,"_ifcMaterialEntities",[/^IFCMATERIALLAYERSETUSAGE$/,/^IFCMATERIALCONSTITUENTSET$/,/^IFCMATERIAL$/,/^IFCMATERIALLIST$/]),t(this,"facetType","Material"),t(this,"value"),t(this,"uri")}serialize(e){if(!this.value||!this.uri)return"<material />";const t=VV("Value",this.value);let s="";return"requirement"===e&&(s+=`cardinality="${this.cardinality}"`,s+=this.uri?`uri=${this.uri}`:"",s+=this.instructions?`instructions="${this.instructions}"`:""),`<material ${s}>\n ${t}\n</material>`}async getEntities(e,t){const s=this._components.get(ji);for(const[i,r]of s.list){if(!e.find(e=>e.test(i)))continue;const s=await r.getItemsOfCategories(this._ifcMaterialEntities),n=Object.values(s).flat();if(0===n.length)continue;const o=await r.getItemsData(n,{relations:{AssociatedTo:{attributes:!0,relations:!1},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});for(const e of o){if(!("value"in e._localId&&"value"in e._category&&Array.isArray(e.AssociatedTo)))continue;if(!this.hasValidMaterial(e))continue;const s=e.AssociatedTo.map(e=>"value"in e._localId&&e._localId.value?e._localId.value:null).filter(e=>null!==e);Oe.append(t,i,...s)}}}async test(e,t,s={skipIfFails:!0}){const i=this._components.get(ji);for(const[r,n]of Object.entries(e)){const e=i.list.get(r);if(!e)continue;const o=await e.getItemsData([[...n][0]],{relations:{AssociatedTo:{attributes:!1,relations:!1},HasAssociations:{attributes:!0,relations:!0},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});for(const e of o){const i=this.getItemChecks(t,r,e,s.skipIfFails);if(i)if(Array.isArray(e.HasAssociations))for(const t of e.HasAssociations){if(!this._ifcMaterialEntities.some(e=>"value"in t._category&&e.test(t._category.value)))continue;if(this.hasValidMaterial(t,i))break}else i.push({parameter:null,currentValue:null,requiredValue:this.value,pass:!1})}}}hasValidMaterial(e,t){let s=!1;if("value"in e._category&&"IFCMATERIAL"===e._category.value){this.evalValue(e,t)&&(s=!0)}else for(const[i,r]of Object.entries(e))if(["ForLayerSet","MaterialLayers","Material","MaterialConstituents","Materials"].includes(i)&&Array.isArray(r))for(const e of r){if("value"in e._category&&"IFCMATERIAL"===e._category.value){if(this.evalValue(e,t)){s=!0;break}}else{if(this.hasValidMaterial(e)){s=!0;break}}}return s}evalValue(e,t){if(!this.value)return null==t||t.push({parameter:null,currentValue:e.Name&&"value"in e.Name?e.Name.value:null,pass:!0}),!0;if(!("value"in e._category)||"IFCMATERIAL"!==e._category.value)return null;let s=!1;return e.Name&&"value"in e.Name&&(s=this.evalRequirement(e.Name.value,this.value,"Value",t)),s||(e.Category&&"value"in e.Category&&(s=this.evalRequirement(e.Category.value,this.value,"Value",t)),s)}}class $V extends OV{constructor(e,s){super(e),t(this,"facetType","PartOf"),t(this,"_entityFacet"),t(this,"_entity"),t(this,"relation"),t(this,"cardinality","required"),this._entity=s,this._entityFacet=new UV(e,s.name),this._entityFacet.predefinedType=s.predefinedType}set entity(e){this._entity=e;const{name:t,predefinedType:s}=e;this._entityFacet=new UV(this._components,t),this._entityFacet.predefinedType=s}get entity(){return this._entity}serialize(){return""}async getEntities(e,t){}async test(e){}}class WV{constructor(e,s,i){t(this,"name"),t(this,"ifcVersion",new Set),t(this,"identifier",w.create()),t(this,"description"),t(this,"instructions"),t(this,"requirementsDescription"),t(this,"applicability",new a.DataSet),t(this,"requirements",new a.DataSet),t(this,"components"),this.components=e,this.name=s;for(const e of i)this.ifcVersion.add(e)}set(e){const t=e,s=this;for(const i in e){if("identifier"===i)continue;const e=t[i];i in this&&(s[i]=e)}return this.components.get(ez).list.set(this.identifier,this),this}async test(e,t={skipIfFails:!0}){const s=new a.DataMap;if(0===this.requirements.size)return s;const i={},r=[];for(const t of this.applicability)r.push(t.getEntities(e,i));await Promise.all(r);const n=[];for(const e of this.requirements)n.push(e.test(i,s,t));return await Promise.all(n),s}serialize(){const e=`name="${this.name}"`,t=this.identifier?`identifier="${this.identifier}"`:"",s=this.description?`description="${this.description}"`:"",i=this.instructions?`instructions="${this.instructions}"`:"";return`<specification ifcVersion="${[...this.ifcVersion].join(" ")}" ${e} ${t} ${s} ${i}>\n <applicability minOccurs="1" maxOccurs="unbounded">\n ${[...this.applicability].map(e=>e.serialize("applicability")).join("\n")}\n </applicability>\n <requirements>\n ${[...this.requirements].map(e=>e.serialize("requirement")).join("\n")}\n </requirements>\n </specification>`}}const HV=e=>{if(!e)return;const t={};if("simpleValue"in e&&(t.type="simple",t.parameter=e.simpleValue),"restriction"in e){const s=e.restriction,i=Object.keys(s);if("pattern"in s&&(t.type="pattern",t.parameter=s.pattern.value),"enumeration"in s){t.type="enumeration";const e=s.enumeration.map(({value:e})=>s.base.includes("string")?String(e):s.base.includes("integer")||s.base.includes("double")?Number(e):e);t.parameter=e}if(i.some(e=>["minInclusive","minExclusive","maxInclusive","maxExclusive"].includes(e))){t.type="bounds";const e={},r=i.find(e=>e.includes("min")),n=i.find(e=>e.includes("max"));r&&(e.minInclusive="minInclusive"===r,e.min=s[r].value),n&&(e.maxInclusive="maxInclusive"===n,e.max=s[n].value),t.parameter=e}if(i.some(e=>["minLength","length","maxLength"].includes(e))){t.type="length";const e={};void 0!==s.length&&(e.length=s.length.value),void 0!==s.minLength&&(e.min=s.minLength.value),void 0!==s.maxLength&&(e.max=s.maxLength.value),t.parameter=e}}return void 0!==t.parameter?t:void 0},qV=(e,t)=>{const s=[];for(const i of t){const t=i.name,r=HV(t);if(!r)continue;const n=new UV(e,r);i.cardinality&&(n.cardinality=i.cardinality),n.predefinedType=HV(i.predefinedType),n.instructions=i.instructions,s.push(n)}return s},XV=(e,t)=>{const s=[];for(const i of t){const t=i.name,r=HV(t);if(!r)continue;const n=new zV(e,r);i.cardinality&&(n.cardinality=i.cardinality),n.value=HV(i.value),n.instructions=i.instructions,s.push(n)}return s},YV=(e,t)=>{const s=[];for(const i of t){const t=new jV(e);i.cardinality&&(t.cardinality=i.cardinality);const r=HV(i.value);"enumeration"===(null==r?void 0:r.type)&&Array.isArray(r.parameter)&&(r.parameter=r.parameter.map(String)),t.value=r,t.uri=i.uri,t.instructions=i.instructions,s.push(t)}return s},ZV=(e,t)=>{const s=[];for(const i of t){const t=i.propertySet,r=i.baseName,n=HV(t),o=HV(r);if(!o||!n)continue;const a=new GV(e,n,o);i.cardinality&&(a.cardinality=i.cardinality);const l=HV(i.value);a.value=l,a.dataType=i.dataType,a.uri=i.uri,a.instructions=i.instructions,s.push(a)}return s},QV=(e,t)=>{const s=[];for(const i of t){const t=i.system,r=HV(t);if(!r)continue;const n=new kV(e,r);i.cardinality&&(n.cardinality=i.cardinality);const o=HV(i.value);"simple"===(null==o?void 0:o.type)&&(o.parameter=String(o.parameter)),"enumeration"===(null==o?void 0:o.type)&&Array.isArray(o.parameter)&&(o.parameter=o.parameter.map(String)),n.value=o,n.uri=i.uri,n.instructions=i.instructions,s.push(n)}return s},KV=(e,t)=>{const s=[];for(const i of t){const t=HV(i.entity.name);if(!t)continue;const r=HV(i.entity.predefinedType),n=new $V(e,{name:t,predefinedType:r});n.relation=i.relation,i.cardinality&&(n.cardinality=i.cardinality),n.instructions=i.instructions,s.push(n)}return s},JV=class e extends d{constructor(i){super(i),t(this,"enabled",!0),t(this,"IDSInfo"),t(this,"list",new s.DataMap),i.add(e.uuid,this)}getModelIdMap(e){const t={},s={};for(const[i,r]of e){const e=[...r].filter(([,e])=>e.pass).map(([e])=>e);Oe.append(t,i,...e);const n=[...r].filter(([,e])=>!e.pass).map(([e])=>e);Oe.append(s,i,...n)}return{pass:t,fail:s}}create(e,t,s){const i=new WV(this.components,e,t);return s&&(i.identifier=s),this.list.set(i.identifier,i),i}load(t){const s=[],i=e.xmlParser.parse(t).ids,{specifications:r,info:n}=i;if(this.IDSInfo={...n},r&&r.specification){const e=Array.isArray(r.specification)?r.specification:[r.specification];for(const t of e){const{name:e,ifcVersion:i,description:r,instructions:n,identifier:o}=t;if(!e||!i)continue;const a=[],l=[],{applicability:h,requirements:u}=t;if(h){const{maxOccurs:e,...t}=h,s=Array.isArray(t)?t:[t];for(const e of s)for(const t in e){const s=Array.isArray(e[t])?e[t]:[e[t]];if("entity"===t){const e=qV(this.components,s);a.push(...e)}if("attribute"===t){const e=XV(this.components,s);a.push(...e)}if("material"===t){const e=YV(this.components,s);a.push(...e)}if("classification"===t){const e=QV(this.components,s);a.push(...e)}if("property"===t){const e=ZV(this.components,s);a.push(...e)}if("partOf"===t){const e=KV(this.components,s);a.push(...e)}}}let c;if(u){const{maxOccurs:e,...t}=u;c=u.description;const s=Array.isArray(t)?t:[t];for(const e of s)for(const t in e){const s=Array.isArray(e[t])?e[t]:[e[t]];if("entity"===t){const e=qV(this.components,s);l.push(...e)}if("attribute"===t){const e=XV(this.components,s);l.push(...e)}if("material"===t){const e=YV(this.components,s);l.push(...e)}if("classification"===t){const e=QV(this.components,s);l.push(...e)}if("property"===t){const e=ZV(this.components,s);l.push(...e)}if("partOf"===t){const e=KV(this.components,s);l.push(...e)}}}const d=this.create(e,i.split(/\s+/),o);d.description=r,d.instructions=n,d.requirementsDescription=c,d.applicability.add(...a),d.requirements.add(...l),s.push(d)}}return s}export(e,t=this.list.values()){const s=t??this.list;return`<ids xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://standards.buildingsmart.org/IDS http://standards.buildingsmart.org/IDS/1.0/ids.xsd" xmlns:ids="http://standards.buildingsmart.org/IDS">\n \x3c!-- Made with That Open Engine ${NO.release} (https://github.com/thatopen/engine_components) --\x3e\n <info>\n <title>${e.title}</title>\n ${e.copyright?`<copyright>${e.copyright}</copyright>`:""}\n ${e.version?`<version>${e.version}</version>`:""}\n ${e.description?`<description>${e.description}</description>`:""}\n ${e.author?`<author>${e.author}</author>`:""}\n ${e.date?`<date>${e.date.toISOString().split("T")[0]}</date>`:""}\n ${e.purpose?`<purpose>${e.purpose}</purpose>`:""}\n ${e.milestone?`<milestone>${e.milestone}</milestone>`:""}\n </info>\n <specifications>\n ${[...s].map(e=>e.serialize()).join("\n")}\n </specifications>\n</ids>`}};t(JV,"uuid","9f0b9f78-9b2e-481a-b766-2fbfd01f342c"),t(JV,"xmlParser",new Se({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0}));let ez=JV;const tz=class e extends d{constructor(s){super(s),t(this,"enabled",!0),s.add(e.uuid,this)}static distanceFromPointToLine(e,t,s,i=!1){const r=new l.Line3,n=new l.Vector3;return r.set(t,s),r.closestPointToPoint(e,i,n),n.distanceTo(e)}round(e){const t=1e3;e.x=Math.trunc(e.x*t)/t,e.y=Math.trunc(e.y*t)/t,e.z=Math.trunc(e.z*t)/t}async getVolumeFromFragments(e){return console.warn("getVolumeFromFragments is deprecated. Use getItemsVolume instead."),this.getItemsVolume(e)}async getItemsVolume(e){let t=0;const s=this.components.get(ji);for(const[i,r]of Object.entries(e)){const e=s.list.get(i);e&&(t+=await e.getItemsVolume([...r]))}return t}static convertUnits(e,t,s,i=2){const r={m:1,cm:.01,mm:.001,km:1e3,m2:1,cm2:1e-4,mm2:1e-6,km2:1e6,m3:1,cm3:1e-6,mm3:1e-9,km3:1e9};if(!r[t]||!r[s])throw new Error("Invalid units provided for conversion.");if(!Number.isInteger(i)||i<0||i>5)throw new Error("Precision must be an integer between 0 and 5.");const n=e*(r[t]/r[s]),o=10**i;return Math.round(n*o)/o}};t(tz,"uuid","267ca032-672f-4cb0-afa9-d24e904f39d6");let sz=tz;const iz=(e,t,s)=>{const i=new l.Vector3(-t.z,0,t.x),r=new l.Vector3(t.x+i.x,0,t.z+i.z).normalize().multiplyScalar(s/2);return[e.x+r.x,e.y,e.z+r.z,e.x-r.x,e.y,e.z-r.z]},rz=(e,t,s)=>{const i=new l.Vector3(-t.z,0,t.x),r=e.x-t.x*s+i.x*s*.4,n=e.z-t.z*s+i.z*s*.4,o=e.x-t.x*s-i.x*s*.4,a=e.z-t.z*s-i.z*s*.4;return[e.x,e.y,e.z,r,e.y,n,e.x,e.y,e.z,o,e.y,a]},nz=()=>[],oz=(e,t,s)=>{const i=new l.Vector3(-t.z,0,t.x),r=e.clone().addScaledVector(t,-s),n=r.clone().addScaledVector(i,.4*s),o=r.clone().addScaledVector(i,.4*-s);return[e.x,e.y,e.z,n.x,n.y,n.z,o.x,o.y,o.z]};class az extends a.DataMap{getBySystem(e){const t=new Map;for(const[s,i]of this)i.system===e&&t.set(s,i.data);return t}}class lz extends a.DataMap{constructor(e){super(),t(this,"_container"),this._container=e,this.deleteGuard=e=>"0"!==e,this.set("0",{name:"0",visible:!0,material:new l.LineBasicMaterial({color:0})})}create(e,t){if(!this.has(e)){const s={name:e,visible:(null==t?void 0:t.visible)??!0,material:(null==t?void 0:t.material)??new l.LineBasicMaterial({color:0})};this.set(e,s)}return this.get(e)}setColor(e,t){const s=this.get(e);s&&(s.material.color.setHex(t),this.set(e,s))}setMaterial(e,t){const s=this.get(e);if(!s)return;const i=s.material;s.material=t,this._container.traverse(s=>{s.userData.layer===e&&(s.userData.isDimension||s.isLineSegments&&(s.material=t))}),i.dispose(),this.set(e,s)}setVisibility(e,t){const s=this.get(e);s&&(s.visible=t,this._container.traverse(s=>{s.userData.layer===e&&(s.visible=t)}),this.set(e,s))}assign(e,t){const s=this.get(t);s&&(e.userData.layer=t,s.visible||(e.visible=!1),e.isLineSegments&&(e.material=s.material))}resolveColor(e){const t=this.get(e);if(t)return t.material.color.getHex()}}const hz=class e extends l.Group{constructor(s){super(),t(this,"_viewport"),t(this,"_border"),t(this,"_handles",[]),t(this,"_raycaster",new l.Raycaster),t(this,"_resizable",!1),t(this,"_movable",!1),t(this,"_dragHandle",null),t(this,"_dragConstraints",[]),t(this,"_hoveredHandle",null),t(this,"_moveDrag",null),t(this,"_hoveringBorder",!1),t(this,"_normalMat"),t(this,"_hoverMat"),t(this,"_borderMat"),this._viewport=s,this._borderMat=new l.LineBasicMaterial({color:e._BORDER_COLOR,depthTest:!1});const i=new l.BufferGeometry;i.setAttribute("position",new l.BufferAttribute(new Float32Array(24),3)),this._border=new l.LineSegments(i,this._borderMat),this._border.renderOrder=999,this._border.frustumCulled=!1,this._border.userData.isDimension=!0,this.add(this._border),this._normalMat=new l.MeshBasicMaterial({color:e._BORDER_COLOR}),this._hoverMat=new l.MeshBasicMaterial({color:e._BORDER_HOVER_COLOR});const r=new l.SphereGeometry(.05,8,6);for(const t of e._HANDLE_DEFS){const e=new l.Mesh(r,this._normalMat);e.renderOrder=1e3,e.visible=!1,e.userData.constraints=t.constraints,e.userData.isDimension=!0,this.add(e),this._handles.push(e)}this.update()}get resizable(){return this._resizable}set resizable(e){this._resizable=e;for(const t of this._handles)t.visible=e;e||(this._hoveredHandle&&(this._hoveredHandle.material=this._normalMat,this._hoveredHandle=null),this._dragHandle=null,this._dragConstraints=[])}get movable(){return this._movable}set movable(e){this._movable=e,e||(this._moveDrag=null,this._setBorderHover(!1))}get isDragging(){return null!==this._dragHandle||null!==this._moveDrag}update(){const e=this._viewport,t=e.left,s=e.right,i=-e.top,r=-e.bottom,n=.005,o=this._border.geometry.attributes.position;o.setXYZ(0,t,n,i),o.setXYZ(1,s,n,i),o.setXYZ(2,s,n,i),o.setXYZ(3,s,n,r),o.setXYZ(4,s,n,r),o.setXYZ(5,t,n,r),o.setXYZ(6,t,n,r),o.setXYZ(7,t,n,i),o.needsUpdate=!0,this._border.geometry.computeBoundingSphere();const a=(t+s)/2,l=(i+r)/2,h=.01,u=[[t,h,i],[s,h,i],[s,h,r],[t,h,r],[a,h,i],[s,h,l],[a,h,r],[t,h,l]];for(let e=0;e<this._handles.length;e++)this._handles[e].position.set(...u[e])}onPointerMove(t){if(this._dragHandle){const e=this._projectToLocal(t);if(!e)return;for(const t of this._dragConstraints)switch(t){case"left":this._viewport.left=e.x;break;case"right":this._viewport.right=e.x;break;case"top":this._viewport.top=-e.z;break;case"bottom":this._viewport.bottom=-e.z}return this._viewport.right<this._viewport.left&&([this._viewport.left,this._viewport.right]=[this._viewport.right,this._viewport.left],this._dragConstraints=this._dragConstraints.map(e=>"right"===e?"left":"left"===e?"right":e)),this._viewport.top<this._viewport.bottom&&([this._viewport.top,this._viewport.bottom]=[this._viewport.bottom,this._viewport.top],this._dragConstraints=this._dragConstraints.map(e=>"top"===e?"bottom":"bottom"===e?"top":e)),void this.update()}if(this._moveDrag){const e=this._projectToLocal(t);if(!e)return;const s=e.x-this._moveDrag.origin.x,i=e.z-this._moveDrag.origin.z;return this._viewport.left=this._moveDrag.left0+s,this._viewport.right=this._moveDrag.right0+s,this._viewport.top=this._moveDrag.top0-i,this._viewport.bottom=this._moveDrag.bottom0-i,void this.update()}if(!this._resizable&&!this._movable)return;this._raycaster.set(t.origin,t.direction);let s=null;if(this._resizable){const e=this._handles.filter(e=>e.visible),t=this._raycaster.intersectObjects(e,!1);s=t.length>0?t[0].object:null}if(s!==this._hoveredHandle&&(this._hoveredHandle&&(this._hoveredHandle.material=this._normalMat),s&&(s.material=this._hoverMat),this._hoveredHandle=s),this._movable&&!this._hoveredHandle){this._raycaster.params.Line={threshold:e._LINE_THRESHOLD};const t=this._raycaster.intersectObject(this._border,!1).length>0;this._setBorderHover(t)}else this._setBorderHover(!1)}onPointerDown(t){if(this._resizable||this._movable){if(this._raycaster.set(t.origin,t.direction),this._resizable){const e=this._handles.filter(e=>e.visible),t=this._raycaster.intersectObjects(e,!1);if(t.length>0)return this._dragHandle=t[0].object,void(this._dragConstraints=[...this._dragHandle.userData.constraints])}if(this._movable){this._raycaster.params.Line={threshold:e._LINE_THRESHOLD};if(this._raycaster.intersectObject(this._border,!1).length>0){const e=this._projectToLocal(t);if(!e)return;this._moveDrag={origin:e,left0:this._viewport.left,right0:this._viewport.right,top0:this._viewport.top,bottom0:this._viewport.bottom}}}}}onPointerUp(){this._dragHandle=null,this._dragConstraints=[],this._moveDrag=null}dispose(){this._border.geometry.dispose(),this._borderMat.dispose(),this._normalMat.dispose(),this._hoverMat.dispose(),this._handles.length>0&&this._handles[0].geometry.dispose(),this.removeFromParent()}_projectToLocal(e){this.updateWorldMatrix(!0,!1);const t=new l.Vector3(0,1,0).transformDirection(this.matrixWorld),s=(new l.Vector3).setFromMatrixPosition(this.matrixWorld),i=(new l.Plane).setFromNormalAndCoplanarPoint(t,s),r=new l.Vector3;return e.intersectPlane(i,r)?this.worldToLocal(r):null}_setBorderHover(t){t!==this._hoveringBorder&&(this._hoveringBorder=t,this._borderMat.color.setHex(t?e._BORDER_HOVER_COLOR:e._BORDER_COLOR))}};t(hz,"_BORDER_COLOR",22015),t(hz,"_BORDER_HOVER_COLOR",16746496),t(hz,"_LINE_THRESHOLD",.06),t(hz,"_HANDLE_DEFS",[{constraints:["left","top"]},{constraints:["right","top"]},{constraints:["right","bottom"]},{constraints:["left","bottom"]},{constraints:["top"]},{constraints:["right"]},{constraints:["bottom"]},{constraints:["left"]}]);let uz=hz;class cz{constructor(e){t(this,"uuid",l.MathUtils.generateUUID()),t(this,"name"),t(this,"camera"),t(this,"onDisposed",new u),t(this,"_left"),t(this,"_right"),t(this,"_top"),t(this,"_bottom"),t(this,"_drawingScale"),t(this,"_container",null),t(this,"_helper",null),t(this,"_helperVisible",!1),this._left=e.left,this._right=e.right,this._top=e.top,this._bottom=e.bottom,this._drawingScale=e.scale??100,this.name=e.name??"Drawing Viewport",this.camera=new l.OrthographicCamera(this._left,this._right,this._top,this._bottom,.1,30),this.camera.up.set(0,0,-1),this.camera.position.set(0,10,0),this.camera.lookAt(0,0,0),this.camera.layers.set(1)}get left(){return this._left}set left(e){var t;this._left=e,this.camera.left=e,this.camera.updateProjectionMatrix(),null==(t=this._helper)||t.update()}get right(){return this._right}set right(e){var t;this._right=e,this.camera.right=e,this.camera.updateProjectionMatrix(),null==(t=this._helper)||t.update()}get top(){return this._top}set top(e){var t;this._top=e,this.camera.top=e,this.camera.updateProjectionMatrix(),null==(t=this._helper)||t.update()}get bottom(){return this._bottom}set bottom(e){var t;this._bottom=e,this.camera.bottom=e,this.camera.updateProjectionMatrix(),null==(t=this._helper)||t.update()}get drawingScale(){return this._drawingScale}set drawingScale(e){this._drawingScale=e}get helper(){return this._helper||(this._helper=new uz(this)),this._helper}get helperVisible(){return this._helperVisible}set helperVisible(e){var t,s;this._helperVisible=e,e?null==(t=this._container)||t.add(this.helper):null==(s=this._helper)||s.removeFromParent()}get bbox(){const e=new l.Vector3(this._left,0,-this._top),t=new l.Vector3(this._right,0,-this._bottom);return new l.Box3(e,t)}get size(){const e=new l.Vector3;return this.bbox.getSize(e),new l.Vector2(1e3*e.x,1e3*e.z)}get localXAxis(){return new l.Vector3(1,0,0)}get localYAxis(){return new l.Vector3(0,0,-1)}get normal(){return new l.Vector3(0,1,0)}setContainer(e){this._container=e,this._helperVisible&&this._helper&&e.add(this._helper)}clipLine(e){const t=this.bbox,{start:s,end:i}=e,r=t.containsPoint(s),n=t.containsPoint(i);if(r&&n)return e;if(!r&&!n){const t=this.getPlaneIntersections(e);return t.length<2?null:new l.Line3(t[0],t[1])}const o=this.getPlaneIntersections(e);return 0===o.length?null:r?new l.Line3(s,o[0]):new l.Line3(o[0],i)}dispose(){var e;null==(e=this._helper)||e.dispose(),this._helper=null,this.onDisposed.trigger(),this.onDisposed.reset()}get bboxPlanes(){const e=this.bbox;return[new l.Plane(new l.Vector3(1,0,0),-e.min.x),new l.Plane(new l.Vector3(-1,0,0),e.max.x),new l.Plane(new l.Vector3(0,0,1),-e.min.z),new l.Plane(new l.Vector3(0,0,-1),e.max.z)]}getPlaneIntersections(e){const t=[];for(const s of this.bboxPlanes){const i=new l.Vector3;s.intersectLine(e,i)&&this.bbox.containsPoint(i)&&t.push(i)}return t}}class dz extends a.DataMap{constructor(e){super(),t(this,"_container"),this._container=e,this.onBeforeDelete.add(({value:e})=>{this._container.remove(e.camera),e.dispose()})}create(e){const t=new cz(e);return this._container.add(t.camera),t.setContainer(this._container),this.set(t.uuid,t),t}}const pz=class e extends l.Group{constructor(s){super(),t(this,"_drawing"),t(this,"_topFrame"),t(this,"_pillars"),t(this,"_bottomFrame"),t(this,"_topPlane"),t(this,"_bottomPlane"),t(this,"_frameMat"),t(this,"_depthMat"),t(this,"_planeMat"),t(this,"width",10),t(this,"height",10),t(this,"farHandle",new l.Object3D),t(this,"widthHandle",new l.Object3D),t(this,"heightHandle",new l.Object3D),this._drawing=s,this._frameMat=new l.LineBasicMaterial({color:e._FRAME_COLOR,depthTest:!1}),this._depthMat=new l.LineBasicMaterial({color:e._DEPTH_COLOR,depthTest:!1,transparent:!0,opacity:.4}),this._planeMat=new l.MeshBasicMaterial({color:e._FRAME_COLOR,transparent:!0,opacity:.07,side:l.DoubleSide,depthTest:!1});const i=()=>{const e=new l.BufferGeometry;return e.setAttribute("position",new l.BufferAttribute(new Float32Array(12),3)),e.setIndex([0,1,2,0,2,3]),e};this._topPlane=new l.Mesh(i(),this._planeMat),this._topPlane.renderOrder=998,this._topPlane.frustumCulled=!1,this._topPlane.userData.isDimension=!0,this._bottomPlane=new l.Mesh(i(),this._planeMat),this._bottomPlane.renderOrder=998,this._bottomPlane.frustumCulled=!1,this._bottomPlane.userData.isDimension=!0;const r=new l.BufferGeometry;r.setAttribute("position",new l.BufferAttribute(new Float32Array(24),3)),this._topFrame=new l.LineSegments(r,this._frameMat),this._topFrame.renderOrder=999,this._topFrame.frustumCulled=!1,this._topFrame.userData.isDimension=!0;const n=new l.BufferGeometry;n.setAttribute("position",new l.BufferAttribute(new Float32Array(24),3)),this._pillars=new l.LineSegments(n,this._depthMat),this._pillars.renderOrder=999,this._pillars.frustumCulled=!1,this._pillars.userData.isDimension=!0;const o=new l.BufferGeometry;o.setAttribute("position",new l.BufferAttribute(new Float32Array(24),3)),this._bottomFrame=new l.LineSegments(o,this._depthMat),this._bottomFrame.renderOrder=999,this._bottomFrame.frustumCulled=!1,this._bottomFrame.userData.isDimension=!0,this.add(this._topPlane,this._bottomPlane),this.add(this._topFrame,this._pillars,this._bottomFrame),this.add(this.farHandle,this.widthHandle,this.heightHandle),this.farHandle.rotation.x=Math.PI,this.update()}update(){const e=this.width/2,t=this.height/2,s=-this._drawing.far,i=.005,r=-e,n=e,o=-t,a=t,l=this._topFrame.geometry.attributes.position;l.setXYZ(0,r,i,o),l.setXYZ(1,n,i,o),l.setXYZ(2,n,i,o),l.setXYZ(3,n,i,a),l.setXYZ(4,n,i,a),l.setXYZ(5,r,i,a),l.setXYZ(6,r,i,a),l.setXYZ(7,r,i,o),l.needsUpdate=!0,this._topFrame.geometry.computeBoundingSphere();const h=this._pillars.geometry.attributes.position;h.setXYZ(0,r,i,o),h.setXYZ(1,r,s,o),h.setXYZ(2,n,i,o),h.setXYZ(3,n,s,o),h.setXYZ(4,n,i,a),h.setXYZ(5,n,s,a),h.setXYZ(6,r,i,a),h.setXYZ(7,r,s,a),h.needsUpdate=!0,this._pillars.geometry.computeBoundingSphere();const u=this._bottomFrame.geometry.attributes.position;u.setXYZ(0,r,s,o),u.setXYZ(1,n,s,o),u.setXYZ(2,n,s,o),u.setXYZ(3,n,s,a),u.setXYZ(4,n,s,a),u.setXYZ(5,r,s,a),u.setXYZ(6,r,s,a),u.setXYZ(7,r,s,o),u.needsUpdate=!0,this._bottomFrame.geometry.computeBoundingSphere();const c=(e,t)=>{const s=e.geometry.attributes.position;s.setXYZ(0,r,t,o),s.setXYZ(1,n,t,o),s.setXYZ(2,n,t,a),s.setXYZ(3,r,t,a),s.needsUpdate=!0,e.geometry.computeBoundingSphere()};c(this._topPlane,i),c(this._bottomPlane,s),this.farHandle.position.set(0,s,0),this.widthHandle.position.set(n,i,0),this.heightHandle.position.set(0,i,a)}attachFarGizmo(e){e.attach(this.farHandle),e.setSpace("local"),e.showX=!1,e.showZ=!1,e.addEventListener("objectChange",()=>{this.farHandle.position.x=0,this.farHandle.position.z=0;const e=Math.max(.1,-this.farHandle.position.y);this._drawing.far=e,this.farHandle.position.y=-e,this.update()})}attachWidthGizmo(e){e.attach(this.widthHandle),e.setSpace("local"),e.showY=!1,e.showZ=!1,e.addEventListener("objectChange",()=>{this.widthHandle.position.y=.005,this.widthHandle.position.z=0,this.width=Math.max(.1,2*this.widthHandle.position.x),this.widthHandle.position.x=this.width/2,this.update()})}attachHeightGizmo(e){e.attach(this.heightHandle),e.setSpace("local"),e.showX=!1,e.showY=!1,e.addEventListener("objectChange",()=>{this.heightHandle.position.x=0,this.heightHandle.position.y=.005,this.height=Math.max(.1,2*this.heightHandle.position.z),this.heightHandle.position.z=this.height/2,this.update()})}dispose(){this._topPlane.geometry.dispose(),this._bottomPlane.geometry.dispose(),this._topFrame.geometry.dispose(),this._pillars.geometry.dispose(),this._bottomFrame.geometry.dispose(),this._planeMat.dispose(),this._frameMat.dispose(),this._depthMat.dispose(),this.removeFromParent()}};t(pz,"_FRAME_COLOR",22015),t(pz,"_DEPTH_COLOR",22015);let mz=pz;function fz(e,t){if(3!==e.length||3!==t.length)throw new Error("computeAlignmentMatrix requires exactly 3 point pairs.");const s=(e,t)=>{const s=(new l.Vector3).subVectors(e[1],e[0]),i=(new l.Vector3).subVectors(e[2],e[0]);if((new l.Vector3).crossVectors(s,i).length()<1e-6)throw new Error(`${t} points are collinear — three non-collinear points are required to define a plane.`)};s(e,"Drawing"),s(t,"World");const i=(e,t,s)=>{const i=(new l.Vector3).subVectors(t,e),r=(new l.Vector3).subVectors(s,e),n=i.clone().normalize(),o=(new l.Vector3).crossVectors(i,r).normalize(),a=(new l.Vector3).crossVectors(n,o).normalize();return(new l.Matrix4).makeBasis(n,o,a)},r=i(e[0],e[1],e[2]),n=i(t[0],t[1],t[2]).clone().multiply(r.clone().invert()),o=e[0].distanceTo(e[1]);if(o<1e-10)throw new Error("The first two drawing points are coincident — cannot compute scale.");const a=t[0].distanceTo(t[1])/o,h=e[0].clone().multiplyScalar(a).applyMatrix4(n),u=(new l.Vector3).subVectors(t[0],h),c=(new l.Quaternion).setFromRotationMatrix(n),d=new l.Matrix4;return d.compose(u,c,new l.Vector3(a,a,a)),d}class gz{constructor(e){t(this,"uuid",l.MathUtils.generateUUID()),t(this,"_raycaster",new l.Raycaster),t(this,"_components"),t(this,"world",null),t(this,"three",new l.Group),t(this,"annotations",new az),t(this,"layers",new lz(this.three)),t(this,"activeLayer","0"),t(this,"far",10),t(this,"viewports",new dz(this.three)),t(this,"onDisposed",new u),this._components=e}raycast(e,t=null){this._raycaster.set(e.origin,e.direction),this._raycaster.layers.set(1),this._raycaster.params.Line&&(this._raycaster.params.Line.threshold=.1);const s=[];this.three.traverse(e=>{e instanceof l.LineSegments&&!e.userData.isDimension&&s.push(e)});const i=this._raycaster.intersectObjects(s,!1);if(0===i.length)return null;const r=i[0],n=this.three.worldToLocal(r.point.clone());let o=null;if(r.object instanceof l.LineSegments&&void 0!==r.index){const e=r.object.geometry.attributes.position,t=r.index,s=new l.Vector3(e.getX(t),e.getY(t),e.getZ(t)),i=new l.Vector3(e.getX(t+1),e.getY(t+1),e.getZ(t+1));s.applyMatrix4(r.object.matrixWorld),this.three.worldToLocal(s),i.applyMatrix4(r.object.matrixWorld),this.three.worldToLocal(i),o=new l.Line3(s,i)}return{point:n,object:r.object,viewport:t,line:o}}alignTo(e,t){fz(e,t).decompose(this.three.position,this.three.quaternion,this.three.scale)}static toDrawingSpace(e,t){e.updateWorldMatrix(!0,!1),t.three.updateWorldMatrix(!0,!1);const s=(new l.Matrix4).copy(t.three.matrixWorld).invert().multiply(e.matrixWorld),i=e.geometry.attributes.position,r=i.count,n=new Float32Array(3*r),o=new l.Vector3;for(let e=0;e<r;e++)o.fromBufferAttribute(i,e).applyMatrix4(s),n[3*e]=o.x,n[3*e+1]=0,n[3*e+2]=o.z;const a=new l.BufferGeometry;return a.setAttribute("position",new l.BufferAttribute(n,3)),new l.LineSegments(a)}addProjectionLines(e,t="0"){return this.layers.has(t)||(console.warn(`[TechnicalDrawing] Layer "${t}" does not exist. Falling back to "0".`),t="0"),this.layers.assign(e,t),e.layers.set(1),e.material instanceof l.LineDashedMaterial&&e.computeLineDistances(),e.geometry.computeBoundsTree({strategy:0,indirect:!0,type:Ii}),this.three.add(e),e}async addProjectionFromItems(e,t){if(!this.world)return void console.warn("[TechnicalDrawing] addProjectionFromItems: drawing has no world assigned.");for(const e of[t.layers.visible,t.layers.hidden])if(!this.layers.has(e))return void console.warn(`[TechnicalDrawing] Layer "${e}" does not exist — create it before calling addProjectionFromItems.`);const s=this._components.get(XF),i=s.projectionDirection.clone(),r=s.nearPlane,n=s.farPlane;try{this.three.updateWorldMatrix(!0,!1);const i=new l.Vector3(0,-1,0).transformDirection(this.three.matrixWorld).normalize();s.projectionDirection.copy(i);const r=(new l.Matrix4).makeRotationFromQuaternion((new l.Quaternion).setFromUnitVectors(i,new l.Vector3(0,-1,0))),n=(new l.Vector3).setFromMatrixPosition(this.three.matrixWorld).applyMatrix4(r).y;s.farPlane=n,s.nearPlane=n-this.far;const o=await s.get(e,this.world,{onProgress:t.onProgress}),a=e=>gz.toDrawingSpace(new l.LineSegments(e),this);this.addProjectionLines(a(o.visible),t.layers.visible),this.addProjectionLines(a(o.hidden),t.layers.hidden)}finally{s.projectionDirection.copy(i),s.nearPlane=r,s.farPlane=n}}orientTo(e){const t=e.clone().normalize(),s=Math.SQRT1_2;t.x>.999?this.three.quaternion.set(.5,-.5,.5,.5):t.x<-.999?this.three.quaternion.set(.5,.5,-.5,.5):t.y>.999?this.three.quaternion.set(0,0,1,0):t.y<-.999?this.three.quaternion.set(0,0,0,1):t.z>.999?this.three.quaternion.set(0,s,-s,0):t.z<-.999?this.three.quaternion.set(s,0,0,s):console.warn("[TechnicalDrawing] orientTo: direction does not match any of the 6 standard axes.")}dispose(){this.viewports.clear(),this.layers.clear(),this.annotations.clear();this._components.get(y).destroy(this.three),this.onDisposed.trigger(),this.onDisposed.reset()}}class yz{constructor(e){t(this,"styles",new a.DataMap),t(this,"activeStyle","default"),t(this,"onCommit",new u),t(this,"onUpdate",new u),t(this,"onDelete",new u),t(this,"onDisposed",new u),t(this,"_knownDrawings",new Set),t(this,"_previewMaterial",new l.LineBasicMaterial({color:16737894,depthTest:!1})),t(this,"_previewObject",null),t(this,"_previewDrawing",null),t(this,"_materialCache",new a.DataMap),t(this,"_meshMaterialCache",new a.DataMap),t(this,"_ownsChildGeometry",!0),this._components=e,this.styles.onItemUpdated.add(({key:e})=>{const t=this._materialCache.get(e);t&&t.color.setHex(this._resolveStyle(e).color);const s=this._meshMaterialCache.get(e);s&&s.color.setHex(this._resolveStyle(e).color);const i=this._components.get(sk),r=i?[...i.list.values()]:[...this._knownDrawings];for(const t of r){const s=[...t.annotations.getBySystem(this)].filter(([,t])=>t.style===e).map(([e])=>e);s.length>0&&this.update(t,s,{})}})}_onAfterPersist(e,t){}_onDispose(){}_updatePreview(){}get(e){const t=new a.DataMap;for(const s of e)for(const[e,i]of s.annotations.getBySystem(this))t.set(e,{drawingUuid:s.uuid,item:i});return t}add(e,t){const s={uuid:l.MathUtils.generateUUID(),style:this.activeStyle,...t},i=this._persist(e,s);return this.onCommit.trigger([i]),s}update(e,t,s){for(const i of t){const t=e.annotations.get(i);if(!t||t.system!==this)continue;const r=t.data;Object.assign(r,s),this._redraw(r,t.three),this.onUpdate.trigger({item:r,group:t.three})}}pick(e,t=.05){const s=new l.Raycaster;s.ray.copy(e),s.params.Line={threshold:t},s.params.LineSegments={threshold:t};const i=l.Line.prototype.raycast;let r=null,n=1/0;for(const e of this._knownDrawings)for(const[t,o]of e.annotations){if(o.system!==this)continue;const e=o.three;e.updateWorldMatrix(!0,!0),e.traverse(o=>{if(o===e)return;const a=[];if(o instanceof l.LineSegments&&o.userData.isDimension)i.call(o,s,a),a.length>0&&a[0].distance<n&&(n=a[0].distance,r=t);else if(o instanceof l.Mesh){const e=(new l.Box3).setFromObject(o),i=new l.Vector3;if(s.ray.intersectBox(e,i)){const e=s.ray.origin.distanceTo(i);e<n&&(n=e,r=t)}}})}return r}delete(e,t){const s=[];for(const i of t){const t=e.annotations.get(i);t&&t.system===this&&(this._disposeGroup(t.three),e.annotations.delete(i),s.push(i))}s.length&&this.onDelete.trigger(s)}clear(e){const t=e??[...this._knownDrawings];for(const e of t){const t=[];for(const[s,i]of e.annotations)i.system===this&&t.push(s);for(const s of t){const t=e.annotations.get(s);this._disposeGroup(t.three),e.annotations.delete(s)}}}dispose(){this._clearPreview(),this._onDispose(),this.clear();for(const e of this._materialCache.values())e.dispose();this._materialCache.clear();for(const e of this._meshMaterialCache.values())e.dispose();this._meshMaterialCache.clear(),this._previewMaterial.dispose(),this.onCommit.reset(),this.onUpdate.reset(),this.onDelete.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}_trackDrawing(e){this._knownDrawings.has(e)||(this._knownDrawings.add(e),e.onDisposed.add(()=>this._knownDrawings.delete(e)))}_resolveStyle(e){return this.styles.get(e)??this.styles.get("default")}_getMaterial(e){const t=this._materialCache.get(e);if(t)return t;const s=new l.LineBasicMaterial({color:this._resolveStyle(e).color});return this._materialCache.set(e,s),s}_getMeshMaterial(e){const t=this._meshMaterialCache.get(e);if(t)return t;const s=new l.MeshBasicMaterial({color:this._resolveStyle(e).color,side:l.DoubleSide});return this._meshMaterialCache.set(e,s),s}_disposeGroup(e){if(e.removeFromParent(),this._ownsChildGeometry)e.traverse(e=>{e.geometry instanceof l.BufferGeometry&&e.geometry.dispose()});else for(;e.children.length>0;)e.remove(e.children[0])}_clearPreview(){this._previewObject&&(this._previewObject.removeFromParent(),this._previewObject.geometry.dispose(),this._previewObject=null)}_persist(e,t){this._trackDrawing(e);const s=this._resolveStyle(t.style),i=this._buildGroup(t,s);return i.userData.isDimension=!0,i.userData.annotationUuid=t.uuid,i.userData.layer=e.activeLayer,e.three.add(i),e.annotations.set(t.uuid,{system:this,data:t,three:i}),this._onAfterPersist(t,i),{drawing:e,item:t,group:i}}_redraw(e,t){for(;t.children.length>0;){const e=t.children[0];this._ownsChildGeometry&&e.geometry instanceof l.BufferGeometry&&e.geometry.dispose(),t.remove(e)}const s=this._resolveStyle(e.style),i=this._buildGroup(e,s);for(;i.children.length>0;)t.add(i.children[0]);this._onAfterPersist(e,t)}}function xz(e,t){const s=e[0],i=e[e.length-1],r=(new l.Vector3).subVectors(i,s);if(r.lengthSq()<1e-10)return 0;r.normalize();const n=new l.Vector3(-r.z,0,r.x);return t.clone().sub(s).dot(n)}function bz(e,t){const s=[];for(let i=0;i<e.length-1;i++)s.push({uuid:l.MathUtils.generateUUID(),pointA:e[i].clone(),pointB:e[i+1].clone(),offset:t,style:""});return s}function _z(e,t){switch(e.kind){case"awaitingFirstPoint":if("CLICK"===t.type){if(!t.line)return e;const s=(new l.Vector3).subVectors(t.line.end,t.line.start).normalize();return{kind:"placingPoints",points:[t.point.clone()],cursor:null,lineDir:s,firstLine:t.line.clone()}}return"SELECT_LINE"===t.type?{kind:"positioningOffset",points:[t.line.start.clone(),t.line.end.clone()],cursor:null}:e;case"placingPoints":if("MOUSE_MOVE"===t.type){const s=new l.Vector3(-e.lineDir.z,0,e.lineDir.x),i=e.points[e.points.length-1],r=t.point.clone().sub(i).dot(s),n=i.clone().addScaledVector(s,r);return{...e,cursor:n}}if("CLICK"===t.type){if(!t.line)return e;if(function(e,t){const s=1e-6;return e.start.distanceTo(t.start)<s&&e.end.distanceTo(t.end)<s||e.start.distanceTo(t.end)<s&&e.end.distanceTo(t.start)<s}(t.line,e.firstLine))return e;const r=(new l.Vector3).subVectors(t.line.end,t.line.start).normalize();if(s=r,i=e.lineDir,!(Math.abs(s.dot(i))>.999))return e;const n=function(e,t,s){const i=e.clone().sub(t.start).dot(s);return t.start.clone().addScaledVector(s,i)}(e.points[0],t.line,e.lineDir),o=[...e.points,n];return{...e,points:o,cursor:e.cursor}}return"CONFIRM"===t.type&&e.points.length>=2?{kind:"positioningOffset",points:e.points,cursor:null}:"ESCAPE"===t.type?{kind:"awaitingFirstPoint"}:e;case"positioningOffset":if("MOUSE_MOVE"===t.type)return{...e,cursor:t.point.clone()};if("CLICK"===t.type){const s=xz(e.points,t.point);return{kind:"committed",dimensions:bz(e.points,s)}}return"ESCAPE"===t.type?{kind:"awaitingFirstPoint"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingFirstPoint"}:e}var s,i}function wz(e){const{pointA:t,pointB:s,offset:i}=e,r=(new l.Vector3).subVectors(s,t),n=new l.Vector3(-r.z,0,r.x).normalize(),o=t.clone().addScaledVector(n,i),a=s.clone().addScaledVector(n,i),h=(new l.Vector3).subVectors(a,o).normalize();return[{tip:o,dir:h},{tip:a,dir:h.clone().negate()}]}function vz(e,t){const{pointA:s,pointB:i,offset:r}=e,n=(new l.Vector3).subVectors(i,s),o=new l.Vector3(-n.z,0,n.x).normalize(),a=r>=0?1:-1,h=Math.abs(r),u=s.clone().addScaledVector(o,t.extensionGap*a),c=s.clone().addScaledVector(o,(h+t.extensionOvershoot)*a),d=i.clone().addScaledVector(o,t.extensionGap*a),p=i.clone().addScaledVector(o,(h+t.extensionOvershoot)*a),m=s.clone().addScaledVector(o,r),f=i.clone().addScaledVector(o,r),g=(new l.Vector3).subVectors(f,m).normalize(),y=t.lineTick(m,g,t.tickSize),x=t.lineTick(f,g.clone().negate(),t.tickSize);return[u.x,u.y,u.z,c.x,c.y,c.z,d.x,d.y,d.z,p.x,p.y,p.z,m.x,m.y,m.z,f.x,f.y,f.z,...y,...x]}function Tz(e,t,s,i){if("placingPoints"===e){const e=[];for(let s=0;s<t.length-1;s++){const i=t[s],r=t[s+1];e.push(i.x,i.y,i.z,r.x,r.y,r.z)}if(s){const i=t[t.length-1];e.push(i.x,i.y,i.z,s.x,s.y,s.z)}return e}if(!s||t.length<2)return[];const r=xz(t,s),n=[];for(let e=0;e<t.length-1;e++)n.push(...vz({pointA:t[e],pointB:t[e+1],offset:r},i));return n}class Sz extends yz{constructor(e){super(e),t(this,"enabled",!0),t(this,"machineState",{kind:"awaitingFirstPoint"}),t(this,"onMachineStateChanged",new u),this.styles.set("default",{lineTick:iz,tickSize:.4,extensionGap:.05,extensionOvershoot:.2,color:0,textOffset:.4,fontSize:.45})}pickHandle(e,t,s=.1){const i=(new l.Matrix4).copy(e.three.matrixWorld).invert(),r=t.origin.clone().applyMatrix4(i),n=t.direction.clone().transformDirection(i).normalize(),o=new l.Ray(r,n),a=new l.Plane(new l.Vector3(0,1,0),0),h=o.intersectPlane(a,new l.Vector3);if(!h)return null;let u=null,c=s;for(const[t,s]of e.annotations.getBySystem(this)){const e=(new l.Vector3).subVectors(s.pointB,s.pointA),i=new l.Vector3(-e.z,0,e.x).normalize(),r=(new l.Vector3).addVectors(s.pointA,s.pointB).multiplyScalar(.5).addScaledVector(i,s.offset);for(const[e,i]of[["pointA",s.pointA],["pointB",s.pointB],["offset",r]]){const s=Math.hypot(h.x-i.x,h.z-i.z);s<c&&(c=s,u={uuid:t,handle:e})}}return u}sendMachineEvent(e){const t=e.drawing??null;t&&(this._previewDrawing=t);const s=_z(this.machineState,e);if(s!==this.machineState){if(this.machineState=s,this._updatePreview(),"committed"===s.kind){if(!this._previewDrawing)return console.warn("LinearAnnotations: no drawing context — send a CLICK or SELECT_LINE with `drawing` first. Skipping."),void this._resetMachine();for(const e of s.dimensions)e.style=this.activeStyle;const e=s.dimensions.map(e=>this._persist(this._previewDrawing,e));this.onCommit.trigger(e)}this.onMachineStateChanged.trigger(this.machineState),"committed"===s.kind&&this._resetMachine()}}_buildGroup(e,t){const s=new l.Group,i=vz(e,t),r=new l.BufferGeometry;r.setAttribute("position",new l.BufferAttribute(new Float32Array(i),3));const n=new l.LineSegments(r,this._getMaterial(e.style));if(n.layers.set(1),n.userData.isDimension=!0,s.add(n),t.meshTick)for(const{tip:i,dir:r}of wz(e)){const n=t.meshTick(i,r,t.tickSize),o=new l.BufferGeometry;o.setAttribute("position",new l.BufferAttribute(new Float32Array(n),3));const a=new l.Mesh(o,this._getMeshMaterial(e.style));a.layers.set(1),a.userData.isMeshTick=!0,s.add(a)}return s}_updatePreview(){const e=this.machineState;if("placingPoints"!==e.kind&&"positioningOffset"!==e.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const t=this._resolveStyle(this.activeStyle);this._previewMaterial.color.setHex(t.color);const s=Tz(e.kind,e.points,e.cursor,t);if(0===s.length)return void this._clearPreview();const i=s.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==i){this._clearPreview();const e=new l.BufferGeometry;e.setAttribute("position",new l.BufferAttribute(new Float32Array(s),3)),this._previewObject=new l.LineSegments(e,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const e=this._previewObject.geometry.attributes.position;e.set(s),e.needsUpdate=!0}}_resetMachine(){this.machineState={kind:"awaitingFirstPoint"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}}const Mz=Math.PI/180;function Az(e,t,s,i){const r=function(e,t,s){const i=(new l.Vector3).subVectors(e,t).normalize(),r=(new l.Vector3).subVectors(s,t).normalize();return(new l.Vector3).addVectors(i,r).normalize()}(e,t,s);return(new l.Vector3).subVectors(i,t).setY(0).dot(r)}function Nz(e,t,s,i){return Az(e,t,s,i)<0}function Ez(e,t){switch(e.kind){case"awaitingFirstLine":return"CLICK"===t.type&&t.line?{kind:"awaitingSecondLine",line1:t.line.clone(),pointA:t.point.clone()}:e;case"awaitingSecondLine":if("CLICK"===t.type&&t.line){const s=(new l.Vector3).subVectors(e.line1.end,e.line1.start).normalize(),i=(new l.Vector3).subVectors(t.line.end,t.line.start).normalize();if(Math.abs(s.dot(i))>Math.cos(Mz))return e;const r=function(e,t,s,i){const r=t.x*i.z-t.z*i.x;if(Math.abs(r)<1e-10)return null;const n=(new l.Vector3).subVectors(s,e),o=(n.x*i.z-n.z*i.x)/r;return new l.Vector3(e.x+t.x*o,0,e.z+t.z*o)}(e.line1.start,s,t.line.start,i);return r?{kind:"positioningArc",pointA:e.pointA.clone(),vertex:r,pointB:t.point.clone(),cursor:null,flipped:!1}:e}return"ESCAPE"===t.type?{kind:"awaitingFirstLine"}:e;case"positioningArc":if("MOUSE_MOVE"===t.type){const s=Nz(e.pointA,e.vertex,e.pointB,t.point);return{...e,cursor:t.point.clone(),flipped:s}}if("CLICK"===t.type){const s=Nz(e.pointA,e.vertex,e.pointB,t.point),i=Math.max(.05,Math.abs(Az(e.pointA,e.vertex,e.pointB,t.point)));return{kind:"committed",dimension:{uuid:l.MathUtils.generateUUID(),pointA:e.pointA.clone(),vertex:e.vertex.clone(),pointB:e.pointB.clone(),arcRadius:i,flipped:s,style:""}}}return"ESCAPE"===t.type?{kind:"awaitingFirstLine"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingFirstLine"}:e}}function Cz(e){const t=(new l.Vector3).subVectors(e.pointA,e.vertex).normalize(),s=(new l.Vector3).subVectors(e.pointB,e.vertex).normalize(),i=Math.atan2(t.z,t.x);let r=Math.atan2(s.z,s.x)-i;for(;r>Math.PI;)r-=2*Math.PI;for(;r<-Math.PI;)r+=2*Math.PI;e.flipped&&(r-=2*Math.sign(r)*Math.PI);const n=new l.Vector3(e.vertex.x+Math.cos(i)*e.arcRadius,0,e.vertex.z+Math.sin(i)*e.arcRadius),o=i+r,a=new l.Vector3(e.vertex.x+Math.cos(o)*e.arcRadius,0,e.vertex.z+Math.sin(o)*e.arcRadius),h=Math.sign(r);return[{tip:n,dir:new l.Vector3(-Math.sin(i)*h,0,Math.cos(i)*h)},{tip:a,dir:new l.Vector3(Math.sin(o)*h,0,-Math.cos(o)*h)}]}function Rz(e){const t=(new l.Vector3).subVectors(e.pointA,e.vertex).normalize(),s=(new l.Vector3).subVectors(e.pointB,e.vertex).normalize(),i=Math.acos(l.MathUtils.clamp(t.dot(s),-1,1));return e.flipped?2*Math.PI-i:i}function Pz(e){const t=(new l.Vector3).subVectors(e.pointA,e.vertex).normalize(),s=(new l.Vector3).subVectors(e.pointB,e.vertex).normalize(),i=Math.atan2(t.z,t.x);let r=Math.atan2(s.z,s.x)-i;for(;r>Math.PI;)r-=2*Math.PI;for(;r<-Math.PI;)r+=2*Math.PI;const n=i+r/2;return e.flipped?n+Math.PI:n}function Bz(e,t,s,i,r,n=!1){const o=Math.atan2(t.z,t.x);let a=Math.atan2(s.z,s.x)-o;for(;a>Math.PI;)a-=2*Math.PI;for(;a<-Math.PI;)a+=2*Math.PI;n&&(a-=2*Math.sign(a)*Math.PI);const h=[];for(let t=0;t<8;t++){const s=o+a*(t/8),r=o+a*((t+1)/8);h.push(e.x+Math.cos(s)*i,0,e.z+Math.sin(s)*i,e.x+Math.cos(r)*i,0,e.z+Math.sin(r)*i)}const u=new l.Vector3(e.x+Math.cos(o)*i,0,e.z+Math.sin(o)*i),c=new l.Vector3(e.x+Math.cos(o+a)*i,0,e.z+Math.sin(o+a)*i),d=e.clone().addScaledVector(t,r.extensionGap),p=e.clone().addScaledVector(s,r.extensionGap);h.push(d.x,d.y,d.z,u.x,u.y,u.z,p.x,p.y,p.z,c.x,c.y,c.z);const m=Math.sign(a),f=new l.Vector3(-Math.sin(o)*m,0,Math.cos(o)*m),g=o+a,y=new l.Vector3(Math.sin(g)*m,0,-Math.cos(g)*m);return h.push(...r.lineTick(u,f,r.tickSize),...r.lineTick(c,y,r.tickSize)),h}function Iz(e,t){const s=(new l.Vector3).subVectors(e.pointA,e.vertex).normalize(),i=(new l.Vector3).subVectors(e.pointB,e.vertex).normalize();return Bz(e.vertex,s,i,e.arcRadius,t,e.flipped??!1)}function Dz(e,t,s,i,r,n=!1){if(!i)return[];const o=Math.max(.05,(new l.Vector3).subVectors(i,t).setY(0).length());return Bz(t,(new l.Vector3).subVectors(e,t).normalize(),(new l.Vector3).subVectors(s,t).normalize(),o,r,n)}class Lz extends yz{constructor(e){super(e),t(this,"enabled",!0),t(this,"machineState",{kind:"awaitingFirstLine"}),t(this,"onMachineStateChanged",new u),t(this,"_secondLinePreviewObject",null),this.styles.set("default",{lineTick:iz,tickSize:.4,extensionGap:.05,color:0,textOffset:.25,fontSize:.45})}pickHandle(e,t,s){return null}sendMachineEvent(e){const t=e.drawing??null;if("awaitingSecondLine"===this.machineState.kind&&"MOUSE_MOVE"===e.type)return t&&(this._previewDrawing=t),void this._updateSecondLinePreview(e.point,e.line??null);const s=Ez(this.machineState,e);if(s!==this.machineState){if("awaitingSecondLine"===this.machineState.kind&&this._clearSecondLinePreview(),this.machineState=s,t&&(this._previewDrawing=t),this._updatePreview(),"committed"===s.kind){if(!this._previewDrawing)return console.warn("AngleAnnotations: CLICK that commits must include `drawing`. Skipping."),void this._resetMachine();s.dimension.style=this.activeStyle;const e=this._persist(this._previewDrawing,s.dimension);this.onCommit.trigger([e])}this.onMachineStateChanged.trigger(this.machineState),"committed"===s.kind&&this._resetMachine()}}_buildGroup(e,t){const s=new l.Group,i=Iz(e,t),r=new l.BufferGeometry;r.setAttribute("position",new l.BufferAttribute(new Float32Array(i),3));const n=new l.LineSegments(r,this._getMaterial(e.style));if(n.layers.set(1),n.userData.isDimension=!0,s.add(n),t.meshTick)for(const{tip:i,dir:r}of Cz(e)){const n=t.meshTick(i,r,t.tickSize),o=new l.BufferGeometry;o.setAttribute("position",new l.BufferAttribute(new Float32Array(n),3));const a=new l.Mesh(o,this._getMeshMaterial(e.style));a.layers.set(1),a.userData.isMeshTick=!0,s.add(a)}return s}_updatePreview(){const e=this.machineState;if("positioningArc"!==e.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const t=this._resolveStyle(this.activeStyle),s=Dz(e.pointA,e.vertex,e.pointB,e.cursor,t,e.flipped);if(0===s.length)return void this._clearPreview();const i=s.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==i){this._clearPreview();const e=new l.BufferGeometry;e.setAttribute("position",new l.BufferAttribute(new Float32Array(s),3)),this._previewObject=new l.LineSegments(e,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const e=this._previewObject.geometry.attributes.position;e.set(s),e.needsUpdate=!0}}_onDispose(){this._clearSecondLinePreview()}_resetMachine(){this.machineState={kind:"awaitingFirstLine"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}_clearSecondLinePreview(){this._secondLinePreviewObject&&(this._secondLinePreviewObject.removeFromParent(),this._secondLinePreviewObject.geometry.dispose(),this._secondLinePreviewObject=null)}_updateSecondLinePreview(e,t){if("awaitingSecondLine"!==this.machineState.kind)return void this._clearSecondLinePreview();if(!this._previewDrawing)return void this._clearSecondLinePreview();const s=this.machineState,i=(new l.Vector3).subVectors(s.line1.end,s.line1.start).normalize();if(!t)return void this._clearSecondLinePreview();const r=(new l.Vector3).subVectors(t.end,t.start).normalize(),n=function(e,t,s,i){const r=t.x*i.z-t.z*i.x;if(Math.abs(r)<1e-6)return null;const n=s.x-e.x,o=s.z-e.z,a=(n*i.z-o*i.x)/r;return new l.Vector3(e.x+a*t.x,0,e.z+a*t.z)}(s.line1.start,i,t.start,r);if(!n)return void this._clearSecondLinePreview();const o=e.clone(),a=(new l.Vector3).subVectors(o,n).setY(0);if(a.length()<.01)return void this._clearSecondLinePreview();const h=(new l.Vector3).subVectors(s.pointA,n).normalize(),u=a.normalize(),c=Math.atan2(h.z,h.x);let d=Math.atan2(u.z,u.x)-c;for(;d>Math.PI;)d-=2*Math.PI;for(;d<-Math.PI;)d+=2*Math.PI;const p=c+d/2,m=Math.max(.1,.4*Math.min(s.pointA.distanceTo(n),o.distanceTo(n))),f=new l.Vector3(n.x+Math.cos(p)*m,0,n.z+Math.sin(p)*m),g=this._resolveStyle(this.activeStyle),y=Dz(s.pointA,n,o,f,g);if(0===y.length)return void this._clearSecondLinePreview();const x=y.length/3;if(!this._secondLinePreviewObject||this._secondLinePreviewObject.geometry.attributes.position.count!==x){this._clearSecondLinePreview();const e=new l.BufferGeometry;e.setAttribute("position",new l.BufferAttribute(new Float32Array(y),3)),this._secondLinePreviewObject=new l.LineSegments(e,this._previewMaterial),this._secondLinePreviewObject.layers.set(1),this._secondLinePreviewObject.renderOrder=1,this._secondLinePreviewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._secondLinePreviewObject)}else{const e=this._secondLinePreviewObject.geometry.attributes.position;e.set(y),e.needsUpdate=!0}}}function Fz(e,t){const s=t.x-e.x,i=t.z-e.z,r=Math.sqrt(s*s+i*i);if(0===r)return e.clone();const n=Math.atan2(i,s),o=Math.round(n/(Math.PI/4))*(Math.PI/4);return new l.Vector3(e.x+Math.cos(o)*r,0,e.z+Math.sin(o)*r)}function Oz(e,t){switch(e.kind){case"awaitingArrowTip":return"CLICK"===t.type?{kind:"placingElbow",arrowTip:t.point.clone(),cursor:null}:e;case"placingElbow":return"MOUSE_MOVE"===t.type?{...e,cursor:t.point.clone()}:"CLICK"===t.type?{kind:"placingExtension",arrowTip:e.arrowTip,elbow:t.point.clone(),cursor:null}:"ESCAPE"===t.type?{kind:"awaitingArrowTip"}:e;case"placingExtension":return"MOUSE_MOVE"===t.type?{...e,cursor:Fz(e.elbow,t.point)}:"CLICK"===t.type?{kind:"enteringText",arrowTip:e.arrowTip,elbow:e.elbow,extensionEnd:Fz(e.elbow,t.point)}:"ESCAPE"===t.type?{kind:"awaitingArrowTip"}:e;case"enteringText":if("SUBMIT_TEXT"===t.type&&t.text.trim().length>0){return{kind:"committed",annotation:{uuid:l.MathUtils.generateUUID(),arrowTip:e.arrowTip.clone(),elbow:e.elbow.clone(),extensionEnd:e.extensionEnd.clone(),text:t.text.trim(),style:""}}}return"ESCAPE"===t.type?{kind:"awaitingArrowTip"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingArrowTip"}:e}}function Vz(e,t,s,i){return"curved"===i.leaderShape?function(e,t,s,i){const r=new l.QuadraticBezierCurve3(e,t,s).getPoints(24),n=[];for(let e=0;e<r.length-1;e++){const t=r[e],s=r[e+1];n.push(t.x,t.y,t.z,s.x,s.y,s.z)}if(i.lineTick){const s=(new l.Vector3).subVectors(e,t);s.lengthSq()>1e-10&&n.push(...i.lineTick(e,s.normalize(),i.tickSize))}return n}(e,t,s,i):function(e,t,s,i){const r=[e.x,e.y,e.z,t.x,t.y,t.z,t.x,t.y,t.z,s.x,s.y,s.z];if(i.lineTick){const s=(new l.Vector3).subVectors(e,t);s.lengthSq()>1e-10&&r.push(...i.lineTick(e,s.normalize(),i.tickSize))}return r}(e,t,s,i)}function zz(e,t){return Vz(e.arrowTip,e.elbow,e.extensionEnd,t)}function kz(e,t,s,i,r){return i?Vz(t,"placingElbow"===e?i:s,i,r):[]}class Uz extends yz{constructor(e){super(e),t(this,"enabled",!0),t(this,"machineState",{kind:"awaitingArrowTip"}),t(this,"onMachineStateChanged",new u),t(this,"_previewMeshMaterial",new l.MeshBasicMaterial({color:16737894,side:l.DoubleSide,depthTest:!1})),t(this,"_previewMeshObject",null),this.styles.set("default",{tickSize:.4,color:0,textOffset:.1,fontSize:.45,lineTick:rz})}pickHandle(e,t,s=.1){const i=(new l.Matrix4).copy(e.three.matrixWorld).invert(),r=t.origin.clone().applyMatrix4(i),n=t.direction.clone().transformDirection(i).normalize(),o=new l.Ray(r,n),a=new l.Plane(new l.Vector3(0,1,0),0),h=o.intersectPlane(a,new l.Vector3);if(!h)return null;let u=null,c=s;for(const[t,s]of e.annotations.getBySystem(this))for(const[e,i]of[["elbow",s.elbow],["extensionEnd",s.extensionEnd]]){const s=Math.hypot(h.x-i.x,h.z-i.z);s<c&&(c=s,u={uuid:t,handle:e})}return u}sendMachineEvent(e){const t=e.drawing??null;t&&(this._previewDrawing=t);const s=Oz(this.machineState,e);if(s!==this.machineState){if(this.machineState=s,this._updatePreview(),"committed"===s.kind){if(!this._previewDrawing)return console.warn("LeaderAnnotations: commit requires a drawing. Skipping."),void this._resetMachine();s.annotation.style=this.activeStyle;const e=this._persist(this._previewDrawing,s.annotation);this.onCommit.trigger([e])}this.onMachineStateChanged.trigger(this.machineState),"committed"===s.kind&&this._resetMachine()}}_buildGroup(e,t){const s=new l.Group,i=zz(e,t),r=new l.BufferGeometry;r.setAttribute("position",new l.BufferAttribute(new Float32Array(i),3));const n=new l.LineSegments(r,this._getMaterial(e.style));if(n.layers.set(1),n.userData.isDimension=!0,s.add(n),t.meshTick){const i=(new l.Vector3).subVectors(e.arrowTip,e.elbow);if(i.lengthSq()>1e-10){i.normalize();const r=t.meshTick(e.arrowTip,i,t.tickSize),n=new l.BufferGeometry;n.setAttribute("position",new l.BufferAttribute(new Float32Array(r),3));const o=new l.Mesh(n,this._getMeshMaterial(e.style));o.layers.set(1),o.userData.isMeshArrow=!0,s.add(o)}}return s}_updatePreview(){const e=this.machineState;if("placingElbow"!==e.kind&&"placingExtension"!==e.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const t=this._resolveStyle(this.activeStyle),s="placingElbow"===e.kind?kz("placingElbow",e.arrowTip,null,e.cursor,t):kz("placingExtension",e.arrowTip,e.elbow,e.cursor,t);if(0===s.length)return void this._clearPreview();const i=s.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==i){this._clearPreview();const e=new l.BufferGeometry;e.setAttribute("position",new l.BufferAttribute(new Float32Array(s),3)),this._previewObject=new l.LineSegments(e,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.frustumCulled=!1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const e=this._previewObject.geometry.attributes.position;e.set(s),e.needsUpdate=!0}if(t.meshTick){const s="placingElbow"===e.kind?e.cursor:e.elbow,i=s?(new l.Vector3).subVectors(e.arrowTip,s):null;if(i&&i.lengthSq()>1e-10){i.normalize();const s=t.meshTick(e.arrowTip,i,t.tickSize);if(this._previewMeshObject){const e=this._previewMeshObject.geometry.attributes.position;e.set(s),e.needsUpdate=!0}else{const e=new l.BufferGeometry;e.setAttribute("position",new l.BufferAttribute(new Float32Array(s),3)),this._previewMeshObject=new l.Mesh(e,this._previewMeshMaterial),this._previewMeshObject.layers.set(1),this._previewMeshObject.renderOrder=1,this._previewMeshObject.frustumCulled=!1,this._previewDrawing.three.add(this._previewMeshObject)}}else this._clearPreviewMesh()}else this._clearPreviewMesh()}_clearPreview(){super._clearPreview(),this._clearPreviewMesh()}_onDispose(){this._clearPreviewMesh(),this._previewMeshMaterial.dispose()}_resetMachine(){this.machineState={kind:"awaitingArrowTip"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}_clearPreviewMesh(){this._previewMeshObject&&(this._previewMeshObject.removeFromParent(),this._previewMeshObject.geometry.dispose(),this._previewMeshObject=null)}}class Gz extends yz{constructor(e){super(e),t(this,"enabled",!0),t(this,"_ownsChildGeometry",!1),t(this,"definitions",new a.DataMap),this.styles.set("default",{color:0,textOffset:0,fontSize:0})}pickHandle(e,t,s){return null}pick(e,t=.05){const s=new l.Raycaster;s.ray.copy(e),s.params.Line={threshold:t},s.params.LineSegments={threshold:t};let i=null,r=1/0;for(const e of this._knownDrawings)for(const[t,n]of e.annotations){if(n.system!==this)continue;const e=n.three;e.updateWorldMatrix(!0,!0),e.traverse(n=>{if(n===e)return;if(!(n instanceof l.LineSegments))return;const o=[];n.raycast(s,o),o.length>0&&o[0].distance<r&&(r=o[0].distance,i=t)})}return i}define(e,t){this.definitions.set(e,t)}_buildGroup(e,t){const s=this.definitions.get(e.blockName);if(!s)throw new Error(`BlockAnnotations: block "${e.blockName}" is not defined.`);const i=new l.Group;if(s.lines){const t=new l.LineSegments(s.lines,this._getMaterial(e.style));t.layers.set(1),t.userData.isDimension=!0,i.add(t)}if(s.mesh){const t=new l.Mesh(s.mesh,this._getMeshMaterial(e.style));t.layers.set(1),t.userData.isBlockMesh=!0,i.add(t)}return i}_onAfterPersist(e,t){t.position.set(e.position.x,0,e.position.z),t.rotation.set(0,e.rotation,0),t.scale.setScalar(e.scale)}_onDispose(){var e,t;for(const s of this.definitions.values())null==(e=s.lines)||e.dispose(),null==(t=s.mesh)||t.dispose();this.definitions.clear()}}function jz(e,t){const{position:s,direction:i}=e,{length:r}=t,n=new l.Vector3(s.x+i.x*r,0,s.z+i.z*r),o=new l.Vector3(i.x,0,i.z),a=t.lineTick(n,o,t.tickSize),h=[s.x,0,s.z,n.x,0,n.z];return new Float32Array([...h,...a])}function $z(e,t){return new l.Vector3(e.position.x+e.direction.x*t,0,e.position.z+e.direction.z*t)}function Wz(e,t){switch(t){case"percentage":return`${(100*e).toFixed(2)} %`;case"ratio":return 0===e?"1:∞":`1:${(1/e).toFixed(2)}`;case"degrees":return`${(180*Math.atan(e)/Math.PI).toFixed(2)}°`}}class Hz extends yz{constructor(e){super(e),t(this,"enabled",!0),this.styles.set("default",{lineTick:nz,meshTick:oz,tickSize:.4,length:3,color:0,textOffset:.1,fontSize:.45,format:"percentage"})}pickHandle(e,t,s){return null}_buildGroup(e,t){const s=new l.Group,i=jz(e,t),r=new l.BufferGeometry;r.setAttribute("position",new l.BufferAttribute(i,3));const n=new l.LineSegments(r,this._getMaterial(e.style));if(n.layers.set(1),n.userData.isDimension=!0,s.add(n),t.meshTick){const i=$z(e,t.length),r=t.meshTick(i,e.direction,t.tickSize),n=new l.BufferGeometry;n.setAttribute("position",new l.BufferAttribute(new Float32Array(r),3));const o=new l.Mesh(n,this._getMeshMaterial(e.style));o.layers.set(1),o.userData.isDimension=!0,s.add(o)}return s}}function qz(e,t){const s=t.x-e.x,i=t.z-e.z,r=Math.sqrt(s*s+i*i);if(0===r)return e.clone();const n=Math.atan2(i,s),o=Math.round(n/(Math.PI/4))*(Math.PI/4);return new l.Vector3(e.x+Math.cos(o)*r,0,e.z+Math.sin(o)*r)}function Xz(e,t){switch(e.kind){case"awaitingCenter":return"CLICK"===t.type?{kind:"awaitingRadius",center:t.point.clone(),cursor:null}:e;case"awaitingRadius":if("MOUSE_MOVE"===t.type)return{...e,cursor:t.point.clone()};if("CLICK"===t.type){const s=Math.max(.1,Math.abs(t.point.x-e.center.x)),i=Math.max(.1,Math.abs(t.point.z-e.center.z));return{kind:"awaitingElbow",center:e.center,halfW:s,halfH:i,cursor:null}}return"ESCAPE"===t.type?{kind:"awaitingCenter"}:e;case"awaitingElbow":return"MOUSE_MOVE"===t.type?{...e,cursor:t.point.clone()}:"CLICK"===t.type?{kind:"awaitingExtension",center:e.center,halfW:e.halfW,halfH:e.halfH,elbow:t.point.clone(),cursor:null}:"ESCAPE"===t.type?{kind:"awaitingCenter"}:e;case"awaitingExtension":return"MOUSE_MOVE"===t.type?{...e,cursor:qz(e.elbow,t.point)}:"CLICK"===t.type?{kind:"enteringText",center:e.center,halfW:e.halfW,halfH:e.halfH,elbow:e.elbow,extensionEnd:qz(e.elbow,t.point)}:"ESCAPE"===t.type?{kind:"awaitingCenter"}:e;case"enteringText":if("SUBMIT_TEXT"===t.type&&t.text.trim().length>0){return{kind:"committed",annotation:{uuid:l.MathUtils.generateUUID(),center:e.center.clone(),halfW:e.halfW,halfH:e.halfH,elbow:e.elbow.clone(),extensionEnd:e.extensionEnd.clone(),text:t.text.trim(),style:""}}}return"ESCAPE"===t.type?{kind:"awaitingCenter"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingCenter"}:e}}function Yz(e,t){const s=[];s.push(...t.enclosure.buildGeometry(e.center,e.halfW,e.halfH));const i=(new l.Vector3).subVectors(e.elbow,e.center),r=i.lengthSq()>1e-10?i.clone().normalize():new l.Vector3(1,0,0),n=t.enclosure.getAttachmentPoint(e.center,e.halfW,e.halfH,r);if(s.push(n.x,n.y,n.z,e.elbow.x,e.elbow.y,e.elbow.z,e.elbow.x,e.elbow.y,e.elbow.z,e.extensionEnd.x,e.extensionEnd.y,e.extensionEnd.z),t.lineTick){const i=(new l.Vector3).subVectors(e.extensionEnd,e.elbow);i.lengthSq()>1e-10&&s.push(...t.lineTick(e.extensionEnd,i.normalize(),t.tickSize))}return s}function Zz(e,t,s,i,r,n,o){const a="awaitingRadius"===e?n?Math.max(.05,Math.abs(n.x-t.x)):0:s,h="awaitingRadius"===e?n?Math.max(.05,Math.abs(n.z-t.z)):0:i;if(a<1e-10||h<1e-10)return[];const u=[];if(u.push(...o.enclosure.buildGeometry(t,a,h)),"awaitingRadius"===e)return u;const c="awaitingElbow"===e?n:r;if(!c)return u;const d=(new l.Vector3).subVectors(c,t),p=d.lengthSq()>1e-10?d.clone().normalize():new l.Vector3(1,0,0),m=o.enclosure.getAttachmentPoint(t,a,h,p);return"awaitingElbow"===e?(u.push(m.x,0,m.z,c.x,0,c.z),u):n?(u.push(m.x,0,m.z,r.x,0,r.z,r.x,0,r.z,n.x,0,n.z),u):u}const Qz={buildGeometry(e,t,s){const i=.25*Math.min(t,s),r=new l.Vector3(e.x-t,0,e.z-s),n=new l.Vector3(e.x+t,0,e.z-s),o=new l.Vector3(e.x+t,0,e.z+s),a=new l.Vector3(e.x-t,0,e.z+s),h=[[r,n,new l.Vector3(0,0,-1)],[n,o,new l.Vector3(1,0,0)],[o,a,new l.Vector3(0,0,1)],[a,r,new l.Vector3(-1,0,0)]],u=[];for(const[e,t,s]of h){const r=e.distanceTo(t),n=Math.max(1,Math.round(r/(2*i))),o=r/n,a=o/2,h=(new l.Vector3).subVectors(t,e).normalize();for(let t=0;t<n;t++){const i=e.clone().addScaledVector(h,(t+.5)*o),r=e.clone().addScaledVector(h,t*o),n=(new l.Vector3).subVectors(r,i);let c=r.clone();for(let e=1;e<=8;e++){const t=e/8*Math.PI,r=i.x+n.x*Math.cos(t)+s.x*a*Math.sin(t),o=i.z+n.z*Math.cos(t)+s.z*a*Math.sin(t),h=new l.Vector3(r,0,o);u.push(c.x,0,c.z,h.x,0,h.z),c=h}}}return u},getAttachmentPoint(e,t,s,i){const r=Math.abs(i.x)>1e-10?t/Math.abs(i.x):1/0,n=Math.abs(i.z)>1e-10?s/Math.abs(i.z):1/0,o=Math.min(r,n);return new l.Vector3(e.x+i.x*o,0,e.z+i.z*o)}},Kz={buildGeometry(e,t,s){const i=new l.Vector3(e.x-t,0,e.z-s),r=new l.Vector3(e.x+t,0,e.z-s),n=new l.Vector3(e.x+t,0,e.z+s),o=new l.Vector3(e.x-t,0,e.z+s);return[i.x,0,i.z,r.x,0,r.z,r.x,0,r.z,n.x,0,n.z,n.x,0,n.z,o.x,0,o.z,o.x,0,o.z,i.x,0,i.z]},getAttachmentPoint(e,t,s,i){const r=Math.abs(i.x)>1e-10?t/Math.abs(i.x):1/0,n=Math.abs(i.z)>1e-10?s/Math.abs(i.z):1/0,o=Math.min(r,n);return new l.Vector3(e.x+i.x*o,0,e.z+i.z*o)}},Jz={buildGeometry(e,t,s){const i=[];for(let r=0;r<32;r++){const n=r/32*Math.PI*2,o=(r+1)/32*Math.PI*2;i.push(e.x+Math.cos(n)*t,0,e.z+Math.sin(n)*s,e.x+Math.cos(o)*t,0,e.z+Math.sin(o)*s)}return i},getAttachmentPoint(e,t,s,i){const r=i.x/t,n=i.z/s,o=Math.sqrt(r*r+n*n),a=o>1e-10?1/o:t;return new l.Vector3(e.x+i.x*a,0,e.z+i.z*a)}};class ek extends yz{constructor(e){super(e),t(this,"enabled",!0),t(this,"machineState",{kind:"awaitingCenter"}),t(this,"onMachineStateChanged",new u),this.styles.set("default",{enclosure:Qz,lineTick:rz,tickSize:.4,color:22015,textOffset:.1,fontSize:.45})}pickHandle(e,t,s){return null}sendMachineEvent(e){const t=e.drawing??null;t&&(this._previewDrawing=t);const s=Xz(this.machineState,e);if(s!==this.machineState){if(this.machineState=s,this._updatePreview(),"committed"===s.kind){if(!this._previewDrawing)return console.warn("CalloutAnnotations: commit requires a drawing. Pass `drawing` on the first CLICK."),void this._resetMachine();s.annotation.style=this.activeStyle;const e=this._persist(this._previewDrawing,s.annotation);this.onCommit.trigger([e])}this.onMachineStateChanged.trigger(this.machineState),"committed"===s.kind&&this._resetMachine()}}_buildGroup(e,t){const s=new l.Group,i=Yz(e,t),r=new l.BufferGeometry;r.setAttribute("position",new l.BufferAttribute(new Float32Array(i),3));const n=new l.LineSegments(r,this._getMaterial(e.style));if(n.layers.set(1),n.userData.isDimension=!0,s.add(n),t.meshTick){const i=(new l.Vector3).subVectors(e.extensionEnd,e.elbow);if(i.lengthSq()>1e-10){i.normalize();const r=t.meshTick(e.extensionEnd,i,t.tickSize),n=new l.BufferGeometry;n.setAttribute("position",new l.BufferAttribute(new Float32Array(r),3));const o=new l.Mesh(n,this._getMeshMaterial(e.style));o.layers.set(1),o.userData.isMeshArrow=!0,s.add(o)}}return s}_updatePreview(){const e=this.machineState;if("awaitingRadius"!==e.kind&&"awaitingElbow"!==e.kind&&"awaitingExtension"!==e.kind)return void this._clearPreview();if(!this._previewDrawing)return;const t=this._resolveStyle(this.activeStyle),s=(()=>{switch(e.kind){case"awaitingRadius":return Zz("awaitingRadius",e.center,0,0,null,e.cursor,t);case"awaitingElbow":return Zz("awaitingElbow",e.center,e.halfW,e.halfH,null,e.cursor,t);case"awaitingExtension":return Zz("awaitingExtension",e.center,e.halfW,e.halfH,e.elbow,e.cursor,t)}})();if(0===s.length)return void this._clearPreview();const i=s.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==i){this._clearPreview();const e=new l.BufferGeometry;e.setAttribute("position",new l.BufferAttribute(new Float32Array(s),3)),this._previewObject=new l.LineSegments(e,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.frustumCulled=!1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const e=this._previewObject.geometry.attributes.position;e.set(s),e.needsUpdate=!0}}_resetMachine(){this.machineState={kind:"awaitingCenter"},this._clearPreview(),this._previewDrawing=null,this.onMachineStateChanged.trigger(this.machineState)}}const tk=class e extends d{constructor(s){super(s),t(this,"enabled",!0),t(this,"list",new a.DataMap),t(this,"systems",new a.DataMap),t(this,"onDisposed",new u),s.add(e.uuid,this),this.list.onBeforeDelete.add(({value:e})=>e.dispose()),this.systems.onBeforeDelete.add(({value:e})=>e.dispose())}use(e){if(this.systems.has(e))return this.systems.get(e);const t=new e(this.components);return this.systems.set(e,t),t}create(e){const t=new gz(this.components);t.world=e,e.scene.three.add(t.three),e.onDisposed.add(()=>this.list.delete(t.uuid));const s=e.camera;return s.three.layers.enable(1),s instanceof BO&&(s.threePersp.layers.enable(1),s.threeOrtho.layers.enable(1)),this.list.set(t.uuid,t),t}dispose(){this.list.clear(),this.systems.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}};t(tk,"uuid","5c7d3b9a-4e8f-4a2b-9c1d-0e3f2a5b7c8d");let sk=tk;const ik=[[16711680,1],[16776960,2],[65280,3],[65535,4],[255,5],[16711935,6],[16777215,7],[0,7]];function rk(e){const t=e>>16&255,s=e>>8&255,i=255&e;let r=7,n=1/0;for(const[e,o]of ik){const a=(t-(e>>16&255))**2+(s-(e>>8&255))**2+(i-(255&e))**2;a<n&&(n=a,r=o)}return r}class nk{constructor(){t(this,"_lines",[]),t(this,"_handleCounter",1)}p(e,t){return this._lines.push(String(e),String(t)),this}n(e,t,s=6){return this._lines.push(String(e),t.toFixed(s)),this}handle(){return(this._handleCounter++).toString(16).toUpperCase()}build(){return this._lines.join("\n")+"\n"}}class ok{constructor(e){t(this,"precision",2),t(this,"config",{trueColor:!1}),t(this,"_viewport",null),t(this,"_paperSlot",null),t(this,"_annotationLayers",new Map),t(this,"_systemExporters",new Map),this._components=e}registerSystemExporter(e,t){this._systemExporters.set(e,t)}export(e,t){const s=!!t,i=new nk,r=new Map;for(const t of e)for(const e of t.drawing.layers.values())r.has(e.name)||r.set(e.name,e);const n=[...r.values()],o=this._components.get(sk).systems.get(Gz),a=o?[...o.definitions.keys()]:[];this._writeHeader(i,s),this._writeTables(i,n,a),this._writeBlocks(i,o??null),i.p(0,"SECTION").p(2,"ENTITIES"),s&&t&&this._writePaperBorders(i,t);for(const r of e){r.drawing.three.traverse(e=>{e.userData.isDimension&&e.userData.annotationUuid&&this._annotationLayers.set(e.userData.annotationUuid,e.userData.layer??"0")});for(const e of r.viewports){if(this._viewport=e.viewport??null,s&&e.viewport){const s=e.viewport,i=t.heightMm-2*t.margin;this._paperSlot={x:e.x??0,y:i-(e.y??0),mmPerUnit:1e3/s.drawingScale,vpLeft:s.left,vpTop:s.top}}else this._paperSlot=null;this._writeViewportBorder(i),this._writeRawLines(i,r.drawing),this._writeLinearAnnotations(i,r.drawing),this._writeAngleAnnotations(i,r.drawing),this._writeLeaderAnnotations(i,r.drawing),this._writeSlopeAnnotations(i,r.drawing),this._writeCalloutAnnotations(i,r.drawing),this._writeBlockInsertions(i,r.drawing),this._writeCustomSystems(i,r.drawing)}this._annotationLayers.clear()}return i.p(0,"ENDSEC"),this._writeObjects(i),i.p(0,"EOF"),this._viewport=null,this._paperSlot=null,i.build()}_writeHeader(e,t){e.p(0,"SECTION").p(2,"HEADER"),e.p(9,"$ACADVER").p(1,this.config.trueColor?"AC1018":"AC1015"),e.p(9,"$INSUNITS").p(70,t?4:6),e.p(0,"ENDSEC")}_writeTables(e,t,s){e.p(0,"SECTION").p(2,"TABLES"),e.p(0,"TABLE").p(2,"VPORT").p(70,0).p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"LTYPE").p(70,1),e.p(0,"LTYPE").p(2,"CONTINUOUS").p(70,0).p(3,"Solid line").p(72,65).p(73,0).n(40,0),e.p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"LAYER").p(70,t.length);for(const s of t){const t=rk(s.material.color.getHex());e.p(0,"LAYER").p(2,s.name).p(70,0).p(62,t).p(6,"CONTINUOUS")}e.p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"STYLE").p(70,1),e.p(0,"STYLE").p(2,"STANDARD").p(70,0).n(40,0).n(41,1).n(50,0).p(71,0).n(42,.2).p(3,"txt").p(4,""),e.p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"VIEW").p(70,0).p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"UCS").p(70,0).p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"APPID").p(70,1),e.p(0,"APPID").p(2,"ACAD").p(70,0),e.p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"DIMSTYLE").p(70,0).p(0,"ENDTAB");const i=["*Model_Space","*Paper_Space",...s];e.p(0,"TABLE").p(2,"BLOCK_RECORD").p(70,i.length);for(const t of i)e.p(0,"BLOCK_RECORD").p(5,e.handle()).p(2,t);e.p(0,"ENDTAB"),e.p(0,"ENDSEC")}_writeBlocks(e,t){if(e.p(0,"SECTION").p(2,"BLOCKS"),this._writeBlock(e,"*Model_Space",null),this._writeBlock(e,"*Paper_Space",null),t)for(const[s,i]of t.definitions)this._writeBlock(e,s,i.lines??null);e.p(0,"ENDSEC")}_writeBlock(e,t,s){if(e.p(0,"BLOCK").p(5,e.handle()).p(8,"0").p(2,t).p(70,0).n(10,0).n(20,0).n(30,0).p(3,t).p(1,""),s){const t=this._viewport,i=this._paperSlot;this._viewport=null,this._paperSlot=null,this._writeGeoAsLines(e,s,"0"),this._viewport=t,this._paperSlot=i}e.p(0,"ENDBLK").p(5,e.handle()).p(8,"0")}_writeViewportBorder(e){if(!this._viewport)return;const t=this._viewport,s=this._tx(t.left),i=this._tx(t.right),r=this._ty(-t.bottom),n=this._ty(-t.top);this._writeRawLine(e,s,r,i,r,"0",7),this._writeRawLine(e,i,r,i,n,"0",7),this._writeRawLine(e,i,n,s,n,"0",7),this._writeRawLine(e,s,n,s,r,"0",7)}_writePaperBorders(e,t){const{margin:s,widthMm:i,heightMm:r}=t,n=i-2*s,o=r-2*s;this._writeRawLine(e,0,0,n,0,"0",7),this._writeRawLine(e,n,0,n,o,"0",7),this._writeRawLine(e,n,o,0,o,"0",7),this._writeRawLine(e,0,o,0,0,"0",7),this._writeRawLine(e,-s,-s,n+s,-s,"0",7),this._writeRawLine(e,n+s,-s,n+s,o+s,"0",7),this._writeRawLine(e,n+s,o+s,-s,o+s,"0",7),this._writeRawLine(e,-s,o+s,-s,-s,"0",7)}_writeObjects(e){e.p(0,"SECTION").p(2,"OBJECTS"),e.p(0,"DICTIONARY").p(5,e.handle()).p(330,0).p(100,"AcDbRootDictionary"),e.p(0,"ENDSEC")}_writeRawLines(e,t){t.three.traverse(t=>{var s;if(!(t instanceof l.LineSegments))return;if(t.userData.isDimension)return;if(null==(s=t.parent)?void 0:s.userData.blockUuid)return;if(!t.visible)return;const i=t.userData.layer??"0",r=t.material.color.getHex();this._writeGeoAsLines(e,t.geometry,i,rk(r),r)})}_writeLinearAnnotations(e,t){var s;const i=this._components.get(sk).systems.get(Sz);if(i)for(const[,r]of t.annotations.getBySystem(i)){const n=i.styles.get(r.style)??i.styles.get("default"),o=rk(n.color),a=this._annotationLayers.get(r.uuid)??"0";if(!1===(null==(s=t.layers.get(a))?void 0:s.visible))continue;const h=vz(r,n);if(!this._fullyInViewport(this._bboxFromPositions(h)))continue;if(this._writePairsAsLines(e,h,a,o,n.color),n.meshTick)for(const{tip:t,dir:s}of wz(r))this._writeMeshTriangles(e,n.meshTick(t,s,n.tickSize),a,o,n.color);const u=(new l.Vector3).subVectors(r.pointB,r.pointA),c=new l.Vector3(-u.z,0,u.x).normalize(),d=r.offset>=0?1:-1,p=r.pointA.clone().addScaledVector(c,r.offset),m=r.pointB.clone().addScaledVector(c,r.offset),f=p.clone().add(m).multiplyScalar(.5).addScaledVector(c,(n.textOffset+.5*n.fontSize)*d),g=n.unit??{factor:1,suffix:"m"},y=`${(r.pointA.distanceTo(r.pointB)*g.factor).toFixed(this.precision)} ${g.suffix}`;this._writeText(e,y,f.x,f.z,n.fontSize,a,o,this._textAngle(u.x,u.z),1,2,n.color)}}_writeAngleAnnotations(e,t){var s;const i=this._components.get(sk).systems.get(Lz);if(i)for(const[,r]of t.annotations.getBySystem(i)){const n=i.styles.get(r.style)??i.styles.get("default"),o=rk(n.color),a=this._annotationLayers.get(r.uuid)??"0";if(!1===(null==(s=t.layers.get(a))?void 0:s.visible))continue;const h=Iz(r,n);if(!this._fullyInViewport(this._bboxFromPositions(h)))continue;if(this._writePairsAsLines(e,h,a,o,n.color),n.meshTick)for(const{tip:t,dir:s}of Cz(r))this._writeMeshTriangles(e,n.meshTick(t,s,n.tickSize),a,o,n.color);const u=Pz(r),c=r.arcRadius+n.textOffset,d=r.vertex.x+Math.cos(u)*c,p=r.vertex.z+Math.sin(u)*c,m=l.MathUtils.radToDeg(Rz(r));this._writeText(e,`${m.toFixed(this.precision)}°`,d,p,n.fontSize,a,o,0,1,0,n.color)}}_writeLeaderAnnotations(e,t){var s;const i=this._components.get(sk).systems.get(Uz);if(i)for(const[,r]of t.annotations.getBySystem(i)){const n=i.styles.get(r.style)??i.styles.get("default"),o=rk(n.color),a=this._annotationLayers.get(r.uuid)??"0";if(!1===(null==(s=t.layers.get(a))?void 0:s.visible))continue;const h=zz(r,n);if(!this._fullyInViewport(this._bboxFromPositions(h)))continue;if(this._writePairsAsLines(e,h,a,o,n.color),n.meshTick){const t=(new l.Vector3).subVectors(r.arrowTip,r.elbow);t.lengthSq()>1e-10&&this._writeMeshTriangles(e,n.meshTick(r.arrowTip,t.normalize(),n.tickSize),a,o,n.color)}const u=(new l.Vector3).subVectors(r.extensionEnd,r.elbow).setY(0).normalize(),c=u.x<-.1?2:u.x>.1?0:1,d=1===c?.5*n.fontSize:0,p=r.extensionEnd.clone().addScaledVector(u,n.textOffset+d);this._writeText(e,r.text,p.x,p.z,n.fontSize,a,o,0,c,2,n.color)}}_writeSlopeAnnotations(e,t){var s;const i=this._components.get(sk).systems.get(Hz);if(i)for(const[,r]of t.annotations.getBySystem(i)){const n=i.styles.get(r.style)??i.styles.get("default"),o=rk(n.color),a=this._annotationLayers.get(r.uuid)??"0";if(!1===(null==(s=t.layers.get(a))?void 0:s.visible))continue;const h=jz(r,n);if(!this._fullyInViewport(this._bboxFromPositions(h)))continue;if(this._writePairsAsLines(e,h,a,o,n.color),n.meshTick){const t=$z(r,n.length);this._writeMeshTriangles(e,n.meshTick(t,r.direction,n.tickSize),a,o,n.color)}const u=new l.Vector3(r.position.x+r.direction.x*n.length,0,r.position.z+r.direction.z*n.length),c=r.position.clone().add(u).multiplyScalar(.5).addScaledVector(new l.Vector3(-r.direction.z,0,r.direction.x),n.textOffset+n.fontSize);this._writeText(e,Wz(r.slope,n.format),c.x,c.z,n.fontSize,a,o,this._textAngle(r.direction.x,r.direction.z),1,0,n.color)}}_writeCalloutAnnotations(e,t){var s;const i=this._components.get(sk).systems.get(ek);if(i)for(const[,r]of t.annotations.getBySystem(i)){const n=i.styles.get(r.style)??i.styles.get("default"),o=rk(n.color),a=this._annotationLayers.get(r.uuid)??"0";if(!1===(null==(s=t.layers.get(a))?void 0:s.visible))continue;const h=Yz(r,n);if(!this._fullyInViewport(this._bboxFromPositions(h)))continue;if(this._writePairsAsLines(e,h,a,o,n.color),n.meshTick){const t=(new l.Vector3).subVectors(r.extensionEnd,r.elbow);t.lengthSq()>1e-10&&this._writeMeshTriangles(e,n.meshTick(r.extensionEnd,t.normalize(),n.tickSize),a,o,n.color)}const u=(new l.Vector3).subVectors(r.extensionEnd,r.elbow).setY(0).normalize(),c=u.x<-.1?2:u.x>.1?0:1,d=1===c?.5*n.fontSize:0,p=r.extensionEnd.clone().addScaledVector(u,n.textOffset+d);this._writeText(e,r.text,p.x,p.z,n.fontSize,a,o,0,c,2,n.color)}}_writeBlockInsertions(e,t){const s=this._components.get(sk).systems.get(Gz);if(s)for(const[,i]of t.annotations.getBySystem(s)){if(!this._inViewport(i.position.x,i.position.z))continue;const t=s.styles.get(i.style)??s.styles.get("default"),r=rk(t.color),n=-l.MathUtils.radToDeg(i.rotation),o=i.scale*this._scale();e.p(0,"INSERT").p(5,e.handle()).p(8,"0").p(62,r),this._emitTrueColor(e,t.color),e.p(2,i.blockName).n(10,this._tx(i.position.x)).n(20,this._ty(i.position.z)).n(30,0).n(41,o).n(42,o).n(43,o).n(50,n)}}_writeGeoAsLines(e,t,s,i=7,r){const n=t.attributes.position;if(n)for(let t=0;t+1<n.count;t+=2){const o=this._clipSegment(new l.Vector3(n.getX(t),0,n.getZ(t)),new l.Vector3(n.getX(t+1),0,n.getZ(t+1)));o&&this._writeLine(e,o.start.x,o.start.z,o.end.x,o.end.z,s,i,r)}}_writePairsAsLines(e,t,s,i=7,r){for(let n=0;n+5<t.length;n+=6){const o=this._clipSegment(new l.Vector3(t[n],0,t[n+2]),new l.Vector3(t[n+3],0,t[n+5]));o&&this._writeLine(e,o.start.x,o.start.z,o.end.x,o.end.z,s,i,r)}}_emitTrueColor(e,t){this.config.trueColor&&void 0!==t&&e.p(420,t)}_writeLine(e,t,s,i,r,n,o,a){e.p(0,"LINE").p(5,e.handle()).p(8,n).p(62,o),this._emitTrueColor(e,a),e.n(10,this._tx(t)).n(20,this._ty(s)).n(30,0).n(11,this._tx(i)).n(21,this._ty(r)).n(31,0)}_writeRawLine(e,t,s,i,r,n,o){e.p(0,"LINE").p(5,e.handle()).p(8,n).p(62,o).n(10,t).n(20,s).n(30,0).n(11,i).n(21,r).n(31,0)}_writeSolid(e,t,s,i,r,n,o,a,l,h){e.p(0,"SOLID").p(5,e.handle()).p(8,a).p(62,l),this._emitTrueColor(e,h),e.n(10,this._tx(t)).n(20,this._ty(s)).n(30,0).n(11,this._tx(i)).n(21,this._ty(r)).n(31,0).n(12,this._tx(n)).n(22,this._ty(o)).n(32,0).n(13,this._tx(n)).n(23,this._ty(o)).n(33,0)}_writeMeshTriangles(e,t,s,i,r){for(let n=0;n+8<t.length;n+=9)this._writeSolid(e,t[n],t[n+2],t[n+3],t[n+5],t[n+6],t[n+8],s,i,r)}_writeText(e,t,s,i,r,n,o,a=0,l=0,h=0,u){const c=this._tx(s),d=this._ty(i);e.p(0,"TEXT").p(5,e.handle()).p(8,n).p(62,o),this._emitTrueColor(e,u),e.n(10,c).n(20,d).n(30,0).n(40,r*this._scale()).n(50,a).p(1,t),0===l&&0===h||(0!==l&&e.p(72,l),0!==h&&e.p(73,h),e.n(11,c).n(21,d).n(31,0))}_tx(e){return this._paperSlot?this._paperSlot.x+(e-this._paperSlot.vpLeft)*this._paperSlot.mmPerUnit:this._viewport?e-this._viewport.left:e}_ty(e){return this._paperSlot?this._paperSlot.y-(e+this._paperSlot.vpTop)*this._paperSlot.mmPerUnit:this._viewport?-e-this._viewport.bottom:-e}_scale(){return this._paperSlot?this._paperSlot.mmPerUnit:1}_clipSegment(e,t){return this._viewport?this._viewport.clipLine(new l.Line3(e,t)):new l.Line3(e,t)}_inViewport(e,t){return!this._viewport||this._viewport.bbox.containsPoint(new l.Vector3(e,0,t))}_bboxFromPositions(e){const t=new l.Box3;for(let s=0;s+2<e.length;s+=3)t.expandByPoint(new l.Vector3(e[s],0,e[s+2]));return t}_fullyInViewport(e){return!this._viewport||this._viewport.bbox.containsBox(e)}_textAngle(e,t){let s=Math.atan2(-t,e);return(s>Math.PI/2||s<=-Math.PI/2)&&(s+=Math.PI),l.MathUtils.radToDeg(s)}_writeCustomSystems(e,t){if(0===this._systemExporters.size)return;const s=this._makeContext(e);for(const[e,t]of this._systemExporters){const i=this._components.get(sk).systems.get(e);i&&t(i,s)}}_makeContext(e){return{writeLine:(t,s,i,r,n="0",o=7)=>{this._writeLine(e,t,s,i,r,n,o)},writePairs:(t,s="0",i=7)=>{this._writePairsAsLines(e,t,s,i)},writeMeshTriangles:(t,s="0",i=7)=>{this._writeMeshTriangles(e,t,s,i)},writeText:(t,s,i,r,n={})=>{this._writeText(e,t,s,i,r,n.layer??"0",n.aciColor??7,n.rotDeg??0,n.hAlign??0)},hexToAci:rk,textAngle:(e,t)=>this._textAngle(e,t)}}}const ak=class e extends d{constructor(s){super(s),t(this,"enabled",!0),t(this,"exporter",new ok(this.components)),s.add(e.uuid,this)}};t(ak,"uuid","e9a2c3d4-5f67-4b89-a012-1c3d5e7f9b2a");let lk=ak;exports.AngleAnnotations=Lz,exports.AnnotationSystem=yz,exports.ArrowTick=(e,t,s)=>{const i=new l.Vector3(-t.z,0,t.x),r=e.x-t.x*s+i.x*s*.4,n=e.z-t.z*s+i.z*s*.4,o=e.x-t.x*s-i.x*s*.4,a=e.z-t.z*s-i.z*s*.4;return[e.x,e.y,e.z,r,e.y,n,e.x,e.y,e.z,o,e.y,a,r,e.y,n,o,e.y,a]},exports.AsyncEvent=class{constructor(){t(this,"enabled",!0),t(this,"trigger",async e=>{if(!this.enabled)return;const t=this.handlers.slice(0);for(const s of t)await s(e)}),t(this,"handlers",[])}add(e){this.handlers.push(e)}remove(e){this.handlers=this.handlers.filter(t=>t!==e)}reset(){this.handlers.length=0}},exports.BCFTopics=$O,exports.BCFTopicsConfigManager=GO,exports.Base=c,exports.BaseCamera=m,exports.BaseRenderer=f,exports.BaseScene=x,exports.BaseWorldItem=p,exports.BlockAnnotations=Gz,exports.BoundingBoxer=tO,exports.CalloutAnnotations=ek,exports.CircleEnclosure=Jz,exports.Classifier=oO,exports.Clipper=NV,exports.CloudEnclosure=Qz,exports.Comment=VO,exports.Component=d,exports.Components=NO,exports.ConfigManager=Ge,exports.Configurator=ke,exports.ControlsUtils=ze,exports.DataMap=Ve,exports.DataSet=b,exports.DiagonalTick=iz,exports.Disposer=y,exports.DotTick=(e,t,s)=>{const i=.4*s,r=[];for(let t=0;t<12;t++){const s=t/12*Math.PI*2,n=(t+1)/12*Math.PI*2;r.push(e.x+Math.cos(s)*i,e.y,e.z+Math.sin(s)*i,e.x+Math.cos(n)*i,e.y,e.z+Math.sin(n)*i)}return r},exports.DrawingAnnotations=az,exports.DrawingLayers=lz,exports.DrawingSystem=yz,exports.DrawingViewport=cz,exports.DrawingViewportHelper=uz,exports.DrawingViewports=dz,exports.DxfExporter=ok,exports.DxfManager=lk,exports.EdgeProjector=XF,exports.Event=u,exports.EventManager=class{constructor(){t(this,"list",new Set)}add(e){for(const t of e)this.list.add(t)}remove(e){for(const t of e)this.list.delete(t)}set(e){for(const t of this.list)t.enabled=e}reset(){for(const e of this.list)e.reset()}},exports.FastModelPicker=aO,exports.FastModelPickers=hO,exports.FilledArrowTick=oz,exports.FilledCircleTick=(e,t,s)=>{const i=.4*s,r=[];for(let t=0;t<16;t++){const s=t/16*Math.PI*2,n=(t+1)/16*Math.PI*2;r.push(e.x,e.y,e.z,e.x+Math.cos(s)*i,e.y,e.z+Math.sin(s)*i,e.x+Math.cos(n)*i,e.y,e.z+Math.sin(n)*i)}return r},exports.FilledSquareTick=(e,t,s)=>{const i=new l.Vector3(-t.z,0,t.x),r=.4*s,n=e.clone().addScaledVector(t,r).addScaledVector(i,r),o=e.clone().addScaledVector(t,r).addScaledVector(i,-r),a=e.clone().addScaledVector(t,-r).addScaledVector(i,-r),h=e.clone().addScaledVector(t,-r).addScaledVector(i,r);return[n.x,n.y,n.z,o.x,o.y,o.z,a.x,a.y,a.z,n.x,n.y,n.z,a.x,a.y,a.z,h.x,h.y,h.z]},exports.FinderQuery=sO,exports.FirstPersonMode=EO,exports.FragmentsManager=ji,exports.Grids=MO,exports.Hider=JF,exports.IDSAttribute=zV,exports.IDSClassification=kV,exports.IDSEntity=UV,exports.IDSFacet=OV,exports.IDSMaterial=jV,exports.IDSPartOf=$V,exports.IDSProperty=GV,exports.IDSSpecification=WV,exports.IDSSpecifications=ez,exports.IfcFragmentSettings=YF,exports.IfcLoader=QF,exports.ItemsFinder=rO,exports.LeaderAnnotations=Uz,exports.LinearAnnotations=Sz,exports.MeasurementUtils=sz,exports.ModelIdMapUtils=Oe,exports.Mouse=je,exports.NoTick=nz,exports.OpenArrowTick=rz,exports.OrbitMode=CO,exports.OrthoPerspectiveCamera=BO,exports.PlanMode=RO,exports.ProjectionManager=PO,exports.Raycasters=dO,exports.RectEnclosure=Kz,exports.RendererMode=xO,exports.ShadowedScene=class extends yO{constructor(){super(...arguments),t(this,"_distanceRenderer"),t(this,"autoBias",!0),t(this,"_defaultShadowConfig",{cascade:1,resolution:512}),t(this,"_lightsWithShadow",new Map),t(this,"_isComputingShadows",!1),t(this,"_shadowsEnabled",!0),t(this,"_bias",0),t(this,"recomputeShadows",e=>{if(!this._shadowsEnabled)return;this.autoBias&&(this.bias=-.005);if(e*=1.5,!this.currentWorld)throw new Error("A world needs to be assigned to the scene before computing shadows!");if(!this._lightsWithShadow.size)throw new Error("No shadows found!");const t=this.currentWorld.camera.three;if(!(t instanceof l.PerspectiveCamera||t instanceof l.OrthographicCamera))throw new Error("Invalid camera type!");const s=new l.Vector3;t.getWorldDirection(s);let i=e;const r=new l.Vector3;r.copy(this.config.directionalLight.position),r.normalize();for(const[e,n]of this._lightsWithShadow){const o=this.directionalLights.get(n);if(!o)throw new Error("Light not found.");const a=new l.Vector3;a.copy(s);const h=e===this._lightsWithShadow.size-1,u=h?i/2:2*i/3;a.multiplyScalar(u),a.add(t.position);const c=i-u,d=new l.Vector3;d.copy(r),d.multiplyScalar(c),o.target.position.copy(a),o.position.copy(a),o.position.add(d),o.shadow.camera.right=c,o.shadow.camera.left=-c,o.shadow.camera.top=c,o.shadow.camera.bottom=-c,o.shadow.camera.far=2*c,o.shadow.camera.updateProjectionMatrix(),o.shadow.camera.updateMatrix(),h||(i/=3)}this._isComputingShadows=!1})}get bias(){return this._bias}set bias(e){this._bias=e;for(const[,t]of this._lightsWithShadow){const s=this.directionalLights.get(t);s&&(s.shadow.bias=e)}}get shadowsEnabled(){return this._shadowsEnabled}set shadowsEnabled(e){this._shadowsEnabled=e;for(const[,t]of this.directionalLights)t.castShadow=e}get distanceRenderer(){if(!this._distanceRenderer)throw new Error("You must set up this component before accessing the distance renderer!");return this._distanceRenderer}setup(e){super.setup(e);const t={...this._defaultConfig,...this._defaultShadowConfig,...e};if(t.cascade<=0)throw new Error("Config.shadows.cascade must be a natural number greater than 0!");if(t.cascade>1)throw new Error("Multiple shadows not supported yet!");if(!this.currentWorld)throw new Error("A world needs to be assigned to the scene before setting it up!");for(const[,e]of this.directionalLights)e.target.removeFromParent(),e.removeFromParent(),e.dispose();this.directionalLights.clear(),this._distanceRenderer||(this._distanceRenderer=new FV(this.components,this.currentWorld),this._distanceRenderer.onDistanceComputed.add(this.recomputeShadows)),this._lightsWithShadow.clear();for(let e=0;e<t.cascade;e++){const s=new l.DirectionalLight;s.intensity=this.config.directionalLight.intensity,s.color=this.config.directionalLight.color,s.position.copy(this.config.directionalLight.position),s.shadow.mapSize.width=t.resolution,s.shadow.mapSize.height=t.resolution,this.three.add(s,s.target),this.directionalLights.set(s.uuid,s),this._lightsWithShadow.set(e,s.uuid),s.castShadow=!0,s.shadow.bias=this._bias}}dispose(){super.dispose(),this._distanceRenderer&&this._distanceRenderer.dispose(),this._lightsWithShadow.clear()}async updateShadows(){!this._isComputingShadows&&this._shadowsEnabled&&(this._isComputingShadows=!0,await this.distanceRenderer.compute())}},exports.SimpleCamera=bO,exports.SimpleGrid=TO,exports.SimpleGridConfigManager=vO,exports.SimplePlane=SV,exports.SimpleRaycaster=uO,exports.SimpleRenderer=class extends f{constructor(e,s,i){super(e),t(this,"enabled",!0),t(this,"container"),t(this,"three"),t(this,"mode",1),t(this,"needsUpdate",!1),t(this,"_canvas"),t(this,"_parameters"),t(this,"_resizeObserver",null),t(this,"onContainerUpdated",new u),t(this,"_resizing",!1),t(this,"resize",e=>{if(this._resizing)return;this._resizing=!0,this.onContainerUpdated.trigger();const t=e?e.x:this.container.clientWidth,s=e?e.y:this.container.clientHeight;this.three.setSize(t,s),this.onResize.trigger(new l.Vector2(t,s)),this._resizing=!1}),t(this,"resizeEvent",()=>{this.resize()}),t(this,"onContextLost",e=>{e.preventDefault(),this.enabled=!1}),t(this,"onContextBack",()=>{this.three.setRenderTarget(null),this.three.dispose(),this.three=new l.WebGLRenderer({canvas:this._canvas,antialias:!0,alpha:!0,...this._parameters}),this.enabled=!0}),this.container=s,this._parameters=i,this.three=new l.WebGLRenderer({antialias:!0,alpha:!0,...i}),this.three.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.setupRenderer(),this.setupEvents(!0),this.resize(),this._canvas=this.three.domElement;const r=this.three.getContext(),{canvas:n}=r;n.addEventListener("webglcontextlost",this.onContextLost,!1),n.addEventListener("webglcontextrestored",this.onContextBack,!1)}update(){if(!this.enabled||!this.currentWorld)return;if(0===this.mode&&!this.needsUpdate)return;this.needsUpdate=!1,this.onBeforeUpdate.trigger(this);const e=this.currentWorld.scene.three,t=this.currentWorld.camera.three;this.three.render(e,t),this.onAfterUpdate.trigger(this)}dispose(){this.enabled=!1,this.setupEvents(!1),this.three.domElement.remove(),this.three.forceContextLoss(),this.three.dispose(),this.onResize.reset(),this.onAfterUpdate.reset(),this.onBeforeUpdate.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}getSize(){return new l.Vector2(this.three.domElement.clientWidth,this.three.domElement.clientHeight)}setupEvents(e){const t=this.three.domElement.parentElement;if(!t)throw new Error("This renderer needs to have an HTML container!");this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),window.removeEventListener("resize",this.resizeEvent),e&&(this._resizeObserver=new ResizeObserver(this.resizeEvent),this._resizeObserver.observe(t),window.addEventListener("resize",this.resizeEvent))}setupRenderer(){this.three.localClippingEnabled=!0,this.container&&this.container.appendChild(this.three.domElement),this.onContainerUpdated.trigger()}},exports.SimpleScene=yO,exports.SimpleSceneConfigManager=gO,exports.SimpleWorld=pO,exports.SlopeAnnotations=Hz,exports.TechnicalDrawing=gz,exports.TechnicalDrawingHelper=mz,exports.TechnicalDrawings=sk,exports.Topic=kO,exports.UUID=w,exports.Units={m:{factor:1,suffix:"m"},cm:{factor:100,suffix:"cm"},mm:{factor:1e3,suffix:"mm"},ft:{factor:3.28084,suffix:"ft"},in:{factor:39.3701,suffix:"in"}},exports.VertexPicker=class extends d{constructor(e,s){super(e),t(this,"onDisposed",new u),t(this,"onVertexFound",new u),t(this,"onVertexLost",new u),t(this,"onEnabled",new u),t(this,"components"),t(this,"workingPlane",null),t(this,"_pickedPoint",null),t(this,"_config"),t(this,"_enabled",!1),this.components=e,this.config={snapDistance:.25,showOnlyVertex:!1,...s},this.enabled=!1}set enabled(e){this._enabled=e,e||(this._pickedPoint=null),this.onEnabled.trigger(e)}get enabled(){return this._enabled}set config(e){this._config={...this._config,...e}}get config(){return this._config}dispose(){this.onVertexFound.reset(),this.onVertexLost.reset(),this.components=null,this.onDisposed.trigger(),this.onDisposed.reset()}async get(e){if(!this.enabled)return this._pickedPoint;const t=this.components.get(dO).get(e),s=await t.castRay();if(!s)return null!==this._pickedPoint&&(this.onVertexLost.trigger(),this._pickedPoint=null),this._pickedPoint;const i=s.point;return null!==this._pickedPoint&&this._pickedPoint.equals(i)||(this._pickedPoint=i.clone(),this.onVertexFound.trigger(this._pickedPoint)),this._pickedPoint}},exports.View=BV,exports.Viewpoint=EV,exports.Viewpoints=PV,exports.Views=DV,exports.Worlds=wO,exports.XML=Fe,exports.angleDimensionMachine=Ez,exports.buildAnglePositions=Iz,exports.buildAnglePreviewPositions=Dz,exports.buildCalloutPositions=Yz,exports.buildCalloutPreviewPositions=Zz,exports.buildDimensionPositions=vz,exports.buildDimensions=bz,exports.buildLeaderPositions=zz,exports.buildLeaderPreviewPositions=kz,exports.buildPreviewPositions=Tz,exports.buildSlopePositions=jz,exports.calloutAnnotationMachine=Xz,exports.computeAlignmentMatrix=fz,exports.computeAngle=Rz,exports.computeBisectorAngle=Pz,exports.computeOffset=xz,exports.extensionsImporter=UO,exports.formatSlope=Wz,exports.getAngleTickEndpoints=Cz,exports.getDimensionTickEndpoints=wz,exports.getSlopeTip=$z,exports.leaderAnnotationMachine=Oz,exports.linearDimensionMachine=_z;